# Godot Plan: Files TCG as a 3D Tabletop Game _Prepared 2026-10-01 against rules v0.9, the simulator in `files-tcg/sim/` and the browser app in `files-tcg/app/`._ This plan moves Files TCG from the browser app into Godot 4.7 as a 3D game played on a physical-looking table. Decisions made so far: | Decision | Choice | | --- | --- | | Look | A physical tabletop: the playmat on a table, 3D cards, and dice that really roll | | Rules engine | Ported to GDScript now, so the game runs without Node or a browser | | Long term | Online PvP, a desktop release, a deck builder, and a tutorial and campaign | The work comes in milestones. M1–M5 reach what the browser app does today: one person plays the bot, with every rule and card working. M6–M9 add the new goals. ## 1. Starting Point **The TypeScript side.** `sim/` holds a deterministic rules engine, one script per card for all 83 Set 1 cards, and the greedy bot. `app/` is a Preact layer over it. Its controller (`match.ts`) and its click-to-act mapping (`moves.ts`) have no DOM code. This is what gets ported: | Part | TS files | Lines | | --- | --- | --- | | Core engine | `engine`, `flow`, `query`, `state`, `rules`, `map`, `rng`, `csv`, `cards`, `scripts`, `describe`, `invariants`, `deck`, `odds` | ~3,200 (plus ~370 of types) | | Card scripts | `cards/*.ts` | ~1,950 | | Bots | `bots/greedy`, `eval`, `random` | ~1,300 | | Controller | `app/src/match`, `moves`, `replay` | ~600 | | Tests (as fixtures, see §2) | `sim/test/*` | ~2,300 | **The Godot side.** `~/test` is an empty Godot 4.7.2 project named "Test". It uses Forward+ and Jolt Physics, has no scenes or scripts yet, and isn't under version control. The installed Godot is the standard build, so scripting is in GDScript. Export templates are installed. **Why the port is practical.** The engine was built in ways that carry straight over: - **The state is plain data.** That makes it easy to clone (undo, the bot, player views), save, send over a network, and compare between the two engines. - **The UI never builds a move.** It picks from `legalActions(s)`, and `applyAction(s, a)` runs the game to the next decision. The 3D table works the same way, so no rules live in the table code. - **Card prompts store what happens next as data** (`{ name, fn, data }`), not as closures. In GDScript that becomes a `call()` on the card's script. - **The RNG is seeded Mulberry32** and lives in the state, so a seed and a list of moves replay exactly, in either engine. - **`viewFor(s, p)` already hides the opponent's cards.** Online play needs exactly that. ## 2. Two Engines Porting now means two copies of the rules while v0.9 is still changing. `rules.md` was last revised on 2026-09-29, and the 52 Set 2 cards have no scripts yet. The plan handles that with one rule and one tool. **The rule: TypeScript stays the reference until the rules freeze.** Rule and card changes happen in the sim first, as they do now. There, a batch run of thousands of games is quick, and GDScript is much slower at that. The change is then ported. When the rules freeze, decide whether GDScript becomes the only engine (decision 2). **The tool: conformance traces.** - **A trace is a game record plus the engine state after every action.** A new `--trace ` option on the sim CLI writes them for any bots, decks and rule variants. - **A headless Godot runner** (`godot --headless --script res://tests/conformance.gd`) replays each trace through the GDScript engine. It stops at the first difference and prints the action and the field, for example `after attack 2→C2: players[1].anomalies[0].damage ts=4 gd=3`. - **It also compares the legal actions** at every step (as sets), and checks that the GDScript greedy bot picks the same move the TS one did. - **The TS test `Table` gets a record mode**, so its rule and card tests also become fixtures: the arranged state, the actions, and the expected state. - **Browser app game records replay in Godot**, since the action keys are the same. Real playtests become traces too. **How a rule change goes:** 1. Make it in `sim/`, with tests and batch runs, as now. 2. Regenerate the traces. The Godot runner fails wherever the behaviour changed. 3. Port the change until the runner passes. Both engines keep the card-text check, so a reworded card in `cards.csv` flags the TS script and the GDScript one. ## 3. Architecture ``` files-tcg/godot/ res:// (see decision 1) data/ cards.csv, decks/*.json, exported card faces (synced from the repo, see M0) engine/ the GDScript port: types, rng, csv, cards, map, rules, state, query, flow, engine, describe, invariants, deck, odds, scripts cards/ servers, programs, hardware, executions, anomalies, util bots/ greedy, eval, random match/ controller: match, moves, replay, records, scenarios table/ 3D: table, camera rig, playmat, card, piles, tokens, firewall, dice, hand present/ event queue that turns engine events into animations ui/ 2D: HUD, prompts, card inspector, panels, menus, deck builder tests/ conformance runner, fixtures, unit tests ``` **`engine/` and `match/` use no nodes or scenes.** They're plain `RefCounted` classes and static functions, so they run headless: in tests, on a worker thread for the bot, and later on a PvP server. ### State **The state is Dictionaries and Arrays shaped exactly like the TS state's JSON**, with the same keys. A deep copy is one native `duplicate(true)`, which is quick enough for undo, bot lookahead and player views. Saving and sending it is free. It compares field by field with TS traces. And the port stays close to line-by-line, which matters most while both engines are maintained. The cost is that field names aren't checked when scripts are parsed. The conformance runner and debug-build invariant checks cover that. Typed classes are the alternative (decision 3). ### Porting hazards Where TS and GDScript differ in ways that break determinism quietly: | In TypeScript | In GDScript | Do this | | --- | --- | --- | | `Array.sort` is stable | `sort_custom` isn't | Use a stable sort helper (index as tiebreak). There are 18 sorts, and several have ties: defender order in `flow.ts` and the bot's move ranking. | | `/` always gives a float | `int / int` truncates | `Math.ceil(x / 2)` (RAID Array) becomes `ceili(x / 2.0)` | | Mulberry32 uses 32-bit `Math.imul` and `>>> 0` | ints are 64-bit | Mask with `& 0xFFFFFFFF`, and test the first 10,000 values against TS | | `[]` is truthy | an empty Array is falsy | Port every `if (x)` on an array or string deliberately | | Closures can reassign outer `let`s | lambdas capture locals by value | Hold that state in an Array or Dictionary | | `??` and `?.` | not available | Write explicit null checks | | `JSON.parse` keeps ints | `JSON.parse_string` returns every number as a float | Normalize ints when loading traces and records; use `var_to_bytes` for Godot saves | | `` `${5}` `` is `5` | `str(5.0)` is `5.0` | Keep ints as ints, or log lines and action keys drift | ### Events for animation One `applyAction` can draw a card, run a combat, capture a location and fire triggers before the next decision. The table has to show that as a sequence. The GDScript engine therefore adds `s.events`, a list of structured events: drew, moved card, placed, combat started, rolled, rerolled, damaged, destroyed, captured, Firewall changed, Bandwidth changed, and counter changed. Most zone changes already go through helpers in `state.ts` (`toHand`, `toDiscard`, `gainBandwidth` and so on), so events are emitted in a handful of places. They're filtered per player like the log (`events_for(s, p)`), and they stay out of conformance, because TS doesn't have them. The presenter plays them in order, then snaps the table to `view_for(s, you)`. A missed or mis-drawn animation therefore never leaves the table showing the wrong state. ### Seams for later - **A `MatchController` interface**: `view()`, `legal_moves()` and `act(move)`, plus `events` and `changed` signals. M2 builds `LocalMatch`, with the engine in-process and the bot on a worker thread. M8 adds `RemoteMatch` with the same interface, so the table doesn't change for PvP. - **Scenarios.** The port of the TS `Table` helper (arranged boards, rigged dice) serves the card fixtures in M3 and the tutorial in M7. ## 4. The 3D Table | Piece | What it is | | --- | --- | | Table and camera | A seat view angled over your side, a zoom onto a location, and a top-down view on a key for reading the board | | Playmat | Generated from `map.gd` like `layout.ts`, so the 4×4 and lane boards work too. Locations, gateways, starts and row levels are drawn on it, and each location and gateway can be clicked. | | Cards | One `Card3D` scene: a thin box with front and back materials, moving between zones (deck, hand, Server pile, discard, location, worn) | | Card faces | The exported card images, which match print, with one texture per card. Each card name gets one face material made from a shared base and cached, so copies share it. See Card rendering below. | | Anomalies | Their card on the location, with Hardware tucked under it and a damage dial. Copies get a marker. | | Counters and status | Infection and Bug tokens, disabled shown as a card turned sideways, a rooted marker, and +1/−1 Core chips for temporary changes | | Firewalls | Wall pieces on gateways, taller for each level | | Piles | Deck, Server pile and discard as stacks sized by count. Discards can be browsed. | | Bandwidth | A counter on the table, mirrored in the HUD | | Hands | Yours fanned in front of the camera, the bot's face down across the table | **Card rendering.** The table, playmat and card assets already exist, and the faces are exported from the Cider templates. The models are 20× real size (1 unit is 5 cm): a card is 1.27 × 1.778 units, and the playmat a 36 × 30 in mat. Dice physics will need gravity scaled to match. - **One `Card3D` scene for every card.** Its mesh has two surfaces: the face, and the back with the edges. Every card shares one back material. - **One face material per card name**, made from the card shader the first time it's needed and cached by the static `CardFaces` class (`table/card_faces.gd`). Two copies of a card share it. Per-instance shader uniforms can't hold textures, which is why the face needs its own material. - **Per-card state goes in `instance uniform`s** (highlight, dimming a disabled card), so it never duplicates a material. Counters, the damage dial and markers are separate small meshes, so faces stay static and shared. - **A face is only assigned while you can see it.** The bot's hand and face-down cards use the back only, which matches what `view_for` reveals. - **Piles are one stack mesh sized by count.** A `Card3D` is spawned when a card leaves the pile, so a match has about 50–80 live cards, not 138. - **Quality comes from the import settings, not the layout.** Turn mipmaps on, use VRAM Compressed with High Quality (BC7 on desktop), and use anisotropic filtering at 16×. The 750×1050 print size is fine: Godot pads it to 752×1052 for compression without resampling. Faces loaded from code skip Godot's "used in 3D" auto-detection, so each face's `.import` file sets those settings. `tools/name_card_faces.py` writes them, and renames the export's `front-NNNN.png` files to card names (they come out in `cards.csv` row order). - **No atlas.** An atlas needs padding against mipmap bleed, hits the 16384 px limit, and has to be loaded whole. A `Texture2DArray` with a layer index per instance is the upgrade path if profiling ever asks for one material across all cards. **Acting works as it does in the app.** Pick a source, its targets glow (teal for moves, red for attacks), and click one. `moves.gd` ports `moves.ts` unchanged. Every clickable 3D object registers under the same keys (`hand:`, `anomaly::`, `loc:`, `gate:`), so click-to-act maps straight across. A small menu covers several moves on one target, and an action bar holds End, Pass and prompts. Dragging from the hand can come later. **Anything with text is 2D.** Hovering a card shows it large (right-click pins it), and the combat panel, log, info, move list and prompts are all 2D. The 3D table shows where things are; the 2D layer is for reading. **Dice show the engine's numbers.** The engine rolls; the table only acts it out. A tool script records a few dozen settled throws with Jolt in the editor. At runtime each die plays one of them, with its mesh rotated so the face that lands up shows the engine's number. The same approach covers rerolls (Bit Flip), dice added or removed after the roll when Cores change, and the 3+ Bug counter rule. If baked throws don't look good, the fallback is a tumbling tween. This gets a spike in M4. **Pacing.** A game asks each player about 367 decisions and opens about 43 response windows in the bot's commands. The stops setting and step skipping from `match.ts` carry over. Animation speed gets a setting that includes instant, and a click skips the current animation. ## 5. Milestones ### M0. Setup - Move the project into `files-tcg/godot/` (decision 1), put it under git, and rename it "Files TCG". - Add a sync script that copies `cards.csv`, the deck presets and the exported card faces into `godot/data/`. The conformance runner fails if the copies are stale. - Import the table, playmat and card assets, with the card-face import settings from §4. - Set up the folder layout, the headless runner, and a test addon (GUT or gdUnit4) for unit tests. **Done when** `godot --headless` runs an empty conformance suite. ### M1. Core engine - Port in dependency order: `rng`, `csv`, `cards`, `map`, `rules`, `state`, `query`, the script registry, `flow`, `engine`, `describe`, `invariants`, `deck`, `odds`. Then the random bot. - In TS, add `--trace`, plus a way to deal random decks from a limited card list. - Stage A traces use the `Table` helper's small decks (a plain Server, a filler Hardware and four Anomalies). Only a few card scripts are needed to check the turn loop, combat, captures, Firewalls and Bandwidth. **Done when** the RNG matches TS and 1,000 random-vs-random Stage A traces replay with no difference. ### M2. Table vertical slice - The table, built with your existing assets: the playmat placed to match the map, `Card3D` with the exported faces, clicking, the hand, the camera, the action bar and prompts, and the hover inspector. - `LocalMatch` with the random bot. The table snaps to the view after every action, with no animation yet. **Done when** you can play a whole Stage A game against the random bot by clicking, and a port of the app's "every legal move can be reached by clicking" test passes against the 3D table. This tests the biggest design unknown, whether a 3D table reads well, early. The card port carries on alongside it. ### M3. Every card and the greedy bot - Port the card scripts in groups: Servers, Hardware, Programs, Executions, Anomalies. Each group's traces deal decks from the cards ported so far (with `deck.maxCopies` raised). - Add record mode to the TS `Table` helper and run its tests as fixtures. - Port the greedy bot, `eval` and the bot styles. Check bot conformance, measure its speed (the TS bot's slowest move is 1.3 ms; expect GDScript to be one to two orders of magnitude slower), and run it on the `WorkerThreadPool`. **Done when** traces show no difference for random, greedy and nocards bots on full Set 1 decks, for every `Table` fixture, and for a sample of browser app records. ### M4. Presentation - Events in the engine, and the presenter queue. - Card movement, Anomaly unlock flips, Firewall placement and counters. - Combat staging: the camera moves in, the attacker slides up, dice land in the tray, totals show, and damage turns the dials. Captures flip the Server and send Programs to the discard. - An openly licensed font for the 2D UI (Consolas can't be shipped). - The dice spike, then baked throws. - A first pass at sound, and a lighting and material pass on the table and playmat. ### M5. Browser app parity - Port the rest of `match.ts`: stops, skipping empty steps, End command, held-key stops, undo in playtest mode, and invariant checks. - Port `replay.ts`. Game records import and export in the app's format. Save and resume. - Add the 2D panels: combat (Cores by source, odds, dice), info, log with filters, and the move list. - A start screen with side, seed, decks, bot style and rule variants, and a settings screen. **Done when** everything under "Playing" in `app/README.md` works. The browser app can then be retired, or kept as a playtest tool (decision 4). ### M6. Deck builder - Browse the collection by type, set and cost. - A deck editor that runs `validate_deck` as you build. - Import and export the app's deck JSON and pasted lists. The presets come from `decks/*.json`. Decks are saved in `user://`. - Collection limits and unlocks only if the campaign wants them. ### M7. Tutorial and campaign - **A scenario format**: an arranged board (from the `Table` port), rigged dice, scripted bot moves, and guided prompts that limit which moves are offered. The tutorial follows `QUICKSTART.md`. - **The campaign**: a run of bot opponents built from `GreedyParams` presets and fixed decks. Wins can unlock cards for the deck builder. ### M8. Online PvP - **One machine holds the real game.** It sends each player `view_for` and `events_for`, and accepts action keys only if they're in `legal_actions`. Hidden cards mean clients can't each run the full game themselves. This uses Godot's high-level multiplayer over ENet or WebSocket. - `RemoteMatch` implements `MatchController`. - **Response windows** get a timer. Stops run on the client. The engine already skips windows where a player has nothing they could play. - **Reconnecting** resends the current view. A game record lets the host rebuild a game. - Who hosts is decision 5. ### M9. Desktop release - Export presets for Linux, Windows and macOS. Steam via GodotSteam, or itch via butler. - Settings for resolution, audio and animation speed, plus the app's color-blind-safe owner colors. - Check the rights to the card art and fonts, and check the game name and card terms (the 2026-09-30 renames were made for this reason). - Store assets. Bug reports attach the game record. **Order.** M2 can start once M1's Stage A works, then M2, M3 and M4 interleave. M6 and M7 don't depend on M8, so a single-player release (M9 after M7) can ship before PvP. ## 6. Sizes | Milestone | Size | Main work | | --- | --- | --- | | M0 Setup | S | Repo, sync, runner | | M1 Core engine | L | ~3,200 lines ported, trace tooling | | M2 Vertical slice | L | Table, cards, clicking, hand, camera | | M3 Cards and bot | XL | ~1,950 lines of card scripts, ~1,300 of bot, fixtures | | M4 Presentation | L | Events, animation, card faces, dice, art, sound | | M5 Parity | M | ~600 lines of controller, panels, screens | | M6 Deck builder | M | | | M7 Tutorial and campaign | M–L | Scenario system, content | | M8 Online PvP | L | Networking, timers, hosting | | M9 Release | M | Exports, store, rights | The sizes are relative. M1 shows how fast TypeScript ports to GDScript, so firm them up after it. ## 7. Risks - **The engines drift apart.** Card readings marked ⚠ in `rules.md` will change, and Set 2 is unscripted. Traces and the card-text check catch drift, but every rule change costs a port until the freeze. - **Quiet porting differences.** The table in §3 covers the known ones. The runner reports the first differing field, so each one takes minutes to find, not days. - **Bot speed in GDScript.** If greedy is too slow even on a thread, profile `eval` first, since it holds most of the combat math. - **3D readability.** Thirteen locations full of cards, counters and Firewalls can get cluttered. M2 tests this before any art is made, and the top-down view and 2D inspector are the fallbacks. - **Pacing.** Animations multiply the cost of hundreds of decisions per game. Stops, skipping and an instant setting are in from the start. - **Card faces go stale.** Faces are exported from the Cider templates, so a card edit in `cards.csv` needs a re-export. The sync script keeps a hash of each card's CSV row and flags any face exported before the row last changed. - **Scope.** Each long-term goal is a project on its own. The order in §5 lets the single-player game ship first. ## 8. Open Decisions for the Owner 1. **Repo.** Move this project into `files-tcg/godot/`, so the cards, art, reference engine and traces share one commit history? Recommended. 2. **After the freeze.** Retire the TS engine, with batch runs moving to headless Godot, or keep TS for balance runs and maintain both? 3. **State shape.** Dictionaries shaped like the TS JSON (recommended, see §3), or typed classes, which add field checking and autocomplete at the cost of hand-written clone and serialize code and a harder trace comparison? 4. **The browser app after M5.** Retire it, or keep it for quick playtests and replays? 5. **PvP hosting.** One player hosts (cheap, but the host's machine holds the hidden cards), or a dedicated headless server? 6. **Set 2.** Write its scripts in TS first, as now, or only in GDScript once the port is done? ## 9. First Steps 1. Settle decision 1, then do M0: git, the move, the sync script, the headless runner. 2. Add `--trace` to the sim and generate Stage A traces. 3. Port `rng` and check its output against TS, then `csv`, `cards`, `map` and `rules`. 4. Port `state`, `query`, `flow` and `engine` until Stage A traces pass. 5. Start the table with your existing assets as soon as the engine can run a Stage A game. ## 10. Progress **2026-10-01: the rules engine and every Set 1 card script are ported** (M1, plus M3's card port). - **`res://engine/`** mirrors `sim/src/` file for file: `rng`, `csv`, `cards`, `map` (`GameMap`), `rules`, `state`, `query`, `scripts` (`CardScripts`), `flow`, `engine` (`RulesEngine`, since `Engine` is a Godot singleton), `describe`, `invariants`, `deck`, `odds`, `play`, `types`, `util`, `cards/*` and `bots/random`. The state is TS-shaped Dictionaries (decision 3 as recommended). - **Traces.** `sim/src/trace.ts` is a new file in the sim (the CLI is untouched). `tools/make_traces.sh` writes 1,000 random-vs-random games with every card under the main rules, and 100 more that also check the move-list labels. `res://tests/conformance.gd` replays them. - **Result.** All 1,100 games match TS at every step: 1.68 M steps, each comparing the legal actions in order, the state, the log, the decider's view, the random bot's pick and (for the 100) the labels, with invariants checked too. The RNG check covers 10,000 values for 4 seeds. - **Speed.** A random game takes about 0.44 s in GDScript and 17 ms in TS, about 26× slower. - **Data.** `tools/sync_data.py` copies `cards.csv` into `data/`. The runner refuses traces made from a different CSV. - **Not ported yet:** the `Table` test helper and its fixtures (M3), and engine events for animation (M4). **2026-10-01: the greedy bot is ported and the game is playable** (M2, plus M3's bot port). - **The bot.** `engine/bots/eval.gd` (`BotEval`) and `greedy.gd` (`GreedyBot`, with the app's bot styles in `GreedyBot.STYLES`) port `eval.ts` and `greedy.ts`. `Play.bots()` has `greedy` and `nocards`. `tools/make_traces.sh` takes set names and adds three greedy sets. - **Bot conformance.** The bot picks the same move as TS at every step of 850 games, about 331,000 steps: greedy vs greedy, greedy vs random, random vs greedy, and nocards vs greedy. `main` and `labels` still match after the change. - **Bot speed** (`tests/bot_speed.gd`). A `choose()` takes 0.63 ms on average and 6.8 ms at the 99th percentile; the slowest seen was 17 ms, in a post-roll combat-trick window. That's 0.4 s of bot time per game. The game runs it on a `WorkerThreadPool` thread. While it thinks, nothing changes the match and the main thread doesn't call `Odds`, whose caches fill without locks. - **The controller.** `match/local_match.gd` (`LocalMatch`) ports the core of `match.ts`: the stops setting, skipping empty steps, End command, held-Shift stops and the combat readout. Undo, records and replays are still M5. `match/moves.gd` ports `moves.ts` unchanged. - **The table.** `table/game_table.gd` builds the playmat from `GameMap`, laid out by `table/board_layout.gd`. It draws the location tiles (`tile.gdshader`, tinted by owner), lines, gateways and Firewall walls, and puts every visible card in place as a `Card3D` that slides to its spot. Each player's Anomaly slots and piles sit beside their start, and the bot's hand lies past the far edge. Your hand is held in front of the camera. Readouts like Cores and Health are 2D tags pinned to the table. The camera fits the mat between the panels, in a seat view or a top-down one. - **The HUD and game.** `ui/hud.gd` holds the panels, the action bar, the source and response menu, the choice dialog, the inspector, the Log, Combat and Moves tabs, and the new-game, settings and game-over dialogs. `scenes/game.tscn` is the main scene and ties them together. - **The M2 test** (`tests/table_smoke.gd`). Whole games through the game scene, a random player against the greedy bot. Before each of your decisions it checks that every legal move has a screen spot, clear of the panels, where a raycast click hits its source, and another for its target. Every move was reachable in 50 games across both seats, at 16:9 and square screens, with the bot on its thread or not. - **Fonts.** The 2D text and tags use the system's DejaVu fonts for now; the release font is M4.