TableTower/docs/DESIGN.md
2026-11-09 08:21:46 -06:00

19 KiB
Raw Blame History

TableTower — Design and Status

Engine: Godot 4.7.2 (GDScript) · Started: 2026-11-08 · Last updated: 2026-11-09 (big files split; see §10)

This is the starting point for anyone picking the project up, including a new Claude session. It records what TableTower is, how it's built, how to work on it, where things stand, and what's next.

Detailed references:

  • docs/LOGIC.md: the rule language and every logic feature: card kinds, expressions, effects, variables, conditional pipes, routers, dynamic options and the file keys.
  • docs/PLAIN.md: the Plain Build usability layer: plain-language display, fill-in builders, Check cards, card inputs, collections and the "why" trace.
  • README.md: user-facing usage notes and command-line/screenshot flags.

1. What TableTower is

A desktop app for building random roll tables and rolling on them, for tabletop GMs, players and anyone using random prompts. Tables are cards on a felt board, joined by copper pipes. A roll flows down the pipes from card to card, and the path lights up.

On top of plain tables, a logic layer lets a board ask the player questions, remember values, repeat steps, branch, and print a sheet. A whole procedure, such as generating a character, can run as one chain.

Product principles (from the user)

  • General-purpose. Not built for any one game. The Traveller board (§8) is only a capability test, used to find missing general features. Don't build game-specific features.
  • Play mode stays simple for use at the game table. Advanced controls belong in Build mode.
  • Readable by normal people. Rules show in plain words by default. The rule text is still stored, and visible through the Plain/Text switch and "Edit as text".
  • The visual design is settled: felt green, copper pipes, brass for lit and selected things, Rokkitt (display) and Atkinson Hyperlegible (body). See ui/style.gd. Match it and don't restyle.

2. Feature summary (all on main)

Board and rolling

  • Cards and pipes. Cards show their numbered results and a die button. Drag from a result's ● onto another card to lay a pipe.
  • Rolling. Results flicker and land, and a bead travels each pipe. Shift-click fast-rolls with no animation.
  • Play / Build modes. Collapse a card or Collapse all. Pan, zoom (8%–150%), Fit and a minimap (Map).
  • Table types. Weighted plain tables, ranged dice tables (1d100, 2d6, any expression such as 2d6 + dm(@str)), and card mode (a deck with no repeats, with Reshuffle).
  • Pipe options. A count (a number or an expression), "save as", Only if conditions, and Otherwise. A result's conditions and counts are evaluated once, as a snapshot, before any pipe runs.
  • Text in results. [[Table]] inline references, {@var} / {hero} values, and BBCode formatting.
  • The result tray shows the chain as chips with effect lines, a sheet headline, Earlier rolls, a Variables tab, Copy (text, BBCode, with details) and Why this? on each step.

Logic cards (docs/LOGIC.md)

  • Choice: "which option" (pick, with Random), "how many" (a number) or "open ended" (text). The pop-up can be minimized, and its options preview where they lead.
  • Loop: repeat N times, while a condition holds, or until it does. Then "Afterwards".
  • Router: if / else if / otherwise cases; the first true case runs.
  • Check: roll + modifier against a target, with Success and Failure outlets. Sets nat, total and effect.
  • Variable cards (with a starting value) and Collection cards (e.g. Skills, whose members are @skill_*).
  • Sheet: a live template, e.g. a character sheet.
  • Effects on any result: @x = …, +=, -=, reset @prefix_*, list add/remove, and @[expr] indirect names.
  • Dynamic pick options from a collection or list (options_from, options_where), plus show_if on any option.
  • Card inputs: a card declares inputs, and pipes pass values (with), scoped to that pipe's part of the roll.
  • A 10,000-action limit per roll. The roller uses an explicit stack, so long loops don't overflow.

Building (Build mode)

  • The inspector, docked right. It edits the selected card, result or pipe:
    • effects as rows ("[Subtract] [1] from [Luck]")
    • conditions as rows ("[Luck] [is at least] [2]", with and/or)
    • pipe inputs, Otherwise, count and saves-as
    • kind-specific card fields
    • a value picker with "+ New value…"
    • "Edit as text" everywhere
  • Plain / Text switch in the top bar.
  • Undo/redo (Ctrl+Z, Ctrl+Shift+Z / Ctrl+Y, or ↶ ↷) for every board edit. Typing and dragging merge into one step.
    • Collapse/expand isn't undoable.
    • Rolls, variables and decks aren't undoable.
    • Collection members aren't undoable either.
  • Group cards. Frames that collapse whole blocks. Ctrl/Shift-click or Ctrl-drag to select, Ctrl+G to group, then drag cards in or out, rename, ungroup or delete. Arrange ▾ → Pack collapsed groups.
  • Templates. Save a card, group or selection, with {$param} fill-ins. Insert from "+ Card ▾ → From template…". The library is in user://templates/, and generic built-ins are in templates/.
  • Search (button or Ctrl+F) jumps to cards, opens groups and flashes the card.
  • Test board (Board ▾): hundreds of random rolls plus static checks. It reports errors, dead ends, unreached cards and lint, and clicking an item jumps to the card.
  • Collections (switcher in the top bar). Import and export via Board ▾: TableTower JSON, JSON Canvas, GraphML (both ways), plus Mermaid and DOT (export only).

3. Architecture

core/       engine, no UI, testable headless
  tower_board.gd      a collection (tables, groups), JSON, format v2 + migration
  roll_table.gd       a card: kind, dice, entries, logic fields, factories (RollTable.create)
  table_entry.gd      a result: text, weight, range, effects, pipes (+count/save/when/otherwise/with), show_if, when
  roller.gd           coroutine roller with an explicit stack (_chain loop, roll/pipe steps,
                      apply_starting_values) plus delegators to its parts:
    roll_pipes.gd       pipe_plan snapshot, card inputs (`with`)
    roll_cards.gd       weighted picks, router, check, loops
    roll_choice.gd      choice requests, dynamic options, show_if, asking
    roll_tree.gd        flatten, step lookups, lit keys, pipe/entry keys
    roll_lint.gd        lint_*, endless_cycles
  roll_context.gd     per-roll state: chain and board variables, prompt hook, actions, depth
  expr.gd / effects.gd     expression evaluation (Godot Expression + rewrites), effect statements
  text_expander.gd    [[refs]], {vars}, {@prefix_*}, {= expr}; formatter.gd: BBCode safety and stripping
  dice.gd / deck_state.gd  dice parsing and distributions, card-mode decks
  describe.gd         rules → plain words, labels, why sentences
  builder.gd          effect/condition models ↔ text, known_values
  board_tester.gd     simulation and static checks (used by the Test board UI and the CLI)
  library_store.gd / state_store.gd   collections on disk / local state (decks, variables, history, settings)
  table_group.gd, template_kit.gd, template_library.gd, sample_board.gd
io/         json_io (canonical + import), canvas_io, graphml_io, mermaid_exporter, dot_exporter
ui/         main.gd: the app shell (shared fields, _ready, cards, collapse, input) with one-line
            delegators to RefCounted helpers that hold `m: Main`:
              main_cli (every CLI/screenshot flag), main_rolling, main_editing, main_groups,
              main_history (undo), main_navigation (search/focus/minimap/arrange),
              main_top_bar (bar, toast, rules switch), main_state (decks, variables),
              main_collections, main_templates, main_inspector
            table_card.gd + table_card_{header,rows,editing,value,text}.gd
            result_tray.gd + tray_chips, tray_text, earlier_rolls
            table_settings_dialog.gd + table_settings_rules (validation/apply), settings_kind_fields
            and: board_view, card_layer, pipe_layer, port_layer, group_layer, group_card, minimap,
            why_popover, choice_dialog, table_preview, details_popup, inspector*, value_picker,
            rules_view, search_panel, board_search, board_layout, edit_history, test_board_dialog,
            template_*, io_menu, collection_switcher, variables_panel, modal_card, rich_text, style
tools/      simulate_board.gd (headless simulator CLI), test_window.sh (background test windows)
tests/      test_*.gd: 25 headless suites
templates/  built-in templates · examples/logic_demo.json (original demo board) · assets/fonts (OFL)

Key implementation facts

  • Lazy cards. Cards hidden inside collapsed groups aren't built, so main.card_for(id) can return null. Pipe, port and card layers redraw only when something changes.
  • Undo (ui/edit_history.gd) snapshots each table and group separately, sharing unchanged ones.
  • Prompts. The roller awaits ctx.prompt for choices, and the UI shows progress before each pop-up.
  • Rules display. The UI reads plain or text mode through RulesView and main.rules_plain(), and main.rules_view_changed signals a switch.
  • Shared builders, use them rather than copying: Style.menu_button, Style.font_colors, Style.field_colors, TableCard.vbox/hbox, InspectorKit.* (fields, focused_tag/refocus, as_text_link), Main.file_dialog/export_dialog, JsonIO.entry_line/finish_import.
  • Keep files small. Aim for under ~400 lines; split by area into helper objects as above.

4. Data and storage

  • Collections: user://collections/<id>.json, format_version 2 ({format_version, id, name, tables, groups?}). On Linux that's ~/.local/share/godot/app_userdata/TableTower/.
  • Local state (never exported): user://state/state.json holds decks, board variables, history (cap 50) and settings (last_collection, minimap, inspector collapsed, rules_view). Templates live in user://templates/.
  • Installed collections today: my-tables (migrated from the old board.json, backed up as board.json.bak) and traveller-chargen. Backups of earlier Traveller boards are traveller-chargen.before-*.json.bak in the app data folder.

5. Working on it

Basics

  • Godot: ~/apps/Godot_v4.7.2-stable_linux.x86_64. A desktop launcher "TableTower (Godot)" opens the editor on the project.
  • Tests: for t in tests/test_*.gd; do godot --headless --path . -s "res://$t" -- --sample; done. All must print PASS: 0 failure(s). After adding class_name files, run godot --headless --path . --import first.
  • Smoke test: godot --headless --path . --quit-after 120 -- --sample, which must print no SCRIPT ERROR.
  • Simulator: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<id> --runs=N [--check] [--prefer=regex] [--quiet].
  • Windowed runs and screenshots: always go through tools/test_window.sh -- --sample --screenshot=/path.png [flags].
    • It runs the game as window class "TableTower Test", and a KWin rule (KDE Plasma 6, Wayland, in ~/.config/kwinrulesrc) keeps that class unfocused and behind other windows.
    • Never open a test window with plain godot --path ..
    • Don't minimize test windows; Godot stops rendering when minimized.
  • Screenshot and state flags, read in ui/main_cli.gd and in some UI files; README lists the main ones:
    • Setup and roll: --board, --roll, --fast, --answers, --build, --rules=text, --why.
    • Inspector and focus: --inspect=tid[:eid][>to], --search, --focus, --minimap.
    • Tools and layout: --test-board, --pack, --perf, --window=WxH.

Git and agent workflow

  • Git: remote origin = git@forgejo.smhub.duckdns.org:RobinFiredrake/TableTower.git. Work on a feature branch and merge to main when the user asks (fast-forward). End commit messages with the Co-Authored-By line.
  • Agents. Large features have been split across parallel agents in git worktrees, each owning specific files:
    • Worktrees start from an old commit, so each brief says git reset --hard <branch> first.
    • Merge one by one, run every suite and the simulator, take screenshots, then fix the seams.
    • Merged feature branches still exist locally and on the server (pipe-board, fast-roll, logic-cards, groups-templates, boards-v2, undo-options, plain-build); they can be deleted.

6. Decisions on record

  • The three-pane UI from the first design was replaced by the pipe board (a user request: simpler at the table).
  • Variables are kept between rolls until changed or reset, so a character sheet survives other rolls.
  • A variable card's starting value is applied, if the variable isn't set, when a top-level roll starts.
  • Expression dice clamp beyond the end ranges. Plain dice tables report gaps instead.
  • Pipe conditions and counts are a snapshot taken when the result is chosen. Two true Only-if pipes both run; routers give exactly one.
  • a if c else b is refused (Godot's Expression returns the wrong branch); use if(c, a, b).
  • Collapse/expand isn't undoable. Collection members aren't undoable.
  • Rules are stored as text, and the plain layer sits on top of it, so old boards open unchanged.
  • Traveller-derived content stays out of the repo (§8).

7. Known gaps and bugs

  • Only one pipe per target per result. Pipes are keyed by target id, so the mockup's two pipes into Loot (Tier 3 "only if", Tier 1 "otherwise") can't be built. Lifting this needs pipe ids in the model, the file format, the UI keys (tid:eid>to) and undo.
  • Long pipe labels are cut with "…" in narrow gaps, and labels draw behind cards.
  • The Why pop-over opens above the tray and can cover the bottom of the board.
  • Not tried by hand yet: all of this was verified with headless tests and screenshots only. A hands-on playtest with a checklist is overdue.
  • The Linux export preset exists, but the 4.7.2 export templates aren't installed. They're a large download and the user hasn't approved it. There are no Windows or Mac presets.
  • Loading a big board with every group expanded takes about 5 s (building TableCard nodes).
  • Group frames are rectangles, so a non-member card lying inside one looks like a member. Pipes into a collapsed group can't be clicked.
  • Groups aren't kept in the Canvas and GraphML exports. Logic keys survive only in TableTower JSON.
  • {= } dice in live sheet and variable displays re-roll when the display refreshes.

8. The Traveller test board (private)

  • Location. Private content derived from the user's Mongoose Traveller 2e rulebook lives in ~/Repos/Godot/TableTower-private/ (outside git; see its README). That covers the rules digest (traveller/chargen.json), the board generator (traveller/board/build_board.py, python3 -I) and the generated board.
  • The board itself. It's installed as collection traveller-chargen: 662 cards, 23 groups, routers, dynamic options and show_if. It runs clean in the simulator (start card new_traveller).
  • Still worked around:
    • global "argument" variables (@x_offer, @x_lvl) feeding shared skill cards
    • natural-roll pre-rolls (rs, ra, rc)
    • .replace() chains for names
    • counters instead of len()
    • about 70 reset statements
    • a guard before empty dynamic picks
  • Not automated: group steps (Connections, skill packages, shared ships), contact naming, gear choice, medical bills, anagathics, the Psion career, Noble titles, and the total skill cap.
  • Open question for the user: "Raise a skill you already have" counts level-0 skills as held (the rules reading); the user's earlier example was level 1+.

9. Improvement ideas, roughly by value

  1. Hands-on playtest with a checklist, then fix what feels wrong. Highest value now that Build mode has changed a lot.
  2. Several pipes to the same card (pipe ids). It unlocks Tier 3 "only if" plus Tier 1 "otherwise" into one card.
  3. Port the Traveller board to the new features:
    • card inputs instead of the @x_* argument variables
    • Check cards
    • nat
    • collections This also tests them end to end.
  4. Small engine additions:
    • len(list)
    • sum / max over a prefix (enables "best of these skills" and skill caps)
    • a fallback path when a dynamic pick has no options, instead of stopping the roll
    • telling unset from 0
    • lists that keep duplicates
    • effects that run after pipes
    • nicer display names ("Jack-of-all-Trades")
  5. Onboarding: a guided tutorial board, a cheat-sheet panel, and templates surfaced as "starter blocks".
  6. Sheet output: save a finished sheet as text or Markdown; keep finished characters as a list.
  7. Comfort: a UI scale setting, colour-blind-friendly lit pipes, optional seeded rolls.
  8. Groups: nested groups, only true members inside frames, clickable pipes into collapsed groups, and groups in the Canvas and GraphML exports.
  9. Linked templates: a plan exists. Copies record template uid, revision and role, and offer "Update available" with a per-field merge.
  10. Faster expanded-board loads.
  11. Builds: install the export templates (needs the user's OK), add Windows and Mac presets.
  12. From the original design: a big-button quick-roll view, cross-collection references ([[Collection/Table]]), touch support.
  13. Housekeeping: delete merged branches. Keep LOGIC.md and PLAIN.md in step with features.

10. History (2026-11-08, one long session)

Board and core features

  1. Initial Godot project and the original design doc. An HTML mockup became the pipe board, built in Godot.
  2. First feature wave (parallel agents): weights, dice expressions, card mode, text references and BBCode, collections and local state, import/export, a Linux preset, the play-side UI, and the app shell (settings, collection switcher, import/export menu).
  3. Fast roll (Shift-click).

Logic cards 4. Logic cards: choice, loop, variable and sheet cards, effects, expressions, the 10,000-action limit and a coroutine roller. 5. The Traveller board was generated and simulated from the rulebook digest.

Building tools 6. Group cards and templates. Choice pop-up minimize and option previews. 7. Conditional pipes and routers, search, minimap, packing, lazy cards (the board opens in 0.38 s, was 5 s), and Test board. 8. Undo/redo, and dynamic options with show_if and @[expr]. The Traveller board was regenerated with them (792 → 662 cards).

Plain Build 9. The usability mockup, then Plain Build: plain words, the inspector with builders, Check cards, card inputs, collections, Why this?, the Plain/Text switch, and starting values applied.

2026-11-09: token diet 10. Split the oversized files (main.gd 3679 → 617 lines plus 11 helpers; table_card, roller, table_settings_dialog and result_tray likewise) with no behaviour change, then a duplicate-code pass guided by the Coderstanding scanner (shared Style/InspectorKit/JsonIO/Main helpers, dead flags and fields removed). A terminology audit produced suggestions only (not yet applied).