TableTower/docs/ARCHITECTURE.md
RobinFiredrake c09cb98e8f Docs: which export preset packs tests/
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:25:31 -06:00

21 KiB
Raw Blame History

TableTower — Architecture and Features

Read on demand (not every session). Status and plan: docs/DESIGN.md.

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. A result can pipe into several cards (fan-out), on ranged and weighted tables alike; one roll runs them all.
  • 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 every table from View ▾. Pan, zoom (8%–150%) with the − 90% ▾ + control (the percentage opens Fit board, Zoom to 100% and the minimap), minimap (M).
  • Top bar. Search (icon, Ctrl+F), View ▾ (rules as Plain words or Rule text, Collapse/Expand all tables, Striped rows, Minimap), Help ▾ and the zoom control. Build adds undo/redo, + Card ▾ and Board ▾ (Test board, Reset sample, Pack collapsed groups, import, export).
  • Striped rows. Every second result row on a card is tinted (Style.STRIPE); lit, flicker and selection paint over it. On by default; the striped_rows local setting.
  • Help. Help ▾ lists the topics; F1 opens the window. Text in help/topics.txt (a small markup, see HelpDialog), included in exports via the preset's include filter.
  • 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).
  • Roll modifiers (dice_mod, LOGIC.md §3c). A ranged table adds a modifier such as @luck to its dice. Ranges may run past the dice (−3 to 24 on a d20); totals past the ends use the end result. The card shows chances for the modifier's value now, and Why says "+3 for Luck".
  • 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.
  • Resizable panels. Drag the tray's top edge or the inspector's left edge (double-click for the default). The sizes are kept in local settings (tray_height, inspector_width). Every part of the tray scrolls inside it.

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.
  • Changes (stored as 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]")
    • a roll or check modifier as "[Add ▾] [Luck ▾]" (ModifierEditor)
    • 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 in View ▾ → Rules.
  • Card ⋯ menu (Build): Table settings…, Save as template…, Collapse, Delete table. A row's × shows only on hover, keyboard focus or when the row is selected.
  • 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. Board ▾ → 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/: skill check (a Check card, 2d6 + modifier vs target), ask-and-repeat, pick menu, counter and simple sheet.
  • 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)
  roll_range.gd       a ranged card's numbers: span, natural range, labels, chances, the roll
                      modifier (shared with check cards), range problems
  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; kind_label / choice_label
                      (the only place card-kind and choice-type names are defined)
  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, endless-loop chip), main_state (decks, variables),
              main_collections, main_templates, main_inspector
            top bar parts: view_menu (View ▾), zoom_control, help_menu + help_dialog
            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
            inspector_card (card fields) + inspector_roll (roll dice and modifier);
            modifier_editor (the plain modifier builder); panel_splitter (drag handles)
            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
help/       topics.txt: the Help window's text (# Title per topic)
tools/      simulate_board.gd (headless simulator CLI), test_window.sh (background test windows)
tests/      test_*.gd: 27 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. Next candidates, all 530–730 lines:
    • core: describe (731, the largest now), roll_table, expr
    • ui: choice_dialog, inspector_card, inspector, main, edit_history
    • io: json_io

3b. Modules added 2026-11-10

  • Theme: ui/style.gd (tokens, fill_texture, panel_box), ui/theme_store.gd, ui/builtin_themes.gd, ui/theme_dialog.gd, ui/fill_editor.gd, ui/color_choice.gd. Fonts (2026-11-11): ui/font_catalog.gd lists the 13 bundled families (assets/fonts, licences beside them) and builds faces; Style.set_fonts follows the theme's font_body/font_display.
  • 2026-11-11: ui/deck_reveal.gd (Deck mode: an animated roll's draws fade only when shown), ui/entry_handle.gd (Build: drag handle to reorder results; TableCardEditing.move_entry keeps ranges in place). PortLayer hides thread nodes under a card stacked above theirs. ui/group_mark.gd: a member card's top-right corner in its group's colour (TableGroup.color, else Style.GROUP); refreshed from _board_changed.
  • Card visuals and input: ui/card_frame.gd (border + shader), ui/card_grip.gd (resize), ui/card_shield.gd (zoomed out), ui/sparkles.gd; TableCard helpers table_card_skin/input/ geometry/list/kind_rows.gd (next to header/rows/editing/value/text).
  • Menus and selection: ui/actions.gd (all menus), ui/main_selection.gd (groups in the selection), ui/main_layout.gd (Main's layout, saving, mode, input; Main keeps delegators).
  • Lists and phones: ui/list_view.gd, ui/list_tree.gd, ui/list_order.gd, ui/mobile_layout.gd, ui/touch_input.gd.
  • Book and pictures: core/book_page.gd, core/board_images.gd, ui/book_panel.gd, ui/page_editor.gd, ui/image_field.gd. TowerBoard has book, images, nesting helpers (tables_in, groups_in, hidden_by, set_group_parent).
  • Roll features: core/roll_combine.gd (Roller.OP_COMBINE), core/roll_costs.gd, pause in core/roller.gd (OP_PAUSE) + ui/roll_pauses.gd, RollRange.limit (floor/ceiling), ui/batch_roll.gd. Each roll's token lives in a holder dict in MainRolling so a paused roll can be revived.
  • Output and help: ui/sheet_export.gd, core/demo_spreads.gd, ui/demo_mode.gd.
  • Splits (audit): ui/inspector_result/thread/sync.gd, ui/inspector_threads.gd, core/describe_cards.gd, core/describe_why.gd, io/json_canon.gd, io/json_links.gd, ui/choice_preview/chrome/option_row.gd, ui/edit_labels.gd.
  • New JSON keys (all optional; JsonCanon passes them through): spread book, images; group parent; table color, w, list_h, roll_floor, roll_ceiling, deck_empty_text; result page, image, cost {value, amount}; thread color, combine, pause.

3c. Modules added 2026-11-10 (book tables)

  • Scales: core/scales.gd (store/read step names), core/expr_base.gd (Expression's base instance, split out of expr.gd: _lit turns a step name beside a scale into its number, toward()), Effects._assign_scale, RollContext.scale_steps.
  • Columns: core/roll_columns.gd (fills the other columns after a roll), RollTable.columns / column_rolls / cell_text, TableEntry.cells.
  • Thread dice and rerolls: TableEntry.pipe_dice / pipe_reroll, RollCards.pick_for, RollRange.roll_value(…, dice_text).
  • Checks and IO: core/roll_lint_book.gd; core/roll_table_io.gd (RollTable to/from JSON, split out of roll_table.gd). JSON keys: table columns, column_rolls, steps; result cells; thread dice, reroll. Spec: LOGIC.md §3e, §3f, §5.4.

3d. Modules added 2026-11-11 (theme files, tiers 1–2)

Format spec: docs/THEMES.md. Built-in themes: themes/<id>/theme.gd (const DATA, written by tools/theme_defs/make_theme_defs.py from palettes.py) + files beside it; BuiltinThemes.all().

  • Loading: ui/theme_assets.gd (paths relative to a theme folder, cached loads, pin_paths for copies of built-ins).
  • Recolouring: ui/gradient_map.gd (3-stop shader), ui/frame_set.gd (frame art + geometry; FrameSet.active, the beaded frame is FrameSet.beaded()), ui/card_frame.gd draws it, ui/thread_strip.gd (ThreadStrip.active; textured triangle strip in PipeLayer).
  • Mascot: ui/mascot_art.gd (role recolour of an SVG's text; Morgan's logo SVG uses the Keep File importer so its text is exported).
  • Background: ui/board_backdrop.gd (gradient, scene, tile; old dots/stars).
  • Sound: ui/sound_board.gd (Main.sound; roll / card_turn / thread / click / ambient; ☰ / right-click menu → Sound levels, not in the top bar's View ▾; setting sound_volume).
  • Generators: tools/theme_art/ (SVG art), tools/theme_sounds/ (OGG), tools/theme_defs/.

3e. Size audit batch 1 (2026-11-14): helpers split out

Each original file keeps one-line delegators, so callers are unchanged.

  • inspector_card → inspector_choice, inspector_router, inspector_collection (Ledger section); group_card → group_card_compact (the collapsed group card).
  • main_cli → main_cli_build (group/template/inspector flags), main_cli_perf (--perf); pipe_layer → pipe_batch (unlit thread canvas items), pipe_geometry (curve maths); main_rolling → main_rolling_seed (session start), main_rolling_copy (copy as text).
  • expr → expr_rewriter (user syntax → Godot Expression); builder → rule_tokens (tokenizer, shared with Expr), builder_values (known_values); board_tester → board_checks (static checks), board_report_text.
  • roll_table → roll_table_factory (create), more in roll_table_io; roller → roll_nodes (stop/attach/why/log), roll_live (starting values, live displays), more in roll_pipes and roll_choice; tower_board → board_groups (nesting, membership), board_file_io (migrate, atomic write).
  • Batch 2: main (tightened) and main_groups → main_card_drag; result_tray → tray_controls, tray_why; inspector → inspector_frame; table_entry → table_entry_io (to/from dict); describe → describe_labels, describe_dice; table_card → table_card_rebuild; table_card_header → table_card_go_button; table_card_rows → table_card_row_text, table_card_odds. No script is over 400 lines now (largest: test_board_dialog, board_view, 398).

3f. Modules added 2026-11-14 (playtest fixes)

  • Ledger: core/ledger_members.gd (entries on the card: clean, adopt older spreads, sync with saved values), ui/ledger_edits.gd (add/rename/start/remove with undo), ui/ledger_card_rows.gd (Build-mode fields on the card).
  • Rolling: ui/main_rolling_show.gd (show a roll at once), RollCosts.card_gate (card costs), RollPauses pop-up, SpreadLinks (core/spread_links.gd, Spread::Card) with ui/spread_loader.gd and ui/spread_link_dialog.gd.
  • Interface: ui/delete_key.gd, ui/sound_panel.gd, ui/format_menu.gd (right-click Format), ui/text_effects/ (sparkle, shimmer, flash RichTextEffects; RichText.install_effects), ui/colour_dialog.gd ("Any colour…").
  • Spread folders: core/spread_folders.gd (paths such as "a/b", listing, move, rename; kept empty folders are the StateStore setting kept_spread_folders), core/recent_spreads.gd (setting recent_spreads), ui/spread_folder_dialogs.gd (new, rename, "keep it?"). The switcher's menu items run Callables (CollectionSwitcher._calls, id = index).
  • Timing: tests/perf_roll.gd (not in the suite).

3g. Modules added 2026-11-15 (Build UX round)

  • Ranged cards: core/range_weights.gd (Weights vs Ranges editing: reflow, to_weights turns gaps into empty results, sort_rows = auto-sort, total_problem). RollTable.ranged keeps an empty card ranged; range_edit ("ranges" for older files) and auto_sort are saved.
  • Inspector as one list: ui/inspector_list.gd (sections for the card and each result; only open ones build; activate points selection/fields/effects at the section clicked in), ui/inspector_range.gd (a result's weight, range and position).
  • Dock tabs: ui/side_tabs.gd (Build: Inspector | Lore Index; BookPanel is the Lore Index).
  • Rolling: ui/skip_animations.gd (View ▾ setting); ModalCard.animate_in (pop-up entrance).
  • Look: ui/card_move_handle.gd (Build grip on the header; CardGrip is the resize corner); theme tokens SELECTED and CARD_HEAD (derived from CARD/CARD_SHADE when a theme omits it).
  • Build hint: ui/build_mode_hint.gd (Play's greyed + Card, ☰ New card; MainTopBar.toast_action).
  • Spellcheck: core/spell_words.gd (which words to check), ui/spellcheck.gd (Hunspell via the Godot-Hunspell SpellChecker class if present; off on Android), ui/spell_underline.gd (wavy lines and the right-click menu). Spread words: TowerBoard.dictionary ("dictionary" in the file). addons/hunspell/ holds the add-on's prebuilt libraries (Windows, Linux, macOS) and the en_US dictionary.

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, striped_rows). 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.

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.
  • Linux and Windows export presets exist (both include templates/*.json, help/*.txt, addons/hunspell/dictionaries/*); no Mac or Android preset yet. Linux excludes tests/*; Windows still packs it (harmless; could be excluded).
  • Loading a big board with every group expanded takes about 5 s (building TableCard nodes).
  • Group frames are rectangles; members are told apart by their coloured top-right corner. 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.
  • The simulator and Test board list results that only a modifier reaches as "never chosen" when the modifier stays small in the runs (the demo's luck-only vault, for example).
  • Not yet looked into: Coderstanding warnings.
    • Signals emitted but never connected: ModalCard.closed, SearchPanel.closed.
    • A possible wrong handler in ModalCard.segmented (pressed → on_change; probably a false positive from a bound callable).
    • Large class cycles in ui/ (expected from the main back-references).