25 KiB
AGENTS.md — re3 operating manual for coding agents
This file is the whole onboarding for an autonomous agent (or a human) who has to change this repository with zero prior context. It is deliberately concrete: every command and path below was executed/verified against this tree.
Read it completely before editing anything. Then read CODING_STYLE.md and the
Contributing section of README.md — those two documents are the policy of
record; this file only summarises and operationalises them.
AGENTS.local.md (git-ignored) may override anything here on a specific machine;
see §9.
1. What this repository is
re3 is the reverse-engineered source code of Grand Theft Auto III, reconstructed function by function from the PC binaries and made to build as a standalone game.
master(this branch) — GTA III (GTA_VERSION GTA3_PC_11insrc/core/config.h).miami— reVC, the Vice City port (GTAVC_PC_11). Same engine layout, different game.lcs— reLCS, Liberty City Stories (work in progress, much less complete).
The Gitea remote currently hosts master only. The local clone carries
remote-tracking refs origin/miami and origin/lcs (both with full objects, so
local checkouts and builds of those trees work). Getting miami/lcs onto the
remote is a tracked one-time task (tracker issue #1) and needs an authenticated
push this environment does not have; treat the remote as master-only until then.
Do not assume master's files match the other branches.
No license. From README.md:
We don't feel like we're in a position to give this code a license. The code should only be used for educational, documentation and modding purposes. We do not encourage piracy or commercial use. Please keep derivate work open source and give proper credit.
Provenance discipline is the central rule. The project only exists because the
code can be compared to the original binaries. From README.md's Contributing
section:
As long as it's not linux/cross-platform skeleton/compatibility layer, all of the code on the repo that's not behind a preprocessor condition(like FIX_BUGS) are completely reversed code from original binaries.
We don't accept custom codes, as long as it's not wrapped via preprocessor conditions, or it's linux/cross-platform skeleton/compatibility layer.
Practical consequence:
- Code outside preprocessor guards must look like what Rockstar would have shipped, i.e. "which code would produce this assembly".
- Behavioural additions/fixes belong behind
FIX_BUGS/FIX_BUGS_64, or inside a platform skeleton (src/skel/), or insrc/extras/(explicitly non-reversed). - Accepted PR shapes (README): features that exist in at least one GTA, game/UI/UX
bug fixes (original-behaviour fixes behind
FIX_BUGS), platform-specific or unreversed code, accuracy/understandability improvements, new skeletons or compatibility layers, maintainability work.
Config switches live in src/core/config.h. MASTER implies FINAL; MASTER
builds drop the debug menu and version text. VALIDATE_SAVE_SIZE and DEBUGMENU
are only defined in non-MASTER builds.
2. Hard rules
Quoted/derived from CODING_STYLE.md (read the whole file — it is short):
- Indent with TABS.
- Braces: same line for control statements, next line after function
definitions and structs/classes,
elseon the same line as the closing brace, no braces around single statements, function return type on its own line. The two accepted shapes are shown at the top ofCODING_STYLE.md; anything closer to Allman/Whitesmiths is "heavily discouraged". - Types:
int8,uint8,int16,uint16,int32,uint32,float,bool(typedef'd insrc/core/common.h;src/extras/re3_inttypes.hadds thePRI*printf macros for them).- "don't use types like
__int16, we haveint16for that" - "don't use
unsigned, we have typedefs for that" - "don't use
charfor anything but actual characters, useint8,uint8orbool" - "don't even think about using win32 types (
BYTE,WORD, &c.) unless you're writing win32 specific code"
- "don't use types like
- Pointers:
int *ptr;, neverint* ptr;. - No magic numbers: "Even if you don't know the exact meaning it's better to
call something
FOOBAR_TYPE_4than just4". - Naming: hungarian-ish,
m_members,ms_statics,ffloat,i/nint,bbool,aarray; nodwforDWORD("we're not programming win32"). - "Don't just copy paste code from IDA, make it look nice" and "try to make the code look as if R could have written it"*.
Language standard, from README.md:
Do not use features from C++11 or later.
The build currently compiles with CXX_STANDARD 11 (src/CMakeLists.txt), but that
is a build-setting detail, not permission: write C++98-style code in reversed
sections. nullptr, auto, range-for, override, lambdas, std:: containers
etc. do not appear in reversed code. The only existing exceptions in the tree are
the non-reversed/back-end parts: src/extras/ini.h, the INI settings code in
src/core/re3.cpp (behind LOAD_INI_SETTINGS/CUSTOM_FRONTEND_OPTIONS), and the
OpenAL backend (src/audio/oal/). The formal standard policy is an open decision
(Gitea milestone M4: Toolchain & language modernization, issue "Ratify C++
language-standard policy"); until it lands, the C++98 rule above is the operative
one.
Also: build warnings are expected and must not become errors; the CI workflow
deliberately builds without -Werror.
3. Build and verify (the gate)
A task is not done until the documented build passes. Run it before every commit. Warnings are fine; a non-zero exit is not.
3.1 Verified container recipe
The reference environment is a podman container re3dev
(docker.io/library/ubuntu:24.04, gcc 13.3, cmake 3.28, ninja 1.11). Create it
once:
podman run -dit --name re3dev --security-opt label=disable \
-v /var/home/jchroback/Projects/re3:/src:ro \
docker.io/library/ubuntu:24.04 sleep infinity
podman exec re3dev sh -c 'apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends build-essential cmake ninja-build pkg-config git ca-certificates libglfw3-dev libopenal-dev libsndfile1-dev libmpg123-dev libgl-dev'
--security-opt label=disable is required on this host: SELinux is Enforcing, and
a plain :ro bind mount otherwise fails to be readable by the container. The source
mount is read-only on purpose — builds go to a directory inside the container.
Configure and build (the same two commands are the whole gate):
podman exec re3dev cmake -S /src -B /build -G Ninja \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DRE3_AUDIO=OAL \
-DRE3_VENDORED_LIBRW=True \
-DLIBRW_PLATFORM=GL3 \
-DLIBRW_GL3_GFXLIB=GLFW
podman exec re3dev cmake --build /build --parallel 12
Expected on this machine (verified): configure succeeds and prints
Building re3 GIT SHA1: <hash of HEAD>; build compiles 296 Ninja targets,
prints many -Wmaybe-uninitialized-style warnings, exits 0 in roughly
20 s on 12 cores, and produces /build/src/re3, a ~24 MiB (25 MB) ELF64
executable.
To prove a clean tree still builds (and to avoid stale objects), use a fresh
build directory, e.g. -B /build-verify, then build it.
3.2 Without the container
On any Linux box with the packages above installed, the identical invocation works from the repo root:
cmake -S . -B build -G Ninja \
-DCMAKE_BUILD_TYPE=RelWithDebInfo -DRE3_AUDIO=OAL \
-DRE3_VENDORED_LIBRW=True -DLIBRW_PLATFORM=GL3 -DLIBRW_GL3_GFXLIB=GLFW
cmake --build build --parallel "$(nproc)"
Dependency list and flags match .gitea/workflows/linux.yml (the CI definition).
RE3_AUDIO=OAL is the only audio backend on Linux (MSS is Windows-only, and needs
the Miles SDK). LIBRW_GL3_GFXLIB accepts GLFW or SDL2, but SDL2 is only a
librw option — re3 itself has no SDL skeleton in src/skel/.
Prerequisites: clone with --recursive (librw/ogg/opus/opusfile are submodules) and
keep .git available — CMake calls get_git_head_revision() and embeds the short
SHA via configure_file.
3.3 Running the game (not part of the gate)
The repository contains no game assets. To actually run, you need a legally
owned GTA III installation: put data/, models/, audio/, TEXT/, movies/
next to the built binary, then overlay the contents of gamefiles/ (updated menu
textures, translations, PARTICLE.CFG, the extra freeroam script, the controller
database) as the README's installation step describes ("Extract the downloaded zip
over your GTA 3 directory and run re3"). Without assets the binary only gets as far
as failing to load data. Automated verification therefore stops at the build;
visual/gameplay checks need a human-provided asset directory (record it in
AGENTS.local.md).
4. Repository map
Top level:
| Path | What it is |
|---|---|
src/ |
the game itself (see below) |
vendor/ |
third-party code. librw, ogg, opus, opusfile are git submodules (pinned); libsndfile, mpg123, openal-soft, milessdk are partial in-tree copies (headers/libs) kept for the Windows/legacy builds |
gamefiles/ |
updated/extra game data shipped with releases (TEXT/*.gxt translations, frontend/menu TXDs, data/PARTICLE.CFG, extra data/main_freeroam.scm, gamecontrollerdb.txt) |
cmake/ |
Find*.cmake modules and GetGitRevisionDescription.cmake |
utils/gxt/ |
GXT (text table) tooling |
res/, codewarrior/, autoconf/ |
assets, the CodeWarrior 7 project (reference build), premake modules |
premake5.lua, premake-vs*.cmd, premake5.exe, premake5Linux |
the legacy premake build (Windows-focused) |
CMakeLists.txt, src/CMakeLists.txt |
the primary build |
printHash.sh / printHash.bat |
premake-time equivalent of the CMake GitSHA1.cpp generation |
.gitea/ |
Gitea Actions CI (Linux: configure+build as in §3.2) |
.github/ |
historical upstream GitHub Actions workflows — reference only |
AGENTS.md, CODING_STYLE.md, README.md |
policy |
Source subsystems (src/):
| Dir | Contents |
|---|---|
core/ |
entry/state machine and frame (main.cpp), CGame, CTimer, frontend/menus, streaming, CFileMgr/CFileLoader, pads and control mapping, profiles, stats, zones, world, config.h constants |
control/ |
mission-script VM (Script*.cpp), car/ped AI control (CarCtrl, CarAI, PathFind), pickups, garages, phones, replay, records, road blocks, traffic lights, scene edit |
entities/ |
CEntity/CPhysical base hierarchy |
peds/ |
CPed, CPlayerPed, civilians/cops/emergency, population, ped AI/combat/IK routes |
vehicles/ |
CAutomobile, CBoat, CBike, CHeli, CPlane, CTrain, car generators, damage/handling |
audio/ |
DMAudio/AudioManager front end, sampman_oal.cpp + oal/ (OpenAL backend), sampman_miles.cpp, eax/, music/radio (MusicManager, PolRadio) |
renderer/ |
CRenderer, CHud, CSprite2d, particles, weather, water, timecycle, coronas, shadows, skidmarks, glass, clouds, credits, point lights, motion blur |
collision/ |
CCollision, CColModel, spheres/boxes/triangles/lines, CVuCollision (PS2 VU path) |
modelinfo/ |
model descriptors: simple/clump/ped/vehicle/time/MLO models, CModelInfo store |
save/ |
C_PcSave, GenericGameStorage (byte-wise serialisation), SaveBuf.h helpers, memory card stubs, dates |
skel/ |
platform layer: crossplatform.cpp/.h (POSIX shims incl. case-insensitive path resolution and user-file folder), events.*, skeleton.* (RenderWare skeleton API), glfw/glfw.cpp (Linux entry point, main()), win/win.cpp (Windows WinMain) |
extras/ |
non-reversed additions: debug menu, custom frontend options, post-FX/screen droplets, custom pipelines, INI parser, GitSHA1.h |
fakerw/ |
stub headers emulating RenderWare headers that are not needed when librw is used |
rw/ |
RenderWare glue: texture/TXD reading, visibility plugins, MatFX, lights, memory heap/pools |
math/ |
vectors, matrices, quaternions, rects, engine math helpers |
objects/ |
CObject, CCutsceneObject, dummies, object data |
text/ |
GXT text (TheText), messages, pager |
weapons/ |
CWeapon, weapon/bullet/shot/projectile info, explosions, weapon effects |
animation/ |
animation blending (RpAnimBlend, CAnimBlend*), bones, cutscene manager |
buildings/ |
CBuilding, treadables |
Platform facts verified in-tree:
- Linux runs the glfw skeleton:
src/skel/glfw/glfw.cppownsmain(), creates the window, maps GLFW keysyms toRsKeyCodes, and runs the game-state loop. src/skel/win/is Windows-only (WinMain, win32 resources).- There is no SDL skeleton in
src/skel/. librw has an SDL2 gfxlib option, but re3 has no SDL-based platform layer.
5. Engine frame flow
5.1 Platform loop (src/skel/glfw/glfw.cpp)
After RsEventHandler(rsINITIALIZE, nil) the skeleton runs an outer while(TRUE)
loop around an inner loop that ends on RsGlobal.quit,
FrontEndMenuManager.m_bWantToRestart or window-close. Each iteration:
glfwPollEvents()(window/input events; key mapping is done by the GLFW callbacks installed earlier).- If the window is not foreground, nothing is ticked (the app idles).
- Otherwise a small state machine on
gGameStateruns:
GS_START_UP → GS_INIT_ONCE → GS_INIT_LOGO_MPEG → GS_LOGO_MPEG
→ GS_INIT_INTRO_MPEG → GS_INTRO_MPEG (movies; NO_MOVIES skips)
→ GS_INIT_PLAYING_GAME | GS_INIT_FRONTEND → GS_FRONTEND
→ GS_PLAYING_GAME
GS_FRONTENDcallsRsEventHandler(rsFRONTENDIDLE, nil)every iteration, and transitions toGS_INIT_PLAYING_GAMEonce the menu wants to start/load a game.GS_INIT_PLAYING_GAMErunsInitialiseGame()(CGame::Initialise("DATA\\GTA3.DAT")) then setsGS_PLAYING_GAME.GS_PLAYING_GAMEcallsRsEventHandler(rsIDLE, (void*)TRUE)only if the frame limiter is off or1000/maxFPSms have elapsed since the last frame (CTimer::GetCurrentTimeInCycles()/GetCyclesPerMillisecond()).resizeCB()callsRsEventHandler(rsIDLE, TRUE)directly when the window is resized during play, i.e.Idle()can be entered outside the normal pacing.
5.2 Idle() — one in-game frame (src/core/main.cpp)
Idle(void *arg) with arg != nil (the normal rsIDLE case):
CTimer::Update()— wall clock →ms_fTimeStep(1.0 == 50 Hz; clamped to[0.01, 3.0];FIX_BUGSversion also counts 30 Hz logical frames).CSprite2d::InitPerFrame(),CFont::InitPerFrame().CPointLights::InitPerFrame(),CGame::Process()— the simulation tick:CPad::UpdatePads();DebugMenuProcess();CCutsceneMgr::Update();FrontEndMenuManager.Process();CStreaming::Update(); then, unless paused:CTheZones::Update, sprite/font init, record capture,CPad::DoCheats(),CClock::Update,CWeather::Update,CTheScripts::Process(),CCollision::Update,CTrain/Plane/Heliupdates,CDarkel,CSkidmarks,CAntennas,CGlass,CEventList,CParticle, fires,CPopulation::Update,CWeapon::UpdateWeapons, car generators,CCranes,CClouds,CWaterCannons,CUserDisplay,CReplay,CWorld::Process(), accidents, pac-man pickups, pickups, garages, rubbish, special FX,CTimeCycle::Update,TheCamera.Process(),CCullZones,CGameLogic::Update,CBridge,CCoronas, shadows, phone info,CCarCtrl::GenerateRandomCars/CRoadBlocks::GenerateRoadBlocks/CCarCtrl::RemoveDistantCars.DMAudio.Service().- Demo-mode timeout / restart / load-request early outs, then
SetLightsWithTimeOfDayColour(Scene.world). - If
arg == nil, return here (process-only frame). - Render phase, only when the frontend menu is inactive or wants the game
rendered in the background, and no screen fade is active:
CRenderer::ConstructRenderList(),CRenderer::PreRender().- Clip/fog setup (
RwCameraSetFarClipPlane/RwCameraSetFogDistanceunderFIX_BUGS). DoRWStuffStartOfFrame_Horizon(...)with timecycle sky colours (or white during lightning),DefinedState().RenderScene():CClouds::Render(),DoRWRenderHorizon(),CRenderer::RenderRoads(),CCoronas::RenderReflections(),CRenderer::RenderEverythingBarRoads(),CRenderer::RenderBoats(),CWaterLevel::RenderWater(),CRenderer::RenderFadingInEntities(),CRenderer::RenderVehiclesButNotBoats(),CWeather::RenderRainStreaks().RenderDebugShit(),RenderEffects()(glass, water cannons, special FX, shadows, skidmarks, antennas, rubbish, coronas, particles, weapon effects, point lights, moving things, first-person vehicle).- Optional screen droplets (
SCREEN_DROPLETS) thenTheCamera.RenderMotionBlur(). Render2dStuff(): replay, pickup text, widescreen borders, radio name, console,CHud::Draw(), on-screen timer, messages, fonts,DebugMenuRender()(debug menu overlay).- If the menu is active instead: size/clear the camera and begin update.
RenderMenus()(FrontEndMenuManager.DrawFrontEnd()),DoFade(),Render2dStuffAfterFade()(CHud::DrawAfterFade(), fonts),CCredits::Render(),DoRWStuffEndOfFrame().
FrontendIdle() (the non-PS2 rsFRONTENDIDLE path) is much smaller:
CTimer::Update(), sprite/font init, CPad::UpdatePads(),
FrontEndMenuManager.Process(), camera clear/begin, DefinedState(),
RenderMenus(), DoFade(), Render2dStuffAfterFade(), DoRWStuffEndOfFrame().
5.3 Debug aids you will use
- Ctrl+M toggles the debug menu (
DebugMenuProcessinsrc/extras/debugmenu.cpp, compiled whenDEBUGMENUis defined, i.e. all non-MASTERbuilds). It can teleport, spawn vehicles, toggle rendering options, change time/weather, etc. - Ctrl+B toggles the free/debug camera (
IMPROVED_CAMERA, handled inCCamera::ProcessviaCTRLJUSTDOWN('B')insrc/core/Camera.cpp; setsCCam::MODE_DEBUG). src/core/Debug.cppdraws collision lines, path data and script debug lines in non-FINALbuilds;TIMEBARS(gbShowTimebars) prints per-phase timings.
6. Known fragile areas
Do not "discover" these the hard way; assume they are load-bearing:
- High-FPS timing.
CTimer::Update(src/core/Timer.cpp,FIX_BUGSbranch) converts wall-clock time intoms_fTimeStep, where 1.0 means 50 Hz, clamps it to[0.01, 3.0]and freezes time when a frame exceeds 60 ms. Game logic, physics, animation and FX were written around ~30–50 Hz; above that, assumptions about per-frame movement, input deltas and event counts break (README To-Do: "Fix physics for high FPS"; tracker issue: high-FPS physics/mouse input). Never tweak per-frame constants to "fix" an FPS-dependent symptom without aFIX_BUGS-scoped change and a clear statement of what the original code assumed. - Event-pump pacing in the glfw skeleton.
rsIDLEis only dispatched fromGS_PLAYING_GAMEunder the frame-limiter condition, andresizeCB()can callIdle()re-entrantly during a window resize. Mouse-look and camera code derive deltas from pad state that is expected to be reset once per tick; touching the loop or the resize path easily produces doubled input or stuck movement. - Hardcoded backslash data paths. Examples:
src/vehicles/Train.cpp("data\\paths\\tracks.dat",tracks2.dat),src/vehicles/Plane.cpp("data\\paths\\flight*.dat"),src/rw/TexRead.cpp("DATA\\CAPS.DAT","models\\txd.img","models\\txd.dir").src/skel/crossplatform.cpp(casepath,_fcaseopen,_caserename) copes with/vs\and with case on POSIX, but only for code paths that go through it. Do not blanket-rewrite these literals: onmasterthey are reversed code; Linux path work is tracked as its own task. - Case sensitivity of asset names. Linux filesystems are case-sensitive; the
original data is not consistently cased.
_fcaseopen/casepathresolve the real name component by component, but directfopen/RwStreamOpencalls bypass that. When adding file access, route it throughCFileMgr/_fcaseopen. - Save-file layout.
src/save/*serialises field by field (seeSaveBuf.h), andCOMPATIBLE_SAVES/FIX_INCOMPATIBLE_SAVESexist precisely because struct layouts differ between platforms/builds (see the comments insrc/core/config.h). Nevermemcpya struct to/from the save buffer, never add/reorder save fields without aCOMPATIBLE_SAVESpath, and do not tightenVALIDATESAVEBUF/VALIDATE_SAVE_SIZEchecks across platforms — they only run in non-MASTERbuilds and are a debugging aid, not an on-disk contract. src/extras/GitSHA1.cppis generated. CMake configuressrc/extras/GitSHA1.cpp.in→<build-dir>/extras/GitSHA1.cppand compiles that (seesrc/CMakeLists.txt); the file is git-ignored and must not be created in the source tree.printHash.shis the premake equivalent.vendor/submodules are pinned to exact commits (git submodule status). Updating them is a deliberate, verified change of its own — not a side effect of another fix.
7. Never touch
vendor/submodule pins. Bumps are coordinated changes that must be separately motivated and build-verified (there is an open tracker item for a librw bump — that is the shape such a change takes).gamefiles/— shipped game data; changing it changes what players get and requires asset knowledge..github/— historical upstream CI, kept as a record. Current CI is.gitea/workflows/.premake5.exe/premake5Linuxbinaries (checked-in tooling).- Policy text:
README.md's Contributing/Installation/License sections andCODING_STYLE.md. These express project policy and need human sign-off; an agent may fix typos in them only if explicitly asked. MASTER/GTA_VERSIONsemantics insrc/core/config.h(and theVANILLA_DEFINESblock). Changing whatMASTERmeans silently changes which code is compiled as "release" — that is a project decision, not a task detail.
8. Workflow for agents
- Pick one bounded task. Work is tracked in the Gitea issue tracker
(
https://git.thetomie.com/rockstargames/re3/issues), grouped into milestones: M1: Repo & CI modernization, M2: Linux platform hardening, M3: Known bug backlog, M4: Toolchain & language modernization. Work one issue (or one clearly separable slice of one issue) per commit. If no tracker access is available, the task brief you were given is the source of truth. - Read the code you will touch, plus the nearest neighbours that share its
patterns (
premake5.luaandsrc/CMakeLists.txtglob sources, so adding a.cppneeds no build-file edit — but headers and platform guards still matter). - Keep diffs minimal. Fix the thing asked; do not reformat, re-sort, rename or
"clean up" adjacent reversed code. Match the file's local style even where it
disagrees with
CODING_STYLE.md. - Put behaviour changes behind
FIX_BUGS. If the change alters what the reversed code does at runtime, guard it (#ifdef FIX_BUGS), or place it insrc/extras//src/skel/if it is genuinely an addition or platform layer. - Verify with §3 before committing. Fresh-ish build dir, exit code 0, binary
produced. For
miami/lcstargets, run the equivalent build on that branch — the recipes are the same, the sources are not. - Commit atomically with a Conventional Commit subject, imperative, no
trailing period:
fix:,feat:,docs:,ci:,refactor:,test:,style:,perf:,chore:— optionally scoped, e.g.fix(glfw): .... - Never
git push. There are no push credentials. The orchestrator mirrors local commits to the Gitea remote through the API. Do not rewrite published history; do not force-push; do not create tags. - CI is not your gate. Gitea Actions need a registered runner (tracker issue: runs stay queued without one). The local §3 build is the authoritative check.
Quick pre-commit checklist:
- only the intended files changed (
git status,git diff) - no C++11+ constructs outside
src/extras/, skeletons orFIX_BUGSguards - tabs, pointer style, typedef'd integer types respected in new code
- runtime behaviour changes guarded by
FIX_BUGS - §3 configure+build exits 0 in a clean build dir
- commit message is one Conventional Commit line
9. AGENTS.local.md
AGENTS.local.md at the repo root is git-ignored (added to .gitignore alongside
this file, following the llama.cpp convention). It is for machine-specific
facts: where the GTA III asset directory lives, which build directory to use,
container names, local runner quirks, paths to a legally-owned game install.
It takes precedence over this file for anything it states, but it may not override the provenance and style rules in §1–§2 or the "never touch" list in §7 — those are project policy, not local configuration.