TableTower/docs/DESIGN.md
RobinFiredrake cf1d8a6f1e Add design document
Covers roll tables, chained triggers and inline references, Card mode,
chain and persistent variables, hover details, BBCode formatting,
graph layout, import/export formats, and milestones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:13:57 -06:00

339 lines
24 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# TableTower — Design Document
**Status:** Draft · **Engine:** Godot 4.7 (GDScript) · **Started:** 2026-11-08
## 1. Overview
TableTower is a desktop app for building **random roll tables** and rolling on them. It's aimed at tabletop RPG game masters and players, and at anyone who uses random prompts for creative work: writers, worldbuilders, artists.
What sets it apart from a basic dice roller is **chained tables**. A result can point to another table, which is then rolled on automatically:
```
Loot (d6) ──► "Melee weapon" ──► Melee Weapons (d8) ──► "Sword"
└──► Sword Quality (d4) ──► "Rusty"
Final result: Rusty Sword
```
## 2. Goals and non-goals
**Goals**
- Create, edit, organize and delete roll tables quickly.
- Roll on any table and see both the final result and the chain of rolls behind it.
- Let a result trigger one or more other tables, nested to any depth.
- Save everything locally in a human-readable format that's easy to back up and put under version control.
- Import and export tables so people can share them, including as **node graphs**.
- Let tables and entries carry extra details that appear in a pop-up when the user hovers over them.
- Let a chain remember a result and reuse it later, either within one roll or across rolls (such as a "current town").
- Offer an optional **Card mode** that avoids repeat results, like drawing from a deck.
- Support Godot's **BBCode** formatting anywhere the user types text.
**Non-goals (for now)**
- Online accounts, cloud sync or multiplayer.
- A full virtual tabletop (maps, tokens, character sheets).
- Mobile builds. The design shouldn't rule them out, but the first target is Linux desktop.
## 3. Core concepts
### Table
A named list of entries, with a way to pick one.
| Field | Description |
|---|---|
| `id` | Stable unique ID (used for references, so renaming doesn't break links) |
| `name` | Display name, such as "Melee Weapons" |
| `details` | Optional description of the table, shown in a hover pop-up (see "Hover details" below) |
| `tags` | Optional, for organizing and searching |
| `mode` | `weighted` (default) or `dice` (see below) |
| `dice` | Dice expression for `dice` mode, such as `1d20` or `2d6` |
| `card_mode` | `false` by default. When on, results don't repeat until the deck is reshuffled (see "Card mode" below) |
| `entries` | The list of entries |
### Entry
One possible result on a table.
| Field | Description |
|---|---|
| `id` | Stable unique ID within the table. Card mode uses it to track drawn cards even if the entry text is edited |
| `text` | The result text, which can contain inline table references and variables (see "Two ways to chain tables" and "Variables" below) |
| `details` | Optional longer description, shown in a hover pop-up (see "Hover details" below) |
| `weight` | Relative chance in `weighted` mode (default 1) |
| `range` | Roll range in `dice` mode, such as `1–3` or `12` |
| `triggers` | Optional list of tables to roll on when this entry comes up. Each trigger can save its result as a variable |
### Two ways to chain tables
1. **Triggers** (structured): the entry lists other tables to roll on, plus how many times. They're set in the editor with a table picker, and results appear as children of the entry.
- Example: entry "Melee weapon" → trigger `Melee Weapons` ×1.
2. **Inline references** (in the text): the text contains a placeholder that's replaced by a roll on that table.
- Example: `A [[Sword Quality]] sword` → "A rusty sword".
- Extended syntax to consider later: `[[3x Gems]]`, `[[1d4 Coins]]`.
Triggers are easier for beginners and inline references read more naturally. Supporting both is planned, but triggers come first (see milestones).
**Optional extra: references to other collections.** By default a reference points to a table in the same collection. As a later extra, a reference can name another collection: `[[Common/Colors]]` in text, or a trigger that stores both a collection ID and a table ID. If the other collection isn't loaded, the result shows the "missing table" marker described in section 4.
### Selection modes
- **Weighted:** each entry has a weight, and the chance of an entry is its weight divided by the total. This is the simplest to edit.
- **Dice:** the table has a dice expression and each entry covers a range of results, matching how printed RPG tables work (for example "d100: 01–15 Goblin"). The editor should warn about gaps and overlaps in the ranges.
### Card mode (no repeats)
Card mode is an optional setting on each table and is **off by default**. When it's on, the table works like a deck of cards: a drawn entry is set aside and can't come up again until the deck is reshuffled.
- **Weighted tables:** an entry's weight is its number of copies in the deck. An entry with weight 3 can come up three times before it runs out.
- **Dice tables:** the roll is made among the entries that are still in the deck, with each entry's chance based on the size of its range. The dice value shown is one of the numbers in the drawn entry's range.
- **Drawn cards are saved locally** and stay drawn, even after the app closes, until the user presses **Reshuffle** for that table. They're kept in local state (see section 5), never in the table file, so exporting or sharing a table never includes its drawn cards.
- **When the deck runs out:** it reshuffles automatically by default, and the result tree notes "Deck reshuffled". A per-table option can instead show a "deck empty" result.
- **When the table is edited:** a deleted entry is removed from the deck, and a new entry goes into the undrawn pile. Raising an entry's weight adds copies to the undrawn pile.
- The roll panel shows how many cards are left, such as "7 / 12 left".
### Variables (remembering results)
A result can be saved under a name and reused later. There are two kinds:
| Kind | Syntax | Lasts for | Example |
|---|---|---|---|
| **Chain variable** | `{hero}` | One top-level roll | A hero's name used several times in one result |
| **Persistent variable** | `{@town}` | Until the user changes or clears it, even after the app closes | The party's current town |
- **Save:** in text, `[[Names -> hero]]` rolls on *Names*, inserts the result and saves it as `hero`. `[[Towns -> @town]]` does the same for a persistent variable. A trigger can do either with a "Save as" field.
- **Reuse:** `{hero}` or `{@town}` inserts the saved value without rolling again.
- Example entry: `{hero} the [[Titles]] seeks revenge in {@town}.`
- **Roll if not set:** `{@town|Towns}` uses `@town` if it's already saved, and otherwise rolls on *Towns* and saves the result. This makes "current town" work with no setup.
- **Chain scope:** chain variables are shared by every table in one roll, including tables rolled later through triggers. Each new roll starts with none.
- **Persistent scope:** persistent variables belong to a collection, so a fantasy campaign's `@town` doesn't affect a sci-fi collection's. They're kept in local state (see section 5) and aren't exported.
- **Variables panel:** shows every persistent variable for the current collection. The user can edit a value by hand, re-roll it from its table, or clear it.
- **Order:** text is expanded from left to right and triggers in list order, so a chain variable must be saved before it's used. Using a variable that hasn't been saved shows a visible `{hero?}` marker instead of failing.
### Hover details
Both **tables and entries** can have a `details` field with a longer description.
- **Entry example:** the *Classes* table has the entry "Fighter", with the details "A master of martial combat, skilled with a variety of weapons and armor…".
- **Table example:** the *Classes* table itself has the details "Core classes from the Player's Guide. Card mode is on so each player gets a different class."
Where the pop-ups appear:
- **Entry details:** when hovering over a result in the roll panel or an entry in the table editor.
- **Table details:** when hovering over a table in the library, a table's name in the result tree, or a trigger or `[[reference]]` that points to the table.
How they behave:
- Items with details get a small marker (such as a ⓘ icon or a dotted underline) so users know there's more to see.
- Details are copied along with a result only if the user chooses "Copy with details".
- Touch screens can't hover, so a tap or long press opens the pop-up instead. This only matters for a future mobile version.
### Formatting (BBCode)
BBCode is always on, with no setting to turn on. It works anywhere the user types text: entry text, details, table and collection names, and variable values. Godot's BBCode covers tags such as `[b]bold[/b]`, `[i]italic[/i]`, `[color=red]…[/color]` and lists, and text is shown with Godot's `RichTextLabel`.
- **Ordinary brackets are safe:** Godot shows tags it doesn't recognize as typed, so text like `[x]` or `[optional]` appears normally. To show a real tag as text, type `[lb]` for `[`.
- **Places that can't show formatting:** some spots can only show plain text, such as window titles, file names, autocomplete lists and search. There the tags are removed, and search matches the text without them.
- **One entry can't break another:** if an entry leaves a tag open (such as `[b]` without `[/b]`), it's closed automatically at the end of that entry, so the formatting doesn't spill into the rest of the result.
- **The editor helps:** a small toolbar (bold, italic, color) inserts tags, and a live preview shows the formatted result.
- **Table references come first:** `[[Table]]` references and `{variables}` are replaced before the BBCode is rendered, so the reference syntax never clashes with BBCode tags.
- **Copy as text** removes the tags. "Copy as BBCode" keeps them for pasting into forums or Discord bots that use BBCode.
- **Safety on import:** imported files are only allowed formatting tags (`b`, `i`, `u`, `s`, `color`, `font_size`, `ul`, `ol`, `center`, …). Other tags, especially `[img]` and `[url]`, are removed. This means a shared file can't load images from arbitrary paths on the user's computer.
## 4. Rolling
### Algorithm
```
roll(table, ctx, depth): # ctx holds chain vars, persistent vars, decks, RNG
if depth > MAX_DEPTH: return error "Chain too deep"
entry = pick(table, ctx) # weighted or dice, honoring card mode
node = ResultNode(table, roll_value, entry) # keeps table and entry details for pop-ups
node.text = expand_text(entry.text, ctx, depth + 1) # [[refs]], [[ref -> var]], {var}, {@var}
for trigger in entry.triggers:
repeat trigger.count:
child = roll(trigger.table, ctx, depth + 1)
if trigger.save_as: ctx.save(trigger.save_as, child.summary) # "@name" = persistent
node.children.append(child)
return node
```
- The result is a **tree** (`ResultNode`). The UI can show it collapsed as one summary line or expanded to show every step. Each node keeps the table's and entry's details so the pop-ups work in the result view.
- **Card mode state** (which entries have been drawn) is held by a `DeckState` per table, and `pick()` reads from it. Changes to decks and persistent variables are saved to local state after each roll.
- **Cycle safety:** tables may legitimately reference themselves (for example "roll twice more on this table"), so cycles aren't forbidden outright. A depth limit (default 32, configurable) stops runaway chains. The editor should also flag a cycle that can't end: a table where every entry leads back to itself.
- **Missing references:** if a referenced table has been deleted, the roll shows a visible "missing table" marker instead of failing.
- **Seeded randomness:** use a `RandomNumberGenerator` instance with an optional seed, so a roll can be reproduced for testing or debugging.
### Roll history
Each roll is added to the history: time, starting table, and the result tree. The user can copy any result as plain text or BBCode.
## 5. Data and storage
There are two kinds of saved data, kept apart on purpose:
| | **Table data** | **Local state** |
|---|---|---|
| What it holds | Collections, tables, entries, details | Card mode draws, persistent variables, roll history |
| Location | `user://collections/` (on Linux, `~/.local/share/godot/app_userdata/TableTower/collections/`) | `user://state/` |
| Exported or shared? | Yes | **Never** |
| Reset by | Editing or deleting | Reshuffle, clearing variables, clearing history |
- **Format:** JSON for both. It's easy to read, to compare between versions, and to share. Godot's `.tres` resources were considered, but they're tied to Godot and less friendly to hand-edit or share.
- **Collections:** one file per collection. A collection is a group of related tables, such as "Fantasy Loot".
- **Local state:** stored by collection ID and table ID, so it stays linked when names change. If a collection is deleted, its state is deleted too.
- **Versioning:** every file includes `"format_version": 1` so later versions can migrate older files.
Example collection file:
```json
{
"format_version": 1,
"collection": "Fantasy Loot",
"tables": [
{
"id": "loot",
"name": "Loot",
"mode": "weighted",
"entries": [
{ "id": "e1", "text": "Gold coins", "weight": 3 },
{ "id": "e2", "text": "Melee weapon", "weight": 1,
"triggers": [ { "table": "melee_weapons", "count": 1, "save_as": "weapon" } ] }
]
},
{
"id": "classes",
"name": "Classes",
"details": "Core classes. Card mode is on so each player gets a different class.",
"mode": "weighted",
"card_mode": true,
"entries": [
{ "id": "e1", "text": "Fighter",
"details": "A master of martial combat, skilled with many weapons and armor." },
{ "id": "e2", "text": "Wizard",
"details": "A scholar who bends reality through studied [b]arcane[/b] spells." }
]
},
{
"id": "melee_weapons",
"name": "Melee Weapons",
"mode": "dice",
"dice": "1d6",
"entries": [
{ "id": "e1", "text": "Dagger", "range": [1, 2] },
{ "id": "e2", "text": "[[Sword Quality]] sword", "range": [3, 5] },
{ "id": "e3", "text": "Warhammer", "range": [6, 6] }
]
}
],
"graph": {
"nodes": {
"loot": { "x": 0, "y": 0 },
"classes": { "x": 320, "y": 160 },
"melee_weapons": { "x": 320, "y": -80 }
},
"zoom": 1.0,
"scroll": [0, 0]
}
}
```
Fields left out of an entry or table use their defaults (`weight` 1, `card_mode` false, no `details`), which keeps files short.
### Graph layout
The in-app graph view doesn't have its own file format. It's another view of the same collection file, so changes made in it (such as dragging an arrow to make a trigger) edit the same tables, entries and triggers as the List view.
The only extra data is where each table sits on screen, saved in the optional `graph` section at the end of the collection file:
- **It goes wherever the tables go:** exports, backups and git all keep the arrangement, so a shared collection opens looking the way it was laid out.
- **It's optional:** if the section is missing, or a table has no position yet, the graph is laid out automatically.
- **The roller ignores it,** so a bad or missing position never affects a roll.
- **Small git changes:** positions snap to a grid, and the section is kept at the end of the file. This keeps changes from moving nodes small and separate from table edits.
## 6. Import and export
### TableTower JSON
This is the main format, the same JSON as the collection files. It keeps everything except local state, and it's the only format that's guaranteed to bring back a collection exactly as it was.
### Node graphs
A collection maps naturally onto a graph:
- Each **table** is a node, or a group of nodes containing its entries.
- Each **trigger** or `[[reference]]` is an arrow from the entry to the table it rolls on, labeled with the count or variable name.
| Option | What it is | Import? | Export? | Notes |
|---|---|---|---|---|
| **In-app graph view** | A view inside TableTower built with Godot's `GraphEdit` and `GraphNode` | — | — | Edit tables visually and drag arrows to make triggers. Not a file format, but it's the best graph experience |
| **JSON Canvas** (`.canvas`) | Open format created for Obsidian's Canvas, also supported by other tools | ✔ | ✔ | Best fit for editing in another program and bringing the result back. Popular with game masters who keep campaign notes in Obsidian |
| **Mermaid** | Text diagram language | — | ✔ | Renders right inside Markdown files on Forgejo, so a repo's README can show its table graph |
| **Graphviz DOT** | Classic graph text format | Partly | ✔ | Good for automatic layout of large collections and for producing images. Importing is possible but awkward |
| **GraphML** | XML graph format | ✔ | ✔ | Works with yEd and Gephi. Can store custom fields, so it could bring back most details |
**Recommendation:**
1. Build the **in-app graph view** first. It gives the visual experience without depending on another program.
2. Add **JSON Canvas** for import and export. It's the most useful outside graph editor and is simple to read and write.
3. Add **Mermaid** (and possibly **DOT**) export for viewing and documentation, since these take little work.
4. Treat **GraphML** as an extra if someone needs yEd or Gephi.
How JSON Canvas would work:
- **Mapping:** each table becomes a **group**, labeled with the table name. Each entry becomes a **text node** inside the group, with text such as `3 × Gold coins` (weighted) or `1–2: Dagger` (dice). Each trigger becomes an **edge** from the entry node to the target group, with a label such as `×2 → weapon`.
- **Extra data:** TableTower also writes its own fields (IDs, details, Card mode) onto the nodes, so they can come back on import. Other programs may drop unknown fields when they save. If they do, import rebuilds what it can from the visible text and labels and lists anything it had to guess.
- **Layout:** node positions from the canvas are imported into the collection's `graph` section (see "Graph layout" in section 5), and exported from it.
## 7. User interface
A single main window with three areas:
```
┌──────────────┬──────────────────────────────┬─────────────────┐
│ Library │ Table editor │ Roll panel │
│ │ [List | Graph] │ │
│ ▸ Fantasy │ Name: Melee Weapons ⓘ │ [ Roll ] [x3] │
│ • Loot │ Mode: Dice 1d6 ☐ Card mode │ │
│ • Melee W. │ ┌────┬───────────┬────────┐ │ ▾ Loot: Melee │
│ ▸ Sci-fi │ │1–2 │ Dagger │ │ │ ▾ Melee: 4 │
│ │ │3–5 │ [[SQ]] sw │ →table │ │ Rusty sword │
│ [+ Table] │ │6 │ Warhammer │ │ │ │
│ [search…] │ └────┴───────────┴────────┘ │ Variables · Hist│
└──────────────┴──────────────────────────────┴─────────────────┘
```
- **Library:** collections and tables, with search and tags. You can create, duplicate, rename and delete tables. Hovering over a table shows its details.
- **Table editor:**
- **Views:** a **List** view and a **Graph** view (see section 6).
- **Entries:** an editable list, a trigger picker for each entry (with a "Save as" field), and multi-line details editors for the table and each entry.
- **Settings:** a Card mode switch.
- **Formatting:** a BBCode toolbar and live preview for text fields.
- **Help while typing:** autocomplete for `[[` references, and a warning when dice ranges have gaps or overlaps.
- **Roll panel:**
- A roll button with a repeat count, and an expandable result tree with hover pop-ups for tables and entries.
- For Card mode tables, a cards-left count and a **Reshuffle** button.
- Tabs for **Variables** (persistent variables) and **History**, and copy as text or BBCode.
- Later: a "quick roll" view with large buttons for use at the table during play.
## 8. Technical architecture (Godot)
| Layer | Contents |
|---|---|
| **Data** | `RollTable`, `TableEntry`, `Trigger`, `Collection` (plain GDScript classes or `RefCounted`) |
| **Logic** | `Roller` (selection, recursion, depth limit), `RollContext` (variables and RNG for one roll), `DeckState` (Card mode draws), `DiceParser` (`NdM+K`), `TextExpander` (`[[...]]` references and `{var}`), `Formatter` (closing open tags, removing tags for plain-text spots, allowed-tag filter) |
| **UI helpers** | `DetailsTooltip`: a custom tooltip built with `RichTextLabel` through Godot's `_make_custom_tooltip()`, so details can be formatted. In formatted results, each table and entry is wrapped in a `[url]` tag internally, and the `meta_hover_started` signal shows the right pop-up |
| **Storage** | `LibraryStore` (collections), `StateStore` (decks, persistent variables, history), with version migration |
| **Import and export** | One converter per format: `JsonIO`, `CanvasIO`, `MermaidExporter`, `DotExporter`, and later `GraphMLIO` |
| **UI** | Control scenes: `Main`, `LibraryPanel`, `TableEditor` (list view), `GraphView` (`GraphEdit`), `RollPanel`, `VariablesPanel` |
| **App state** | An autoload `Library` singleton that holds loaded collections and emits signals when they change |
The logic layer has no dependency on the UI, so it can be unit tested headless (for example with GUT or gdUnit4) and driven from the command line.
Suggested folder layout:
```
res://
├── core/ # data classes, roller, parsers, formatter
├── storage/ # collection and state load/save
├── io/ # import/export converters
├── ui/ # scenes and scripts
├── tests/
└── docs/
```
## 9. Milestones
1. **M1, core roller:** data model (including `details`, `card_mode` and the `graph` section), weighted selection, triggers, depth limit, JSON load and save, tests. Driven from a minimal UI or the command line.
2. **M2, editor UI:** library panel, table editor, roll panel with the result tree, and hover pop-ups for tables and entries.
3. **M3, dice mode and Card mode:** dice parser, ranged entries, warnings for gaps and overlaps, deck draws saved to local state, Reshuffle.
4. **M4, inline references and variables:** the `[[Table]]` syntax, autocomplete, missing-reference markers, chain variables, persistent `@` variables, the Variables panel.
5. **M5, formatting:** BBCode everywhere text is shown, closing open tags, removing tags for plain-text spots, toolbar and live preview, allowed-tag filter, copy as BBCode.
6. **M6, sharing and graphs:** JSON import and export, in-app graph view, JSON Canvas import and export, Mermaid and DOT export.
7. **M7, polish:** roll history, themes, Linux export build.
8. **Extras:** references to other collections (`[[Collection/Table]]`), GraphML.
## 10. Open questions
- Graph formats: does the recommended order (in-app view, JSON Canvas, Mermaid and DOT, then GraphML) suit how you'd use it?
- Persistent variables: should they belong to a collection (as planned), or should some be shared by every collection?
- Import formats: support plain text or CSV pasted from PDFs and other tools?
- Should rolls show dice values ("rolled 4 on d6") by default, or only in the expanded view?
- Name: keep "TableTower"?