# AGENTS.md — working on Un-Banished Instructions for anyone changing this repository: human contributors and AI coding agents (Claude Code, Codex, Cursor and others). Players want the [README](README.md) and the [user guide](docs/USER-GUIDE.md) instead. ## The goal Un-Banished is a **1:1 reimplementation** of Banished 1.0.7 (Steam build 170910, Windows x64) in Rust + wgpu. It runs natively and in the browser (WASM) on the player's own game data. "1:1" means the behaviour, data formats, constants, timings and interface match the original executable, down to float rounding where the simulation depends on it. It is not "inspired by". 1:1 applies to what the player can observe. The port may be built differently inside. Where it changes nothing observable (rules, numbers, Random order, saves, visuals), make the port efficient in memory, CPU and GPU: share assets instead of copying them per instance, upload each texture once, avoid rebuilding unchanged data every frame. The browser build runs in a 4 GB wasm heap, so waste shows up as crashes and stutter. Look for such waste while you work, measure it before and after, and fix it; `determinism.sh` and the emulator tests must still pass. A change like this is not a deviation. Anything Un-Banished adds that the original does not have (the probe, the mod sites, the cinematic camera, multiplayer) is an **extension**: its own files behind a cargo feature, reaching the game only through the doors listed in [docs/develop/EXTENSIONS.md](docs/develop/EXTENSIONS.md). A new extension starts as an `unstable-NAME` feature, which no release contains, and moves into the default `more` feature when it is stable. `--vanilla` turns every extension off for one run. The core crate, `unbanished-sim`, never depends on an extension or on drawing, windows, the interface, sound or the network. The code is named `unbanished`: crates `unbanished-*`, the programs `unbanished`, `unbanished-mods`, `unbanished-cli` and `unbanished-server`, environment variables `UNBANISHED_*`. Before 1.0 there is no backward-compatible naming; old names survive only where old builds or old data need them (`tools/compat` sets both for builds before the rename). Player-data names stay as they are, so nobody loses settings, kept game files or saves: the settings folder and the browser's storage are `banished-wasm`. The save folder is the original's. The product name is **Un-Banished**. ## Non-negotiable rules 1. **Never commit game material.** `game-data/` (original binaries, `.pkg`, extracted `.crs`, derived images, emulator dumps), `analysis/` (Ghidra project, `decomp.c`, disassembly) and save files (`*.sav`, e.g. in `save-game/`) are git-ignored and stay that way. Never force-add past `.gitignore`. Never paste decompiled C, disassembly, shader bytecode or resource dumps into tracked files: describe findings in prose, tables, addresses (`FUN_1400be770`), offsets (`+0x44`) and constants. The one exception is the handful of screenshots in `docs/assets/screenshots/` that show the game running for the README, the setup guide and the developer guides: compressed WebP of Un-Banished's own frames, made with `tools/screenshots.sh`. The same applies to the short WebM videos of Un-Banished's own frames in `docs/assets/videos/`, made with `tools/videos.sh`. Add to either only when the docs need it, and keep each file small. 2. **Evidence before code.** Every ported behaviour cites the original function it came from. A claim read in the code is *observed*; one produced by running the original (the emulator) is *measured*; a guess is marked *inferred* or *assumed* in the comment and the docs. Check against the decompile or the emulator; don't invent behaviour. Doc comments (`///`, `//!`) are what rustdoc shows, so write them in plain English and end each ported item's doc with one line ``Original: `FUN_1400be680` ``. Offsets, vtable slots and `DAT_` constants go in ordinary `//` comments next to the code, where `tools/triage` still finds them. "Deviation:" and "not ported" comments keep their exact wording. 3. **Mark every intentional difference** in a code comment containing "Deviation:" (or "not ported"), then regenerate the ledger with `python3 tools/triage/deviations.py` and commit `docs/DEVIATIONS.md` with the change. 4. **Other sessions edit this repo at the same time.** Stage only your own files or hunks. Never `git add -A`, `git add .` or `git commit -a`, and never revert changes you didn't make. 5. **Small files.** No Rust file may pass 500 lines, data tables and tests included: give each type or topic its own file, and split a file before it grows past that. The quick tier checks it (`tools/test/file_size.py`); the larger files listed in `tools/test/large-files.txt` may only shrink, and their line goes when they are split. 6. **Back up as you go.** Commit and push to `origin main` after each coherent, verified piece of work. 7. **Ask before downloading** anything (say the file, the source and the size). Treat downloaded files as untrusted. ## Setup ```bash tools/worktree-setup.sh # in a git worktree: link game-data, save-game, analysis, .venv, .env from the main checkout tools/extract-assets.sh # copies your game into game-data/ (or UNBANISHED_DIR=… tools/extract-assets.sh) tools/re-setup.sh [--install] # checks (and installs) Ghidra, JDK 21, objdump, Node, .venv with unicorn and pefile; writes .env # GameFrame: the machine's one checkout, named by GAMEFRAME_ROOT in .env (see "GameFrame" below) cargo test --release # tests needing game data skip when it is missing tools/ghidra/export.sh # optional, ~20 min: analysis/export//decomp.c ``` - Ghidra 12.1.x with JDK 21. Their folders go in `.env` (`GHIDRA_INSTALL_DIR`, `JAVA_HOME`), which `tools/re-setup.sh` writes and every tool reads (`tools/re-env.sh`, `tools/re_env.py`). - REA (`rea-agents`, https://github.com/morluto/rea) starts from the project `.mcp.json` through `./gameframe mcp-provider rea`, at the version GameFrame pins. `REA_MCP_VERSION` in `.env` picks another exact version. `tools/re-setup.sh --rea` shows REA's registration plan for other agents. - The generic method these skills follow, for any game, is https://github.com/tanepiper/reverse-engineer-games. - Web builds: `rustup target add wasm32-unknown-unknown`, `cargo install trunk`, then `tools/dev-web.sh --app game --release`. Binaries under study: `Application-steam-x64.exe` (game logic, base `0x140000000`) and `Runtime-steam-x64.dll` (engine, base `0x180000000`, exports mangled C++ names). ## Map of the repository | Path | What | |---|---| | `apps/game` | The game (binary `unbanished`), by folder: `ui/` (windows, toolbar, dialogs), `gfx/` (renderer, models, decals, shadows, `*.wgsl`), `tools/` (placement, removal, roads, selection), `audio/` (sound, music, ambience), `view/` (scene, world view, particles, weather), `saves/`, `platform/` (paths, browser glue, version, profiler); at the root `main.rs`, `game.rs` (the `Game`), `app.rs` (the window), `native.rs` (headless commands), `probe.rs` (the [probe](docs/develop/PROBE.md)), `loops.rs` (engine loops), `menu.rs`, `gameplay.rs` + `gameplay/` (the town's loop: simulation, input, tools, HUD, audio, saving); `start` is the town from `unbanished-sim` | | `apps/viewer` | Asset browser (models, textures, audio, dialogs) | | `apps/cli` | Command-line helpers | | `apps/frame` | The launcher (binary `unbanished-frame`, its own Cargo workspace): GameFrame's frame in front of the game, starting `unbanished --frame-io` (feature `frame`); in every release zip; see `docs/develop/FRAME.md` and `install.json` | | `apps/modmanager` | The mod manager (binary `unbanished-mods`, egui): mods on and off, order, mod lists, Nexus Mods installs, Play | | `crates/core` | Bit-exact foundations: CRT maths (`crt`), `Random`, Perlin `noise`, `math` (`Transform`), game time (`scheduler`), `calendar`; `picking`; re-exported by `unbanished-game` | | `crates/terrain`, `crates/path` | The terrain generator, mesh and ground queries; the pathfinder, walkable regions and sector graph; re-exported by `unbanished-game` as `terrain`, `pathfind`, `sectors` | | `crates/sim` | The core (`unbanished-sim`): the running town with no drawing, sound or interface, by folder: `town.rs` + `town/` (new game, templates, frame update, load, save, the map), `saved.rs` (a save as the game reads it), `mods.rs` (mod lists for templates); the app uses it as `start` | | `crates/game` | Bit-exact game rules, by folder: `people/` (citizens, lives, needs), `behaviour/` (agents, AI, characters, animation), `work/` (jobs, construction, production, stock), `production/` (farms, orchards, quarries, hunting…), `commerce/` (markets, trade), `nature/` (seeding, growth, wildlife, climate), `world/` (map, floors, placement), `disasters/`, plus `town.rs` + `town/` (the simulation context: sites, building, clearing, piles, storage, the job and building callbacks) and `events.rs` | | `crates/formats` | Dependency-free readers: `.pkg`, `.crs`, UI dialogs, gameplay resources, saves | | `crates/ui` | The game's UI system (element tree, layout, fonts, controls, input) | | `crates/gfx`, `crates/audio`, `crates/wma` | wgpu helpers, xWMA playback, WMA v2 decoder | | `crates/mods` | The mod list (`Modification`, `IO::Modification`) shared by the game and the mod manager, and a text store for the settings file | | `crates/banishedinfo` | Optional banishedinfo.com support (not in the original): its mod list, search and versions, and installs; native only (the site sends no CORS headers) | | `crates/nexus` | Optional Nexus Mods support (not in the original): search, download links with the player's API key, `.pkm` install from archives; native transport behind the `native` feature | | `crates/session` | The multiplayer and recording session (`unbanished-session`, not in the original): `Session` (single player, lockstep), lockstep turns and messages, the links to other players (relay, simulated), digests, recordings, and `watch::Watcher` (a room's town run by the server); the game loop's glue stays in `apps/game/src/gameplay/` (`extensions.rs` is its door) | | `crates/hooks` | Rule hooks (not in the original): WebAssembly plugins run with wasmi behind the core's `unbanished_sim::hooks` door (`unbanished-hooks`). See `docs/develop/RULE-HOOKS.md` | | `crates/net`, `apps/server` | Multiplayer (not in the original): the protocol, the rooms' rules (`rooms::Relay`), the checks, kept towns (`store`) and a WebSocket connection, native and browser (`unbanished-net`); the server program and library (`unbanished-server`: settings, health, the server's own games). See `docs/ARCHITECTURE.md` | | `tools/emu` | Unicorn harness `pe_emu.py` and ground-truth generators for the tests | | `tools/ghidra` | Headless export scripts, `readdata.py` (constants), `vtable.py` | | `tools/triage` | `deviations.py`, `coverage.py` (uncited functions), `determinism.sh`, `cite_labels.py` (labels from citations), `draw_sites.py` (every function that draws from the game's Random; see `docs/RANDOM-DRAWS.md`), `nan_jumps.py` (each float comparison of a function and which way a NaN goes) | | `labels/` | Names of original functions (`names.tsv` by hand, `names-from-port.tsv` generated) and struct fields (`fields.tsv`), read by every decompile tool here and in GameFrame | | `gameframe`, `tools/gf.sh` | GameFrame's project launcher (its MCP server, REA, `advise`); runs GameFrame's tools from this folder | | `tools/github`, `.github/` | `sync-labels.sh` (the label set), issue forms, PR template | | `site/` | The website (VitePress): `npm --prefix site run build`; pages from `docs/` and the README are generated by `site/scripts/prepare.mjs` | | `tools/compat` | Build any revision cleanly, play fixed scenarios, compare versions; see `docs/COMPATIBILITY.md` | | `tools/test` | The test runner `run.py` (tiers `quick`, `standard`, `long`), probe scenarios and baselines, and the headless browser tests; see `docs/develop/TESTING.md` | | `tools/refactor` | Scripts that move code without changing it: `regroup.py` (modules into folders), `split_tests.py` (test modules into files), `split_impl.py` (a type's methods into topic files, driven by a `*-split.json` plan) | | `tools/perf` | `samply_top.py` summarises samply profiles; see `docs/PERFORMANCE.md` for `UNBANISHED_PROFILE` | | `tools/logo` | `make_logo.py` regenerates the logo, icon and favicon in `docs/assets/` | | `docs/` | Findings. Start with `FINDINGS.md`, `CHECKLIST.md`, `GAME-LOOP-CHECKLIST.md`, `PARITY-AUDIT.md`; how the code is built: `ARCHITECTURE.md` | Before starting, read `docs/GAME-LOOP-CHECKLIST.md` and grep `docs/` for the addresses or resources you are about to touch: much has already been traced. ## How work flows A typical change runs: **trace → (emulate) → port → verify → document → land.** Project skills in `.claude/skills/` spell each step out (agents without skill support can read the `SKILL.md` files directly): | Task | Skill | |---|---| | Find and understand an original function, constant, vtable or string | `banished-trace` | | Get exact numbers from an original function (Unicorn emulation) | `banished-emulate` | | Parse a `.crs`/`.rsc` resource or save block | `banished-format` | | Turn traced behaviour into Rust | `banished-port` | | Port a material or shader to WGSL | `banished-shader` | | Prove a change works (tests, captures, web build) | `banished-verify` | | Document, commit and push safely | `banished-land` | | Record a video of the game or a model (headless frames to WebM) | `banished-video` | | Write or edit a release post for the blog (one story per feature) | `banished-blog` | ### GameFrame This project follows [GameFrame](https://github.com/tanepiper/game-frame)'s standard for a reverse-engineering project ([docs/develop/GAMEFRAME.md](docs/develop/GAMEFRAME.md)). `.claude/settings.json` enables GameFrame's Claude Code plugin, which brings: - its `re-*` skills and its 18 agents (`gameframe:re-tracer`, `gameframe:re-porter` and the rest), which hand work to each other. The `banished-*` skills above are this game's versions of the same steps: use them first, and GameFrame's for anything they do not cover; - its gates: a commit or a written file that would add game material or decompiled code is stopped, and only `re-lander` among GameFrame's agents commits. `./gameframe` at the root is GameFrame's project launcher, copied from its `templates/project/gameframe`. The plugin starts GameFrame's MCP server with `./gameframe serve`, and `.mcp.json` starts REA with `./gameframe mcp-provider rea`, so the file must stay. `./gameframe advise "TEXT"` looks up known failures, `./gameframe mcp --list` shows the MCP providers and `./gameframe mcp --enable NAME` adds one. GameFrame's skills name tools by GameFrame's paths. Run them with `tools/gf.sh`, for example `tools/gf.sh tools/triage/decomp_query.py fn 1400be770`. Both commands use the machine's one GameFrame checkout, named by `GAMEFRAME_ROOT` in `.env`, and sets `GAMEFRAME_PROJECT` to this folder. Never clone GameFrame next to this project. To change GameFrame, work in a worktree of that checkout (`git -C "$GAMEFRAME_ROOT" worktree add ../game-frame-NAME -b NAME`), test there and merge into its `main`; GameFrame's `docs/working/environments.md` ("One GameFrame checkout") has the details. What helps any game (a tool fix, a format family, a pitfall) goes back to GameFrame this way. This game's own tools, crates and scripts stay here. Labels are in `labels/`, where GameFrame's tools look: `labels/names.tsv` and `labels/fields.tsv` by hand, `labels/names-from-port.tsv` generated from the port's citations. The project's state, in GameFrame's format, is [docs/CHECKLIST.md](docs/CHECKLIST.md). ### Exactness checklist The details that drift are the ones that bite: - Float operation order matters. Port the original's term order, and use `crate::crt` (`sinf`, `cosf`, `acosf`, `atan2f`) and `crate::math` (normalise, heading, quaternion `Transform`) rather than Rust's `f32` methods in simulation code. - `System::Time` is integer microseconds; convert as `scheduler::seconds` / `ticks` do. - Iteration order, the game `Random` call order and CRT `qsort` instability are observable; `ai::crt_qsort_by` reproduces the latter. - Where possible, add an emulator check (`tools/emu/*.py` writing to `game-data/derived/emu/`, a test in `crates/game/tests/` that skips without it). ## Versions The engine version is `-`, for example `0.2.0-93be55d`. Do not confuse it with the Banished version: the main menu footer ("Version 1.0.7 - Build 170910") comes from the original's resources and must not change. - The version is set once, as `version` in `[workspace.package]` in the root `Cargo.toml`. Every crate inherits it with `version.workspace = true`. - `apps/game/build.rs` sets the build id at compile time, for native and wasm32 builds: `UNBANISHED_BUILD` from the environment if it is set, else the short git hash (7 characters) with `-dirty` for uncommitted changes to tracked files, else `GITHUB_SHA`, else `unknown`. `.github/workflows/site.yml` sets `UNBANISHED_BUILD`. The site footer uses the same rule (`site/.vitepress/config.mts`). - It appears in `unbanished --version`, the first log line, the browser's loading panel and the site footer (`apps/game/src/platform/version.rs`). Do not add it to the original's menus unless the change is marked as a Deviation. - Bump the workspace version only for a release, in its own commit: the minor number for new features or parity work, the patch number for fixes only. Before 1.0 there are no compatibility promises. Ordinary commits do not change it; the build id identifies them. - [CHANGELOG.md](CHANGELOG.md) has an `Unreleased` section. Add a line there for each change a player or contributor would notice. - **Releasing `X.Y.Z`:** run the Release workflow (`.github/workflows/release.yml`), only when the user asks for the release: `gh workflow run release.yml -f version=X.Y.Z -f next=X.Y+1.0` (add `-f dry_run=true` to check and see the notes without pushing anything). It does not run the tests: run `tools/test/run.py` locally before it. The Tests workflow runs only by hand (`gh workflow run tests.yml`), to save GitHub's minutes. It renames `Unreleased` to `[X.Y.Z] - DATE` with its compare link, commits and tags `vX.Y.Z` (annotated), sets the workspace version to the next version in a second commit, pushes, publishes a GitHub release with the changelog section as its notes (and a link to the version's blog post in `site/blog/`), rebuilds the website, and starts the Binaries workflow. That builds the game (Un-Banished More: default features, no unstable ones) and its launcher (`unbanished-frame`) from the tag and attaches a zip for Windows, macOS (Apple silicon and Intel) and Linux; start it by hand (`gh workflow run binaries.yml -f version=X.Y.Z`) to build a release again. Before a release, write the Unreleased section's opening line; `tools/release/release.py` holds the steps, so you can try them on a scratch copy. ## Before every commit ```bash rustfmt --edition 2021 tools/test/run.py # quick tier, ~2 min: format, ledger, harness, cargo test, wasm, Clippy, probe baselines tools/test/run.py determinism browser # ~3 min more, when the change touches the game, its UI or the web page tools/compat/compare.sh HEAD # if the change can touch the simulation ``` Other sessions share `target/release`. Before `compare.sh`, copy your build to a file of your own (for example in your scratchpad) and compare that copy. `tools/test/run.py long` adds the website, replays, lockstep, network and multiplayer: run it before a release and after save, network or multiplayer work. The quick tier regenerates `docs/DEVIATIONS.md`; stage it if it changed. A probe baseline that changes (`tools/test/baselines/`) is a change in what the game does: find the cause, or record it with `--update-baselines` only when the change is intended. In tests and scripts, find and press things with the probe ([docs/develop/PROBE.md](docs/develop/PROBE.md)), not with pixel positions or fixed waits. [docs/develop/TESTING.md](docs/develop/TESTING.md) describes every suite. An optimisation or refactor must not change the game's results at all: same saves, same frames, same random numbers ([docs/COMPATIBILITY.md](docs/COMPATIBILITY.md)). If the comparison finds a difference, find the exact cause (check the old build against itself too), then fix it or revert. If it cannot be fixed, open an issue with the problem, the outcome, the suggested change and its impact, for a community vote. Captures and tests must not write the player's settings or saves (`UNBANISHED_SETTINGS`, `UNBANISHED_USER_DIR`). Tests must never be heard: people work next to these runs, in meetings too. `UNBANISHED_MUTE=1` keeps the native game's volume at 0. `.cargo/config.toml` sets it for every `cargo run` and `cargo test` here, and `tools/test/run.py`, the `tools/compat` scripts, `determinism.sh`, `screenshots.sh`, `videos.sh` and `tools/reference` set it too. The game's own test builds are silent without it. Set it yourself for a built binary you start by hand (`--sim-continue`, captures). In a browser, open the game with `&mute` (`tools/dev-web.sh` prints that address); the browser tests start Chrome with `--mute-audio` and Firefox at volume 0. To hear a game, set `UNBANISHED_MUTE=0` or drop `&mute`. ## Committing - Stage files explicitly: `git add path/one path/two`. For a shared file holding someone else's edits, stage only your hunks (see `.claude/skills/banished-land/SKILL.md`). - Subject in the imperative, at most 72 characters; the body says what was traced or ported and how it was verified. - AI agents end the message with their attribution line, e.g. `Co-Authored-By: Claude Opus 5.5 `. - `git show --stat HEAD` to confirm only your files went in, then `git pull --rebase --autostash && git push`. If the rebase conflicts in files you didn't touch, stop and report. ## Writing docs Match the existing docs: an opening paragraph on scope and evidence type; prose and tables keyed by function address and field offset; every claim observed, marked *inferred*, or listed under **Open questions**; no copied pseudocode. Tick `docs/GAME-LOOP-CHECKLIST.md` when an item is done. Player-facing changes (controls, file locations, new options) also go in [docs/USER-GUIDE.md](docs/USER-GUIDE.md).