Compare commits

...

16 commits

Author SHA1 Message Date
667ee1d9f0 Merge play-side UI; connect it to the collection switcher
Combines the play-side integration (refs and variables through the
roller, BBCode rendering, hover details, card decks, variables panel,
copy, reference pipes, pipe options, Build card editors) with the app
shell. Switching collections now loads that collection's decks,
variables and history and relights its last roll. Adds a Quest Hooks
and Towns table to the sample so references and variables show by
default, and updates the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:45:34 -06:00
87e578b85a Play-side UI: BBCode rendering, hover details, card decks, variables, copy, ref pipes
- Cards, result chips and the Earlier list render BBCode with RichTextLabel;
  Play rows show [[refs]] as teal chips and {vars} in brass, lit rows show the
  rolled text; missing/unset/too-deep markers are red.
- Hover pop-up (DetailsPopup) for table headers, entries with details, result
  chips and [url] metas in rendered text; items with details get a small ⓘ.
- Card-mode tables show cards left and Reshuffle; chips note reshuffles.
- Local state: decks, persistent variables and history per collection via
  StateStore (memory only when saving is off); delete_table forgets its state.
- Result tray: Copy menu (text / BBCode / with details) and a Variables tab
  (edit, re-roll, clear; last roll's chain variables read-only).
- Reference pipes drawn dashed from TextExpander.references; lit when used.
- Build mode: weight field, per-entry and table details editors, a gear
  button for table settings, pipe popover (count, save as, remove), range
  clamps use min_value(); Build cards are 300px wide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:43:01 -06:00
38e3819898 Roller: expand refs and variables through RollContext, save pipe results
Entry text is expanded by TextExpander with a shared RollContext; inline
reference rolls become children marked inline, pipes with save_as save the
child's export BBCode. MAX_DEPTH is 32. Steps carry BBCode text, depth and
inline/reshuffle flags. Adds tests/test_integration.gd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:26:33 -06:00
2e353224ab Add app-shell UI: table settings, collection switcher, import/export, endless-loop chip
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:23:21 -06:00
f3a6964044 Merge branch 'worktree-agent-a605529cce27c4de2' into pipe-board 2026-11-08 12:15:32 -06:00
cd4e13c85a Add import/export converters: JSON, JSON Canvas, Mermaid, DOT, GraphML
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:14:56 -06:00
51f2cc9e6d Merge branch 'worktree-agent-a0e26080a92828227' into pipe-board 2026-11-08 12:14:05 -06:00
29ab755a3e Add RollContext, TextExpander and Formatter for inline references and BBCode
RollContext holds chain and persistent variables, depth and the
resolve/roll hooks for one top-level roll. TextExpander expands [[Table]],
[[Table -> var]], [[3x T]], [[1d4 T]], {var}, {@var} and {@var|Table} left to
right, wrapping inserted pieces in internal [url=table:/var:/missing:/unset:/deep:]
meta tags for hover pop-ups. Formatter closes open tags, strips tags for plain
text, exports BBCode without internal markers and filters imported tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:13:25 -06:00
6a873810b0 Merge branch 'worktree-agent-a2900db2ff6409443' into pipe-board 2026-11-08 12:12:16 -06:00
438529d7a4 Merge Linux export preset 2026-11-08 12:12:03 -06:00
70dc23360f Merge branch 'worktree-agent-afc79ec9adbb5d317' into pipe-board 2026-11-08 12:12:03 -06:00
8ea83947ff Add a test-window wrapper that keeps test runs in the background
tools/test_window.sh runs the game under the window class "TableTower
Test" (via a temporary override.cfg) so a KWin window rule can keep
automated screenshot runs unfocused and behind other windows, without
affecting normal playtests from the editor. Also ignore override.cfg
and agent worktrees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:11:55 -06:00
388759f5b6 Add weights, dice expressions, pipe options, card mode and cycle check to the model
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:11:43 -06:00
6f29e9373d Add collection storage: LibraryStore, StateStore, format version 2
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:11:26 -06:00
01717a66f9 Add Linux export preset (M7)
Adds a Linux/x86_64 release preset exporting to build/linux/TableTower.x86_64
with embedded PCK, all resources included, and tests/* excluded.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 12:08:26 -06:00
60c2d03147 Build the pipe-board app in Godot
Tables are cards on a felt board, joined by copper pipes that carry a
roll from one table to the next. Play mode rolls with a flicker and a
bead down each pipe; Build mode edits names, results, ranges and pipes.

- core/: data model (RollTable, TableEntry, TowerBoard), sample board
  with a d100 table of 100 trinkets and a weighted d100 range table,
  and a Roller with a depth limit
- ui/: board with pan and zoom, pipe and port layers, collapsible table
  cards, result tray with earlier rolls, undo toasts, and a Collapse all
  / Expand all button
- assets/fonts/: Rokkitt and Atkinson Hyperlegible (SIL OFL)
- tests/test_roller.gd: headless checks for the model and roller

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 12:05:41 -06:00
102 changed files with 10078 additions and 3 deletions

6
.gitignore vendored
View file

@ -11,3 +11,9 @@
.DS_Store
Thumbs.db
.vscode/
# Temporary file written by tools/test_window.sh
override.cfg
# Agent worktrees
.claude/worktrees/

View file

@ -1,7 +1,70 @@
# TableTower
A Godot 4.7 project.
Random roll tables for tabletop games, built as a board of table cards joined by pipes.
Click the die on any table and the result flows down its pipes into the next table.
## Getting started
Made with Godot 4.7 (GDScript).
Open `project.godot` with Godot 4.7.x.
## Running
Open `project.godot` in Godot 4.7.x and press Play, or from a terminal:
```sh
godot --path .
```
## Using it
- **Play mode** is for the game table. Click a die to roll. The results flicker, one lands,
and a bead runs down any pipe into the next table. The tray at the bottom shows the whole
chain and the last few rolls.
- **Build mode** is for setting up tables. Edit names, results, weights and details in place,
add or delete results and tables, and drag a card by its header. Drag from a result's ●
onto another table to lay a pipe. Click a pipe to set how many times it rolls, save its
result as a variable, or remove it. The ⚙ on a card opens its settings: details, tags,
plain or dice table (e.g. 2d6), and Card mode. Deletions can be undone from the toast.
- **Text in results** can roll on other tables inline with `[[Table]]`, `[[3x Gems]]` or
`[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}`
keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as
`[b]bold[/b]` works anywhere you type.
- **Collections:** the switcher in the top bar holds separate sets of tables. Build mode's
**Board ▾** menu imports and exports TableTower JSON, JSON Canvas, Mermaid, DOT and GraphML.
- **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its
chance. Each range takes one pipe; laying a new one replaces the old.
- **Collapsing:** the arrow beside a table's name collapses it. A collapsed table still shows
its last result. **Collapse all / Expand all** in the top bar does every table at once.
- **Moving around:** drag the felt to pan, use the mouse wheel to scroll (Shift for sideways),
Ctrl+wheel or pinch to zoom, and **Fit** to see every table.
Collections save automatically to `user://collections/<id>.json`, and card draws, saved
variables and roll history to `user://state/state.json` (on Linux, under
`~/.local/share/godot/app_userdata/TableTower/`). Local state is never exported.
**Board ▾ → Reset sample** restores the example tables.
## Layout
```
core/ data model, roller, dice, decks, text references, storage (no UI; testable headless)
io/ import and export converters
ui/ main scene, board view, cards, pipes, ports, result tray, styles
assets/ fonts (Rokkitt and Atkinson Hyperlegible, both SIL OFL)
tests/ headless checks
docs/ design document
```
## Tests
```sh
for t in tests/test_*.gd; do godot --headless --path . -s "res://$t"; done
```
## Screenshots from the command line
```sh
tools/test_window.sh -- --screenshot=/tmp/board.png [--build] [--expand-all] [--collapse-all] \
[--roll=wilderness] [--shot-delay=0.75]
```
This uses the sample board and doesn't save anything. `tools/test_window.sh` runs the game
under the window class "TableTower Test" (via a temporary `override.cfg`), which a KWin
window rule keeps in the background without focus.

Binary file not shown.

View file

@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://dtio22kq04sn1"
path="res://.godot/imported/AtkinsonHyperlegible-Bold.ttf-88b8e4bce39666c760f25dd9a57aebce.fontdata"
[deps]
source_file="res://assets/fonts/AtkinsonHyperlegible-Bold.ttf"
dest_files=["res://.godot/imported/AtkinsonHyperlegible-Bold.ttf-88b8e4bce39666c760f25dd9a57aebce.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}

Binary file not shown.

View file

@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://dx0nfkms7uiws"
path="res://.godot/imported/AtkinsonHyperlegible-Italic.ttf-14142505a6f176216bb2ba0d516c771b.fontdata"
[deps]
source_file="res://assets/fonts/AtkinsonHyperlegible-Italic.ttf"
dest_files=["res://.godot/imported/AtkinsonHyperlegible-Italic.ttf-14142505a6f176216bb2ba0d516c771b.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}

Binary file not shown.

View file

@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://dtl7o3ylmr57k"
path="res://.godot/imported/AtkinsonHyperlegible-Regular.ttf-b1b81e810f770645a511deee33c11e03.fontdata"
[deps]
source_file="res://assets/fonts/AtkinsonHyperlegible-Regular.ttf"
dest_files=["res://.godot/imported/AtkinsonHyperlegible-Regular.ttf-b1b81e810f770645a511deee33c11e03.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}

View file

@ -0,0 +1,92 @@
Copyright 2020 Braille Institute of America, Inc.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View file

@ -0,0 +1,93 @@
Copyright 2016 The Rokkit Project Authors (https://github.com/googlefonts/RokkittFont)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

View file

@ -0,0 +1,36 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://5yn578714rcd"
path="res://.godot/imported/Rokkitt-Variable.ttf-14be251d11ed80b2da988301fba43b0d.fontdata"
[deps]
source_file="res://assets/fonts/Rokkitt-Variable.ttf"
dest_files=["res://.godot/imported/Rokkitt-Variable.ttf-14be251d11ed80b2da988301fba43b0d.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=3
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=true
preload=[]
language_support={}
script_support={}
opentype_features={}

106
core/deck_state.gd Normal file
View file

@ -0,0 +1,106 @@
class_name DeckState
extends RefCounted
## Which cards have been drawn from one card-mode table.
##
## Weighted tables treat an entry's weight as its number of copies. Ranged
## tables treat each ranged entry as one card, drawn in proportion to the
## probability of its range. State is kept per entry id, so edits behave:
## deleted entries drop out, new entries start undrawn, raising a weight adds
## copies.
## entry id -> number of copies drawn.
var drawn: Dictionary = {}
func to_dict() -> Dictionary:
return {"drawn": drawn.duplicate()}
static func from_dict(d: Dictionary) -> DeckState:
var s := DeckState.new()
var src: Variant = d.get("drawn", {})
if src is Dictionary:
for k: Variant in src:
var n: int = int(src[k])
if n > 0:
s.drawn[str(k)] = n
return s
func reshuffle() -> void:
drawn.clear()
## Copies of this entry that are in the deck in total.
static func copies_of(table: RollTable, e: TableEntry) -> int:
if table.is_ranged():
return 1 if e.has_range and table.chance(e) > 0.0 else 0
return maxi(0, e.weight)
func _remaining(table: RollTable, e: TableEntry) -> int:
return maxi(0, copies_of(table, e) - int(drawn.get(e.id, 0)))
## Vector2i(cards left, total cards) for the table as it is now.
func cards_left(table: RollTable) -> Vector2i:
var left := 0
var total := 0
for e in table.entries:
total += copies_of(table, e)
left += _remaining(table, e)
return Vector2i(left, total)
## Draws one card. Returns {"index": int, "value": int} or {} if nothing is left.
func draw(table: RollTable, rng: RandomNumberGenerator) -> Dictionary:
_prune(table)
var weights: Array[float] = []
var sum := 0.0
for e in table.entries:
var w := float(_remaining(table, e))
if table.is_ranged():
w *= table.chance(e)
weights.append(w)
sum += w
if sum <= 0.0:
return {}
var pick := rng.randf() * sum
var index := -1
for i in weights.size():
if weights[i] <= 0.0:
continue
index = i
if pick < weights[i]:
break
pick -= weights[i]
var chosen := table.entries[index]
drawn[chosen.id] = int(drawn.get(chosen.id, 0)) + 1
var value := index + 1
if table.is_ranged():
value = _value_in(table, chosen, rng)
return {"index": index, "value": value}
## A die value inside the entry's range, weighted by the dice distribution.
func _value_in(table: RollTable, e: TableEntry, rng: RandomNumberGenerator) -> int:
var dist := table.dice_obj().distribution()
var vals: Array[int] = []
var mass := 0.0
for v in range(e.range_lo, e.range_hi + 1):
if dist.has(v):
vals.append(v)
mass += float(dist[v])
var pick := rng.randf() * mass
for v in vals:
pick -= float(dist[v])
if pick < 0.0:
return v
return vals[vals.size() - 1]
## Forgets draws for entries that no longer exist.
func _prune(table: RollTable) -> void:
for k: Variant in drawn.keys():
if table.find_entry(str(k)) == null:
drawn.erase(k)

1
core/deck_state.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dxnqme8pv84v4

116
core/dice.gd Normal file
View file

@ -0,0 +1,116 @@
class_name Dice
extends RefCounted
## A dice expression such as "1d100", "2d6" or "1d8+2".
##
## Parse with Dice.parse(); check `valid` before use. Invalid expressions never
## roll and have min/max of 0.
const MAX_COUNT := 20
const MAX_SIDES := 1000
const MAX_BONUS := 9999
var valid: bool = false
var count: int = 1
var sides: int = 100
var bonus: int = 0
var _dist: Dictionary = {}
## Parses "NdM", "dM", "NdM+K" or "NdM-K". Spaces and case are ignored.
static func parse(text: String) -> Dice:
var rx := RegEx.new()
rx.compile("^(\\d*)d(\\d+)([+-]\\d+)?$")
var m := rx.search(text.strip_edges().to_lower().replace(" ", ""))
if m == null:
var bad := Dice.new()
return bad
var n: int = m.get_string(1).to_int() if m.get_string(1) != "" else 1
var k: int = m.get_string(3).to_int() if m.get_string(3) != "" else 0
return Dice.make(n, m.get_string(2).to_int(), k)
static func make(p_count: int, p_sides: int, p_bonus: int = 0) -> Dice:
var d := Dice.new()
d.count = p_count
d.sides = p_sides
d.bonus = p_bonus
d.valid = p_count >= 1 and p_count <= MAX_COUNT and p_sides >= 2 and p_sides <= MAX_SIDES and absi(p_bonus) <= MAX_BONUS
return d
static func is_valid_text(text: String) -> bool:
return parse(text).valid
func min_value() -> int:
return count + bonus if valid else 0
func max_value() -> int:
return count * sides + bonus if valid else 0
## Normalized expression, e.g. "1d100", "2d6", "1d8+2".
func expression() -> String:
var s := "%dd%d" % [count, sides]
if bonus > 0:
s += "+%d" % bonus
elif bonus < 0:
s += str(bonus)
return s
## Short label: "d100" for a single die with no bonus, otherwise the expression.
func label() -> String:
return "d%d" % sides if count == 1 and bonus == 0 else expression()
## True only for exactly 1d100.
func is_d100() -> bool:
return valid and count == 1 and sides == 100 and bonus == 0
func roll(rng: RandomNumberGenerator) -> int:
if not valid:
return 0
var total := bonus
for i in count:
total += rng.randi_range(1, sides)
return total
## Exact probability of every total: value -> probability (sums to 1).
func distribution() -> Dictionary:
if not valid:
return {}
if not _dist.is_empty():
return _dist
# cur[i] = probability of total (count_so_far + i); each die is a sliding-window sum.
var cur := PackedFloat64Array([1.0])
var face := 1.0 / float(sides)
for k in count:
var next := PackedFloat64Array()
next.resize(cur.size() + sides - 1)
var run := 0.0
for i in next.size():
if i < cur.size():
run += cur[i]
if i >= sides:
run -= cur[i - sides]
next[i] = run * face
cur = next
var lo := count + bonus
for i in cur.size():
_dist[lo + i] = cur[i]
return _dist
## Probability that the total falls within lo..hi inclusive.
func probability_between(lo: int, hi: int) -> float:
var sum := 0.0
var dist := distribution()
for v: int in dist:
if v >= lo and v <= hi:
sum += float(dist[v])
return sum

1
core/dice.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://oqwt4gld3dfa

256
core/formatter.gd Normal file
View file

@ -0,0 +1,256 @@
class_name Formatter
extends RefCounted
## BBCode helpers for Godot 4 RichTextLabel text: closing open tags, removing
## tags for plain-text spots, export without internal markers, and the allowed-tag
## filter for imported files.
##
## A "tag" here is only a tag Godot's RichTextLabel recognizes (see KNOWN_TAGS).
## Anything else in brackets, such as [x] or [optional], is ordinary text: Godot
## shows it as typed, and every function here leaves it alone.
##
## Internal markers (added by TextExpander, never typed by users) are url tags
## whose parameter starts with one of INTERNAL_META_PREFIXES, for example
## [url=table:loot]…[/url] or [url=missing:Gems]⚠ Gems[/url].
## Every tag name Godot 4's RichTextLabel parses.
const KNOWN_TAGS: Array[String] = [
"b", "i", "u", "s", "code", "char", "p", "center", "left", "right", "fill",
"indent", "url", "hint", "img", "font", "font_size", "opentype_features", "otf",
"lang", "dropcap", "color", "bgcolor", "fgcolor", "outline_size", "outline_color",
"table", "cell", "ul", "ol", "lb", "rb", "br", "hr", "lrm", "rlm", "lre", "rle",
"lro", "rlo", "pdf", "alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
"wave", "tornado", "shake", "fade", "rainbow", "pulse",
]
## Tags that stand alone and never take a closing tag.
const STANDALONE_TAGS: Array[String] = [
"lb", "rb", "br", "hr", "char", "lrm", "rlm", "lre", "rle", "lro", "rlo", "pdf",
"alm", "lri", "rli", "fsi", "pdi", "zwj", "zwnj", "wj", "shy",
]
## Tags kept by sanitize_import(). Godot lists have no item tag: inside [ul]/[ol]
## each line is one item.
const IMPORT_ALLOWED_TAGS: Array[String] = [
"b", "i", "u", "s", "code", "color", "font_size", "ul", "ol",
"center", "left", "right", "fill", "indent", "lb", "rb",
]
## url parameters with these prefixes are TextExpander's internal markers.
const INTERNAL_META_PREFIXES: Array[String] = ["table:", "var:", "missing:", "unset:", "deep:"]
## Matches one tag: [name], [/name], [name=param] or [name key=value ...].
## Parameters may contain quoted strings, so [url={"a":1}] is one tag.
const _TAG_PATTERN := "\\[(/?)([a-z_]+)((?:=|\\s)(?:\"[^\"\\n]*\"|[^\\[\\]\"\\n])*)?\\]"
static var _tag_re: RegEx = null
static var _param_res: Dictionary = {}
## Splits text into tokens, in order. Each token is a Dictionary:
## kind: "text" | "open" | "close" | "single"
## raw: String (the exact source text of the token)
## name: String (tag name, "" for text)
## param: String (everything after the name, such as "=red" or " bullet=*", "" if none)
static func tokenize(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var pos: int = 0
for m: RegExMatch in _tag_regex().search_all(text):
var name: String = m.get_string(2)
if not KNOWN_TAGS.has(name):
continue
var closing: bool = m.get_string(1) == "/"
var param: String = m.get_string(3)
if closing and param != "":
continue
if m.get_start() > pos:
out.append(_text_token(text.substr(pos, m.get_start() - pos)))
var kind: String = "close" if closing else ("single" if STANDALONE_TAGS.has(name) else "open")
out.append({"kind": kind, "raw": m.get_string(), "name": name, "param": param})
pos = m.get_end()
if pos < text.length():
out.append(_text_token(text.substr(pos)))
return out
## Returns the known tag that starts exactly at `pos`, as a token Dictionary
## (see tokenize), or an empty Dictionary when there is none.
static func tag_at(text: String, pos: int) -> Dictionary:
var m: RegExMatch = _tag_regex().search(text, pos)
if m == null or m.get_start() != pos:
return {}
var name: String = m.get_string(2)
if not KNOWN_TAGS.has(name):
return {}
var closing: bool = m.get_string(1) == "/"
if closing and m.get_string(3) != "":
return {}
var kind: String = "close" if closing else ("single" if STANDALONE_TAGS.has(name) else "open")
return {"kind": kind, "raw": m.get_string(), "name": name, "param": m.get_string(3)}
## Closes every tag left open at the end of `text`, so one entry's formatting
## can't spill into the rest of a result. A closing tag that skips over inner open
## tags ([b][i]x[/b]) first closes the inner ones. A closing tag with no matching
## open tag is escaped ([lb]/b]) so it can't close an outer tag from another entry.
static func close_open_tags(text: String) -> String:
var out: String = ""
var stack: Array[String] = []
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if kind == "open":
stack.append(name)
out += t["raw"]
elif kind == "close":
var at: int = stack.rfind(name)
if at < 0:
out += "[lb]" + (t["raw"] as String).substr(1)
continue
while stack.size() - 1 > at:
out += "[/%s]" % stack.pop_back()
stack.pop_back()
out += t["raw"]
else:
out += t["raw"]
while not stack.is_empty():
out += "[/%s]" % stack.pop_back()
return out
## Plain text for window titles, search, autocomplete and "Copy as text".
## Removes every known tag, turns [lb]/[rb] into brackets, [br] into a newline and
## [char=XXXX] into its character, drops [img] paths, and keeps unknown bracket
## text such as [x]. Internal markers become readable: a missing-table marker
## reads "⚠ Gems (missing table)", an unset variable "{hero?}".
static func strip_tags(text: String) -> String:
var out: String = ""
var urls: Array[String] = []
var in_img: int = 0
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if kind == "text":
if in_img == 0:
out += t["raw"]
elif kind == "single":
match name:
"lb": out += "["
"rb": out += "]"
"br": out += "\n"
"char":
var code: String = (t["param"] as String).trim_prefix("=").strip_edges()
if code.is_valid_hex_number():
out += String.chr(code.hex_to_int())
elif name == "img":
in_img = maxi(0, in_img + (1 if kind == "open" else -1))
elif name == "url":
if kind == "open":
urls.append(_meta_of(t["param"]))
elif not urls.is_empty():
if (urls.pop_back() as String).begins_with("missing:"):
out += " (missing table)"
return out
## Formatted text for "Copy as BBCode": keeps the user's formatting but removes
## the internal [url=table:/var:/missing:/unset:/deep:] wrappers (keeping the text
## inside them).
static func to_export_bbcode(text: String) -> String:
var out: String = ""
var urls: Array[bool] = []
for t: Dictionary in tokenize(text):
if t["name"] == "url":
if t["kind"] == "open":
var internal: bool = is_internal_meta(_meta_of(t["param"]))
urls.append(internal)
if internal:
continue
elif not urls.is_empty() and urls.pop_back():
continue
out += t["raw"]
return out
## Cleans text from an imported file. Only IMPORT_ALLOWED_TAGS survive, and only
## with harmless parameters ([color=red], [color=#ff0000], [font_size=20],
## [ul bullet=*], [ol type=a]). Every other tag is removed but its text is kept,
## except [img]…[/img], whose content (a path) is removed too. This means imported
## text can't load files, open links or forge internal markers. Unknown bracket
## text like [x] is kept. Open tags are closed at the end.
static func sanitize_import(text: String) -> String:
var out: String = ""
var in_img: int = 0
var kept: Array[String] = []
for t: Dictionary in tokenize(text):
var kind: String = t["kind"]
var name: String = t["name"]
if name == "img" and kind != "text":
in_img = maxi(0, in_img + (1 if kind == "open" else -1))
continue
if in_img > 0:
continue
if kind == "text":
out += t["raw"]
elif not IMPORT_ALLOWED_TAGS.has(name):
continue
elif kind == "close":
# Keep a closing tag only if its opening tag was kept.
var at: int = kept.rfind(name)
if at >= 0:
kept.remove_at(at)
out += t["raw"]
elif kind == "single" or _param_ok(name, t["param"]):
if kind == "open":
kept.append(name)
out += t["raw"]
return close_open_tags(out)
## Makes text show literally, so a real tag such as [b] is displayed as typed.
## Every "[" becomes "[lb]", which also stops [[references]] from expanding.
static func escape_literal(text: String) -> String:
return text.replace("[", "[lb]")
## True when a url parameter is one of TextExpander's internal markers.
static func is_internal_meta(meta: String) -> bool:
for p in INTERNAL_META_PREFIXES:
if meta.begins_with(p):
return true
return false
static func _meta_of(param: String) -> String:
var m: String = param.trim_prefix("=").strip_edges()
if m.length() >= 2 and m.begins_with("\"") and m.ends_with("\""):
m = m.substr(1, m.length() - 2)
return m
static func _param_ok(name: String, param: String) -> bool:
if param == "":
return name != "color" and name != "font_size"
var pattern: String = ""
match name:
"color": pattern = "^=(#[0-9A-Fa-f]{3,8}|[A-Za-z_]+)$"
"font_size": pattern = "^=\\d{1,3}$"
"ul": pattern = "^ bullet=[^\\[\\]\\s]{1,4}$"
"ol": pattern = "^ type=[1aAiI]$"
"indent": pattern = "^=\\d{1,2}$"
_: return false
if not _param_res.has(pattern):
var re := RegEx.new()
re.compile(pattern)
_param_res[pattern] = re
return (_param_res[pattern] as RegEx).search(param) != null
static func _tag_regex() -> RegEx:
if _tag_re == null:
_tag_re = RegEx.new()
_tag_re.compile(_TAG_PATTERN)
return _tag_re
static func _text_token(s: String) -> Dictionary:
return {"kind": "text", "raw": s, "name": "", "param": ""}

1
core/formatter.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b7qide1wl5alk

176
core/library_store.gd Normal file
View file

@ -0,0 +1,176 @@
class_name LibraryStore
extends RefCounted
## The saved collections: one JSON file per collection in <root>/collections/.
## The file name is the collection id. Local state (decks, variables, history)
## lives in the paired StateStore and is dropped when a collection is deleted.
const LEGACY_NAME := "My Tables"
## Folder that contains collections/. Default user://.
var root: String
var state: StateStore
## Messages about files that couldn't be read or written (most recent last).
var errors: PackedStringArray = []
func _init(p_root: String = "user://", p_state: StateStore = null) -> void:
root = p_root
state = p_state if p_state else StateStore.new(p_root)
func collections_dir() -> String:
return root.path_join("collections")
func path_for(id: String) -> String:
return collections_dir().path_join(id + ".json")
## True for ids that are safe to use as a file name.
static func is_valid_id(id: String) -> bool:
if id == "":
return false
for c in id:
if not (c in "abcdefghijklmnopqrstuvwxyz0123456789-_"):
return false
return true
## Lowercase letters, digits and dashes; "collection" if nothing is left.
static func slugify(text: String) -> String:
var out := ""
for c in text.to_lower():
if c in "abcdefghijklmnopqrstuvwxyz0123456789":
out += c
elif not out.ends_with("-"):
out += "-"
out = out.trim_prefix("-").trim_suffix("-")
return out if out != "" else "collection"
func exists(id: String) -> bool:
return is_valid_id(id) and FileAccess.file_exists(path_for(id))
## [{id, name}] sorted by name. Unreadable files are skipped and noted in errors.
func list() -> Array[Dictionary]:
var out: Array[Dictionary] = []
var dir := DirAccess.open(collections_dir())
if dir == null:
return out
for fname in dir.get_files():
if fname.get_extension() != "json":
continue
var id := fname.get_basename()
if not is_valid_id(id):
continue
var b := load_collection(id)
if b:
out.append({"id": id, "name": b.name})
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0)
return out
## Loads a collection, or returns null (and records why in errors) if it's
## missing or unreadable. The id always comes from the file name.
func load_collection(id: String) -> TowerBoard:
if not exists(id):
return _fail("No collection '%s'." % id)
var b := TowerBoard.new()
if not b.load_json(FileAccess.get_file_as_string(path_for(id))):
return _fail("Collection file %s is unreadable or not a collection." % path_for(id))
b.id = id
if b.name == "":
b.name = id
return b
## Saves a collection under its id. Returns false (and records why) on failure.
func save(board: TowerBoard) -> bool:
if not is_valid_id(board.id):
_fail("Can't save a collection with id '%s'." % board.id)
return false
var err := TowerBoard.write_text_atomic(path_for(board.id), board.to_json())
if err != OK:
_fail("Couldn't save %s: %s" % [path_for(board.id), error_string(err)])
return false
return true
## Makes and saves an empty collection with a unique id taken from the name.
func create(coll_name: String) -> TowerBoard:
var b := TowerBoard.new()
b.name = coll_name.strip_edges() if coll_name.strip_edges() != "" else "Untitled"
b.id = unique_id(slugify(b.name))
save(b)
return b
## Changes the display name only; the id (and so the file and state) stays.
func rename(id: String, new_name: String) -> bool:
var b := load_collection(id)
if b == null or new_name.strip_edges() == "":
return false
b.name = new_name.strip_edges()
return save(b)
## Copies a collection (tables only; local state isn't copied). Returns the copy or null.
func duplicate(id: String, new_name: String) -> TowerBoard:
var b := load_collection(id)
if b == null:
return null
b.name = new_name.strip_edges() if new_name.strip_edges() != "" else b.name + " copy"
b.id = unique_id(slugify(b.name))
return b if save(b) else null
## Deletes the file and the collection's local state.
func delete(id: String) -> bool:
if not exists(id):
return false
if DirAccess.remove_absolute(path_for(id)) != OK:
_fail("Couldn't delete %s." % path_for(id))
return false
state.forget_collection(id)
state.save()
return true
## base, or base-2, base-3 ... whichever isn't taken.
func unique_id(base: String) -> String:
var id := base
var n := 2
while exists(id):
id = "%s-%d" % [base, n]
n += 1
return id
## First run: if the old single-board file exists and there are no collections,
## imports it as a collection and renames the old file to board.json.bak.
## Returns the imported collection, or null if nothing was migrated.
func migrate_legacy(legacy_path: String = "") -> TowerBoard:
if legacy_path == "":
legacy_path = root.path_join("board.json")
if not FileAccess.file_exists(legacy_path) or not list().is_empty():
return null
var b := TowerBoard.load_saved(legacy_path)
if b == null:
_fail("Old board file %s is unreadable; leaving it alone." % legacy_path)
return null
b.name = LEGACY_NAME
b.id = unique_id(slugify(LEGACY_NAME))
if not save(b):
return null
DirAccess.remove_absolute(legacy_path + ".bak")
if DirAccess.rename_absolute(legacy_path, legacy_path + ".bak") != OK:
_fail("Imported %s but couldn't rename it to .bak." % legacy_path)
return b
func _fail(message: String) -> TowerBoard:
errors.append(message)
push_warning(message)
return null

View file

@ -0,0 +1 @@
uid://c0pij64vq2ydy

114
core/roll_context.gd Normal file
View file

@ -0,0 +1,114 @@
class_name RollContext
extends RefCounted
## State for one top-level roll: chain variables, the collection's persistent
## variables, the RNG, the current depth and the hooks back into the roller.
##
## Create one per top-level roll and share it with every table rolled in that
## chain (inline references and pipes alike).
##
## [b]Hooks the roller must set:[/b]
## - [member resolve_table]: [code]func(name_or_id: String) -> String[/code]. Returns
## the table id, or "" when there is no such table. It should match the id
## exactly or the name case-insensitively, ignoring BBCode in names;
## [method normalize_name] does the name cleanup.
## - [member roll_table]: [code]func(table_id: String, depth: int) -> Dictionary[/code].
## Rolls the table at the given depth and returns a result node.
##
## [b]Node contract for roll_table:[/b]
## - Returns [code]{}[/code] (empty) if the table doesn't exist; it is then shown
## with the missing-table marker.
## - Otherwise the node must have [code]"summary": String[/code], the BBCode text
## that replaces the reference inline (normally the node's expanded entry text).
## It may contain internal [url] markers from deeper expansions.
## - Every other key (table, entry, value, children, stop, ...) belongs to the
## roller; TextExpander only collects the nodes in its "children" output.
## - When the roller itself stops (depth limit, empty table), it still returns a
## node whose summary explains why, for example [method TextExpander.deep_marker].
## - roll_table may change [member depth] while it runs; TextExpander restores it.
const DEFAULT_MAX_DEPTH := 32
## Chain variables: name (no "@") -> String value. Fresh for every top-level roll.
var chain_vars: Dictionary = {}
## The collection's persistent variables, owned and saved elsewhere:
## name (without the "@") -> {"value": String, "source": table_id}.
## This is the caller's Dictionary itself, not a copy, so saves show up there.
var persistent_vars: Dictionary = {}
## True once save() has written a persistent variable in this roll, so the caller
## knows local state needs saving.
var persistent_changed: bool = false
## Depth of the text currently being expanded. References in that text are
## rolled at this depth. The roller sets it (depth + 1 for an entry's text).
var depth: int = 0
## References at a depth greater than this show the "chain too deep" marker.
var max_depth: int = DEFAULT_MAX_DEPTH
var rng: RandomNumberGenerator = null
## func(name_or_id: String) -> String (table id or "").
var resolve_table: Callable = Callable()
## func(table_id: String, depth: int) -> Dictionary (a result node).
var roll_table: Callable = Callable()
func _init(p_persistent: Dictionary = {}, p_rng: RandomNumberGenerator = null) -> void:
persistent_vars = p_persistent
rng = p_rng if p_rng != null else RandomNumberGenerator.new()
## True for names that start with "@" (persistent variables).
static func is_persistent(name: String) -> bool:
return name.strip_edges().begins_with("@")
## Saves a value. Names starting with "@" go to the persistent variables
## (stored without the "@", with the source table id); others to the chain.
func save(name: String, value: String, source_id: String = "") -> void:
var n: String = name.strip_edges()
if n.begins_with("@"):
n = n.substr(1)
if n == "":
return
persistent_vars[n] = {"value": value, "source": source_id}
persistent_changed = true
elif n != "":
chain_vars[n] = value
## Returns the saved String value, or null when the variable isn't set.
## "@name" reads a persistent variable, "name" a chain variable.
func lookup(name: String) -> Variant:
var n: String = name.strip_edges()
if n.begins_with("@"):
var entry: Variant = persistent_vars.get(n.substr(1))
if entry is Dictionary:
return str((entry as Dictionary).get("value", ""))
if entry != null:
return str(entry)
return null
if chain_vars.has(n):
return str(chain_vars[n])
return null
## Calls resolve_table, returning "" if the hook isn't set.
func resolve(name_or_id: String) -> String:
if not resolve_table.is_valid():
return ""
return str(resolve_table.call(name_or_id))
## Calls roll_table at the current depth and restores depth afterwards.
## Returns {} if the hook isn't set or the roller returned something that isn't
## a Dictionary.
func roll(table_id: String) -> Dictionary:
if not roll_table.is_valid():
return {}
var d: int = depth
var result: Variant = roll_table.call(table_id, d)
depth = d
return result as Dictionary if result is Dictionary else {}
## Lowercase, trimmed, BBCode-free form of a table name, for matching
## [[references]] against names: normalize_name("[b]Gems[/b] ") == "gems".
static func normalize_name(name: String) -> String:
return Formatter.strip_tags(name).strip_edges().to_lower()

1
core/roll_context.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dpcaah4i7iu88

196
core/roll_table.gd Normal file
View file

@ -0,0 +1,196 @@
class_name RollTable
extends RefCounted
## A named list of entries placed on the board.
##
## Plain tables pick by entry weight (6 equal entries = d6). If any entry has a
## range, the table becomes a ranged dice table (1d100 by default, or any dice
## expression) where the probability mass of each range sets its chance.
const DEFAULT_DICE := "1d100"
var id: String = ""
var name: String = ""
var position: Vector2 = Vector2.ZERO
var collapsed: bool = false
## Longer description (may contain BBCode).
var details: String = ""
var tags: Array[String] = []
## Dice expression for ranged tables, e.g. "1d100", "2d6", "1d8+2".
var dice: String = DEFAULT_DICE
## Card mode: entries are drawn without replacement until the deck is empty.
var card_mode: bool = false
## What happens when the deck runs out: "reshuffle" or "stop".
var deck_empty: String = "reshuffle"
var entries: Array[TableEntry] = []
var _dice_cache: Dice = null
var _dice_cache_text: String = ""
func _init(p_id: String = "", p_name: String = "") -> void:
id = p_id
name = p_name
func is_ranged() -> bool:
for e in entries:
if e.has_range:
return true
return false
## The parsed dice expression (falls back to 1d100 if `dice` is invalid).
func dice_obj() -> Dice:
if _dice_cache == null or _dice_cache_text != dice:
var d := Dice.parse(dice)
_dice_cache = d if d.valid else Dice.make(1, 100)
_dice_cache_text = dice
return _dice_cache
## Label for the dice: "d100", "2d6", "1d8+2". Plain tables label by entry count.
func dice_label() -> String:
if is_ranged():
return dice_obj().label()
return "d%d" % die_size()
## Lowest value that can be rolled (1 on plain tables).
func min_value() -> int:
return dice_obj().min_value() if is_ranged() else 1
## Highest value that can be rolled. Plain tables: the entry count.
func die_size() -> int:
if is_ranged():
return dice_obj().max_value()
return entries.size()
func total_weight() -> int:
var w := 0
for e in entries:
w += maxi(0, e.weight)
return w
## Formats a die value the way printed tables do: d100 values are two digits
## and 100 is written "00".
func fmt(value: int) -> String:
var two_digit := dice_obj().is_d100() if is_ranged() else entries.size() == 100
if two_digit:
return "00" if value == 100 else "%02d" % value
return str(value)
func num_label(e: TableEntry, index: int) -> String:
if not e.has_range:
return fmt(index + 1)
if e.range_lo == e.range_hi:
return fmt(e.range_lo)
return "%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)]
## Chance (0–1) that a roll lands on this entry.
func chance(e: TableEntry) -> float:
if is_ranged():
if not e.has_range:
return 0.0
return dice_obj().probability_between(e.range_lo, e.range_hi)
var total := total_weight()
return float(maxi(0, e.weight)) / float(total) if total > 0 else 0.0
func entry_index_for(value: int) -> int:
for i in entries.size():
var e := entries[i]
if e.has_range and value >= e.range_lo and value <= e.range_hi:
return i
return -1
func find_entry(eid: String) -> TableEntry:
for e in entries:
if e.id == eid:
return e
return null
## Describes gaps, overlaps and out-of-span ranges in a ranged table, or "" when clean.
func range_problems() -> String:
if not is_ranged():
return ""
var lo := min_value()
var hi := die_size()
var hits := PackedInt32Array()
hits.resize(hi + 1)
var outside := PackedStringArray()
for e in entries:
if not e.has_range:
continue
for v in range(maxi(lo, e.range_lo), mini(hi, e.range_hi) + 1):
hits[v] += 1
if e.range_lo < lo or e.range_hi > hi:
outside.append("%s–%s" % [fmt(e.range_lo), fmt(e.range_hi)])
var gaps := _runs(hits, lo, hi, func(h: int) -> bool: return h == 0)
var overlaps := _runs(hits, lo, hi, func(h: int) -> bool: return h > 1)
var parts := PackedStringArray()
if gaps != "":
parts.append("No result for %s." % gaps)
if overlaps != "":
parts.append("%s matches more than one result." % overlaps)
if not outside.is_empty():
parts.append("%s is outside %s–%s." % [", ".join(outside), fmt(lo), fmt(hi)])
return " ".join(parts)
func _runs(hits: PackedInt32Array, lo: int, n: int, test: Callable) -> String:
var out := PackedStringArray()
var start := -1
for v in range(lo, n + 2):
var on: bool = v <= n and test.call(hits[v])
if on and start < 0:
start = v
elif not on and start >= 0:
out.append(fmt(start) if start == v - 1 else "%s–%s" % [fmt(start), fmt(v - 1)])
start = -1
return ", ".join(out)
func to_dict() -> Dictionary:
var list: Array = []
for e in entries:
list.append(e.to_dict())
var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y), "entries": list}
if collapsed:
d["collapsed"] = true
if details != "":
d["details"] = details
if not tags.is_empty():
d["tags"] = tags.duplicate()
if is_ranged():
d["dice"] = dice
if card_mode:
d["card_mode"] = true
if deck_empty != "reshuffle":
d["deck_empty"] = deck_empty
return d
static func from_dict(d: Dictionary) -> RollTable:
var t := RollTable.new(str(d.get("id", "")), str(d.get("name", "")))
t.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0)))
t.collapsed = bool(d.get("collapsed", false))
t.details = str(d.get("details", ""))
for tag: Variant in d.get("tags", []):
t.tags.append(str(tag))
if d.has("dice"):
t.dice = str(d["dice"])
elif int(d.get("die", 0)) > 1:
t.dice = "1d%d" % int(d["die"])
t.card_mode = bool(d.get("card_mode", false))
t.deck_empty = "stop" if str(d.get("deck_empty", "reshuffle")) == "stop" else "reshuffle"
for ed: Variant in d.get("entries", []):
if ed is Dictionary:
t.entries.append(TableEntry.from_dict(ed))
return t

1
core/roll_table.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ccjtqk3cakkc2

289
core/roller.gd Normal file
View file

@ -0,0 +1,289 @@
class_name Roller
extends RefCounted
## Rolls a table and follows its pipes and inline references, producing a
## result tree.
##
## Each node is a Dictionary:
## table: RollTable, value: int (die value), index: int, entry: TableEntry,
## summary: String (the entry text with [[refs]] and {vars} expanded, as
## BBCode with TextExpander's internal [url] markers),
## children: Array of nodes (inline reference rolls first, marked
## "inline": true, then pipe rolls in pipe order),
## and "stop": String when the chain couldn't continue (its summary then
## explains why).
## Deepest level a chain can reach before it stops (matches RollContext).
const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
## A RollContext wired to this board: it resolves [[names]] against the board's
## tables and rolls inline references through the roller. `persistent` is the
## collection's persistent variables (name without "@" -> {value, source}),
## shared, not copied. `decks` maps table id to DeckState for card-mode tables,
## also shared.
static func new_context(board: TowerBoard, rng: RandomNumberGenerator, persistent: Dictionary = {}, decks: Dictionary = {}) -> RollContext:
var ctx := RollContext.new(persistent, rng)
ctx.max_depth = MAX_DEPTH
ctx.set_meta("decks", decks)
# A weak reference, so the context doesn't keep itself alive through its hook.
var wr: WeakRef = weakref(ctx)
ctx.resolve_table = func(name_or_id: String) -> String:
return resolve(board, name_or_id)
ctx.roll_table = func(id: String, depth: int) -> Dictionary:
var c: RollContext = wr.get_ref()
return {} if c == null else _roll(board, id, depth, c)
return ctx
## Table id for a [[reference]]: an exact id, or a name matched
## case-insensitively without BBCode. "" if there's no such table.
static func resolve(board: TowerBoard, name_or_id: String) -> String:
var key := name_or_id.strip_edges()
if board.get_table(key) != null:
return key
var want := RollContext.normalize_name(key)
if want == "":
return ""
for t in board.tables:
if RollContext.normalize_name(t.name) == want:
return t.id
return ""
## Rolls `table_id` and everything its pipes and references lead to.
## `decks` maps table id to DeckState for card-mode tables; missing decks are
## created in it on demand. `ctx` carries the variables for the whole chain.
## Without one, a fresh context (no persistent variables) is made around
## `decks`; a context from new_context() brings its own decks and `decks` is
## then ignored. Extra node keys: "save_as" (on nodes reached through a pipe
## that saves), "reshuffled" (card deck was refilled for this draw), "inline"
## (rolled by a [[reference]] in the parent's text).
static func roll(board: TowerBoard, table_id: String, rng: RandomNumberGenerator, depth: int = 0, decks: Dictionary = {}, ctx: RollContext = null) -> Dictionary:
if ctx == null:
ctx = new_context(board, rng, {}, decks)
elif not ctx.has_meta("decks"):
ctx.set_meta("decks", decks)
return _roll(board, table_id, depth, ctx)
static func _stop(t: RollTable, why: String, extra: Dictionary = {}) -> Dictionary:
var node := {"table": t, "stop": why, "summary": why, "children": []}
node.merge(extra, true)
return node
static func _roll(board: TowerBoard, table_id: String, depth: int, ctx: RollContext) -> Dictionary:
var t := board.get_table(table_id)
if t == null:
return {}
var rng := ctx.rng
if depth > MAX_DEPTH:
return _stop(t, "Chain stopped after %d tables" % MAX_DEPTH, {"summary": TextExpander.deep_marker(t.id)})
if t.entries.is_empty():
return _stop(t, "This table has no results")
var index: int
var value: int
var reshuffled := false
if t.card_mode:
var decks: Dictionary = ctx.get_meta("decks", {})
if not decks.has(t.id):
decks[t.id] = DeckState.new()
var deck: DeckState = decks[t.id]
if deck.cards_left(t).y <= 0:
return _stop(t, "This table has no results")
if deck.cards_left(t).x <= 0:
if t.deck_empty == "stop":
return _stop(t, "Deck empty")
deck.reshuffle()
reshuffled = true
var card := deck.draw(t, rng)
index = int(card["index"])
value = int(card["value"])
elif t.is_ranged():
value = t.dice_obj().roll(rng)
index = t.entry_index_for(value)
if index < 0:
return _stop(t, "No result for %s" % t.fmt(value), {"value": value})
else:
index = _pick_weighted(t, rng)
if index < 0:
return _stop(t, "No result can come up")
value = index + 1
var e := t.entries[index]
ctx.depth = depth + 1
var expanded := TextExpander.expand(e.text, ctx)
var children: Array = []
for c: Dictionary in expanded["children"]:
c["inline"] = true
children.append(c)
for p in e.pipes:
var save := e.save_for(p)
for k in e.count_for(p):
var child := _roll(board, p, depth + 1, ctx)
if child.is_empty():
break
if save != "":
child["save_as"] = save
if not child.has("stop"):
ctx.save(save, Formatter.to_export_bbcode(str(child.get("summary", ""))), p)
children.append(child)
var node := {"table": t, "index": index, "value": value, "entry": e, "children": children,
"summary": expanded["text"]}
if reshuffled:
node["reshuffled"] = true
return node
## Index of a weighted random entry, or -1 if every weight is 0.
static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
var total := t.total_weight()
if total <= 0:
return -1
var pick := rng.randi_range(0, total - 1)
for i in t.entries.size():
pick -= maxi(0, t.entries[i].weight)
if pick < 0:
return i
return -1
## Ids of tables that can never finish rolling: every result they can give
## leads, through pipes, back into such a table. A table that loops on only
## some of its entries is fine.
static func endless_cycles(board: TowerBoard) -> Array[String]:
var done := {}
var changed := true
while changed:
changed = false
for t in board.tables:
if done.has(t.id):
continue
if _can_finish(t, board, done):
done[t.id] = true
changed = true
var out: Array[String] = []
for t in board.tables:
if not done.has(t.id):
out.append(t.id)
return out
static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bool:
if t.entries.is_empty():
return true
for e in t.entries:
if t.is_ranged():
if not e.has_range or t.chance(e) <= 0.0:
continue
elif e.weight <= 0:
continue
var ok := true
for p in e.pipes:
if board.get_table(p) != null and not done.has(p):
ok = false
break
if ok:
return true
# No entry can come up at all: the roll just stops.
for e in t.entries:
if (t.is_ranged() and e.has_range and t.chance(e) > 0.0) or (not t.is_ranged() and e.weight > 0):
return false
return true
## One line of the result tray for a single node. Plain data only, because it
## is saved in the roll history. "text" is BBCode with internal markers.
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
var t: RollTable = n["table"]
var step := {
"table": t.name,
"table_id": t.id,
"num": t.fmt(n["value"]) if n.has("value") else "",
"die": t.die_size(),
"dice": t.dice_label(),
"text": str(n.get("summary", n.get("stop", ""))),
"depth": depth,
}
if n.has("entry"):
step["entry_id"] = (n["entry"] as TableEntry).id
if n.has("stop"):
step["stop"] = true
if n.get("inline", false):
step["inline"] = true
if n.get("reshuffled", false):
step["reshuffled"] = true
if n.has("save_as"):
step["save_as"] = n["save_as"]
return step
## The whole chain in the order it was rolled.
static func flatten(n: Dictionary, out: Array = [], depth: int = 0) -> Array:
if n.is_empty():
return out
out.append(step_of(n, depth))
for c in n["children"]:
flatten(c, out, depth + 1)
return out
static func reaches(n: Dictionary, table_id: String) -> bool:
if n.is_empty():
return false
if (n["table"] as RollTable).id == table_id:
return true
for c in n["children"]:
if reaches(c, table_id):
return true
return false
## Marks every entry, pipe and reference pipe along the chain as lit. When
## given, `texts` gets each lit entry's expanded text (entry key -> BBCode).
static func collect_lit(n: Dictionary, entries: Dictionary, pipes: Dictionary, texts: Dictionary = {}) -> void:
if n.is_empty() or n.has("stop"):
return
var t: RollTable = n["table"]
var e: TableEntry = n["entry"]
entries[entry_key(t.id, e.id)] = true
texts[entry_key(t.id, e.id)] = str(n.get("summary", e.text))
for c in n["children"]:
pipes[link_key(t.id, e.id, c)] = true
collect_lit(c, entries, pipes, texts)
static func entry_key(table_id: String, entry_id: String) -> String:
return table_id + ":" + entry_id
static func pipe_key(table_id: String, entry_id: String, to_id: String) -> String:
return "%s:%s>%s" % [table_id, entry_id, to_id]
## Key of a reference pipe: a [[reference]] in an entry's text to another table.
static func ref_key(table_id: String, entry_id: String, to_id: String) -> String:
return "%s:%s~%s" % [table_id, entry_id, to_id]
static func is_ref_key(key: String) -> bool:
return key.contains("~")
## The pipe or reference-pipe key that led from an entry to child node `c`.
static func link_key(table_id: String, entry_id: String, c: Dictionary) -> String:
var to := (c["table"] as RollTable).id
return ref_key(table_id, entry_id, to) if c.get("inline", false) else pipe_key(table_id, entry_id, to)
## Ids of the tables an entry's text references, resolved against the board,
## without duplicates or missing tables.
static func ref_targets(board: TowerBoard, text: String) -> Array[String]:
var out: Array[String] = []
if not text.contains("[[") and not text.contains("|"):
return out
var res := func(name: String) -> String: return resolve(board, name)
for name in TextExpander.references(text, res):
var id := resolve(board, name)
if id != "" and not out.has(id):
out.append(id)
return out

1
core/roller.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dioyoj7ibpqsa

110
core/sample_board.gd Normal file
View file

@ -0,0 +1,110 @@
class_name SampleBoard
extends RefCounted
## The example board: road encounters, loot chains, a d100 ranged travel table
## and a d100 table of 100 unique trinkets.
const TRINKETS := [
"A brass key that's warm to the touch", "A glass eye that follows movement", "A tin whistle only dogs can hear", "A pressed flower that never wilts",
"A tiny portrait of a stranger", "A compass that points to the nearest well", "A wooden die with seven sides", "A silver spoon bent into a ring",
"A sealed letter addressed to you", "A bell with no clapper that still rings", "A jar of buttons from a hundred coats", "A dragon scale the size of a coin",
"A candle that burns cold", "A deck of cards missing every queen", "A bird skull painted gold", "A map of a city that doesn't exist",
"A thimble of sand that never spills", "A ribbon embroidered with your name", "A clockwork beetle that wants winding", "A pebble that is always wet",
"A fishhook carved from bone", "A coin from a kingdom that fell", "A lock of silver hair tied with string", "A broken hourglass, sand still falling",
"A soup recipe written in blood", "A doll with one button eye", "A chess piece shaped like a crow", "A vial of fog",
"A tooth with a tiny keyhole", "A feather that falls upward", "An empty locket that hums", "A spool of thread that never runs out",
"A ring too small for any finger", "A wax seal of a three-eyed owl", "A shell that whispers in a strange tongue", "A rusted crown sized for a cat",
"A knot no blade can cut", "A page torn from a spellbook", "A marble with a storm inside", "A tiny saddle for a mouse",
"A mirror shard that shows yesterday", "A reed flute that plays by itself", "A holed stone that shows stars at noon", "A child's drawing of you",
"A spice tin of dried fireflies", "A wooden sword notched for every win", "A pair of dice that always roll the same", "An acorn that grows back each night",
"A tarnished medal for bravery", "A bottle with a ship of bones inside", "A glove that's always warm", "A bookmark from a library that burned",
"A walnut that rattles", "A copper ring stamped with a moon", "A lantern wick that relights itself", "A painted egg that is far too heavy",
"A bag of salt from a distant sea", "A wanted poster with no face", "A spinning top that never falls", "A snuff box full of teeth",
"A crystal that glows near goblins", "A riddle carved into a spoon handle", "A scarf that smells of summer rain", "A key with no teeth",
"A thumb-sized statue of a sleeping god", "A bone flute with one hole", "An inkwell that refills with black water", "A quill that writes only in red",
"A pocket watch running backwards", "A wedding ring with both names scratched out", "An eggshell painted with a map", "A pouch of mismatched dice",
"A tinderbox that sparks blue", "A prayer bead from an unknown faith", "A playing card with your face on it", "A cracked monocle",
"A tiny cage with the door open", "A pressed four-leaf clover", "A seashell found far inland", "A gold tooth",
"A badge from the city watch", "A charm bracelet with one charm missing", "A bundle of letters tied with twine", "A chip of a giant's fingernail",
"A rope that ties itself", "A stone that floats", "A song trapped in a bottle", "A carved wooden fish",
"A toy soldier missing an arm", "A coin that always lands on its edge", "A candle stub that smells of home", "A brooch shaped like a spider",
"A sliver of moonlight in a vial", "An arrowhead made of glass", "A dried rose from a grave", "A bone die marked with runes",
"A tiny shield with an unknown crest", "A horseshoe for a six-legged horse", "A note: “Don't trust the innkeeper”", "An egg that is warm and ticking",
]
static func create() -> TowerBoard:
var trinket_rows: Array = []
for s in TRINKETS:
trinket_rows.append([s])
# [id, name, position, entries: [text, pipes?, range?, {details?, weight?}?], options?]
# options: dice, collapsed, details, tags, card_mode
var spec: Array = [
["wilderness", "Wilderness Travel", Vector2(40, 180), [
["Travelers on the road", ["road"], [1, 30], {"details": "Most days the road is just the road. Roll on the Road Encounter table to see who is on it."}],
["Beasts on the hunt", ["monsters"], [31, 50]],
["A peddler's cart", ["wares"], [51, 65]],
["Something glints in the grass", ["loot"], [66, 80]],
["A stranger at the campfire", ["names"], [81, 95]],
["An odd find", ["trinkets"], [96, 100]],
], {"dice": "1d100", "details": "Roll once per [b]travel day[/b]. Each result sends you to a table for the details of what the party meets.", "tags": ["travel"]}],
["road", "Road Encounter", Vector2(390, 40), [
["Bandits ambush the party", ["loot"]], ["A merchant caravan", ["wares"]],
["Something big in the trees", ["monsters"]], ["A quiet stretch of road"],
["A sudden storm rolls in"], ["A lost traveler", ["names"]],
]],
["trinkets", "Curious Trinkets", Vector2(390, 420), trinket_rows, {"collapsed": true}],
["monsters", "Monsters", Vector2(740, 20), [
["Owlbear", ["loot"], null, {"details": "[b]Owlbear[/b]: AC 13, 59 HP. Multiattack: beak and claws. Grabs and crushes anything that comes close to its nest."}],
["Giant spider"],
["Troll", ["loot"], null, {"details": "[b]Troll[/b]: AC 15, 84 HP. Regenerates 10 HP each turn unless hit by [i]fire[/i] or [i]acid[/i]."}],
["Wyvern"],
], {"tags": ["combat"]}],
["wares", "Merchant Wares", Vector2(740, 300), [["Bolts of silk"], ["Rare spices"], ["Lamp oil"], ["A crate of strange eggs"]]],
["loot", "Loot", Vector2(1090, 60), [
["A pouch of gold", [], null, {"weight": 3}], ["A weapon", ["weapons"]], ["A healing potion"],
["A torn map"], ["A gemstone"], ["Nothing but lint"],
], {"tags": ["treasure"]}],
["names", "Traveler Names", Vector2(1090, 400), [["Aldric"], ["Brenna"], ["Corvin"], ["Dagny"], ["Elowen"], ["Fenn"]]],
["weapons", "Weapons", Vector2(1440, 60), [["Dagger"], ["Sword", ["quality"]], ["Hand axe"], ["Shortbow"]]],
["quality", "Sword Quality", Vector2(1790, 130), [["Rusty"], ["Notched"], ["Fine"], ["Elven-forged"]]],
["party_roles", "Party Roles", Vector2(1440, 330), [
["Scout"], ["Map keeper"], ["Quartermaster"], ["Lookout"], ["Cook"], ["Diplomat"],
], {"card_mode": true, "details": "Hand out one role per player. Each role is dealt once until everyone has had one, then the deck is reshuffled."}],
["weather", "Weather", Vector2(1790, 380), [
["Storm", [], [2, 3]], ["Rain", [], [4, 5]], ["Overcast", [], [6, 8]],
["Clear skies", [], [9, 10]], ["Heat wave", [], [11, 12]],
], {"dice": "2d6", "details": "Roll [b]2d6[/b]. Middling weather is the most common."}],
# Shows inline [[references]], a chain variable and a persistent {@town}.
["quest_hooks", "Quest Hooks", Vector2(40, 560), [
["[[Traveler Names -> patron]] begs you to recover [[Loot]] from the ruins near {@town|Towns}. {patron} pays well."],
["The mayor of {@town|Towns} posts a bounty: [i]bring back [[Monsters]] alive[/i]."],
["[[Traveler Names]] swears the [[Curious Trinkets]] they found is cursed."],
], {"details": "Opening hooks for a session. [b]{@town}[/b] is the party's current town; it's rolled once, then reused until you clear it."}],
["towns", "Towns", Vector2(740, 560), [["Millbrook"], ["Saltmere"], ["Grey Harrow"], ["Kettle Ford"]]],
]
var board := TowerBoard.new()
for s in spec:
var t := RollTable.new(s[0], s[1])
t.position = s[2]
var opts: Dictionary = s[4] if s.size() > 4 else {}
t.dice = str(opts.get("dice", RollTable.DEFAULT_DICE))
t.collapsed = bool(opts.get("collapsed", false))
t.details = str(opts.get("details", ""))
for tag in opts.get("tags", []):
t.tags.append(tag)
t.card_mode = bool(opts.get("card_mode", false))
for row in s[3]:
var e := TableEntry.new(TowerBoard.new_id("e"), row[0])
if row.size() > 1:
for p in row[1]:
e.add_pipe(p)
if row.size() > 2 and row[2] != null:
e.has_range = true
e.range_lo = row[2][0]
e.range_hi = row[2][1]
if row.size() > 3:
e.details = str(row[3].get("details", ""))
e.weight = int(row[3].get("weight", 1))
t.entries.append(e)
board.tables.append(t)
return board

1
core/sample_board.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dn40x65nhjxqj

204
core/state_store.gd Normal file
View file

@ -0,0 +1,204 @@
class_name StateStore
extends RefCounted
## Local state that is never exported: Card mode decks, persistent variables,
## roll history and small settings. Everything is keyed by collection and table
## ids, so renaming a collection or table doesn't break it.
##
## Stored as one file, <root>/state/state.json. Mutators only mark the store
## dirty (cheap); call save() to write, which does nothing if nothing changed.
## Decks are opaque Dictionaries (whatever DeckState.to_dict() produces).
const FORMAT_VERSION := 1
const HISTORY_CAP := 50
## Folder that contains state/. Default user://.
var root: String
var _data: Dictionary = {}
var _loaded := false
var _dirty := false
func _init(p_root: String = "user://") -> void:
root = p_root
func state_path() -> String:
return root.path_join("state/state.json")
# ---------- Decks ----------
func get_deck(cid: String, tid: String) -> Dictionary:
var by_c: Dictionary = _section("decks").get(cid, {})
var d: Variant = by_c.get(tid, {})
return (d as Dictionary).duplicate(true) if d is Dictionary else {}
func set_deck(cid: String, tid: String, deck: Dictionary) -> void:
_bucket("decks", cid)[tid] = deck.duplicate(true)
_dirty = true
## Reshuffle: forgets the deck so the next draw starts a fresh one.
func clear_deck(cid: String, tid: String) -> void:
var by_c: Dictionary = _section("decks").get(cid, {})
if by_c.erase(tid):
_dirty = true
# ---------- Persistent variables ----------
# {name: {"value": String, "source": table_id}}
func get_variables(cid: String) -> Dictionary:
var v: Variant = _section("variables").get(cid, {})
return (v as Dictionary).duplicate(true) if v is Dictionary else {}
func set_variable(cid: String, var_name: String, value: String, source: String = "") -> void:
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
_dirty = true
func clear_variable(cid: String, var_name: String) -> void:
var by_c: Dictionary = _section("variables").get(cid, {})
if by_c.erase(var_name):
_dirty = true
func clear_variables(cid: String) -> void:
if _section("variables").erase(cid):
_dirty = true
# ---------- History ----------
# One global list, most recent first, capped at HISTORY_CAP. Callers put a
# "collection" id in each record; get_history(cid) filters by it.
func add_history(record: Dictionary) -> void:
var list: Array = _section_list("history")
list.push_front(record.duplicate(true))
if list.size() > HISTORY_CAP:
list.resize(HISTORY_CAP)
_dirty = true
## All records, or only those whose "collection" is cid when cid isn't empty.
func get_history(cid: String = "") -> Array[Dictionary]:
var out: Array[Dictionary] = []
for r in _section_list("history"):
if r is Dictionary and (cid == "" or str((r as Dictionary).get("collection", "")) == cid):
out.append((r as Dictionary).duplicate(true))
return out
## Clears all history, or only a collection's records when cid isn't empty.
func clear_history(cid: String = "") -> void:
var list: Array = _section_list("history")
if cid == "":
list.clear()
else:
for i in range(list.size() - 1, -1, -1):
if list[i] is Dictionary and str((list[i] as Dictionary).get("collection", "")) == cid:
list.remove_at(i)
_dirty = true
# ---------- Settings ----------
func get_setting(key: String, default: Variant = null) -> Variant:
return _section("settings").get(key, default)
func set_setting(key: String, value: Variant) -> void:
var s := _section("settings")
if not s.has(key) or s[key] != value:
s[key] = value
_dirty = true
# ---------- Forgetting ----------
## Drops everything stored for a collection (decks, variables, its history).
func forget_collection(cid: String) -> void:
_section("decks").erase(cid)
_section("variables").erase(cid)
clear_history(cid)
if str(_section("settings").get("last_collection", "")) == cid:
_section("settings").erase("last_collection")
_dirty = true
## Drops a table's deck and the variables it set.
func forget_table(cid: String, tid: String) -> void:
clear_deck(cid, tid)
var vars: Dictionary = _section("variables").get(cid, {})
for k in vars.keys():
var v: Variant = vars[k]
if v is Dictionary and str((v as Dictionary).get("source", "")) == tid:
vars.erase(k)
_dirty = true
# ---------- Saving ----------
func is_dirty() -> bool:
return _dirty
## Writes the file if anything changed. Returns false only on a write error.
func save() -> bool:
if not _loaded or not _dirty:
return true
var out := _data.duplicate()
out["format_version"] = FORMAT_VERSION
var err := TowerBoard.write_text_atomic(state_path(), JSON.stringify(out, " "))
if err != OK:
push_warning("Couldn't save local state to %s: %s" % [state_path(), error_string(err)])
return false
_dirty = false
return true
## Re-reads the file, dropping unsaved changes. A corrupt file is moved aside to
## state.json.corrupt and the store starts empty.
func reload() -> void:
_loaded = true
_dirty = false
_data = {}
var path := state_path()
if not FileAccess.file_exists(path):
return
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
if parsed is Dictionary:
_data = parsed
return
push_warning("Local state file %s is unreadable; starting fresh (old copy kept as .corrupt)." % path)
DirAccess.rename_absolute(path, path + ".corrupt")
# ---------- Internals ----------
func _ensure() -> void:
if not _loaded:
reload()
func _section(key: String) -> Dictionary:
_ensure()
if not (_data.get(key) is Dictionary):
_data[key] = {}
return _data[key]
func _section_list(key: String) -> Array:
_ensure()
if not (_data.get(key) is Array):
_data[key] = []
return _data[key]
func _bucket(section: String, cid: String) -> Dictionary:
var s := _section(section)
if not (s.get(cid) is Dictionary):
s[cid] = {}
return s[cid]

1
core/state_store.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bhci5uoa7vbhp

119
core/table_entry.gd Normal file
View file

@ -0,0 +1,119 @@
class_name TableEntry
extends RefCounted
## One possible result on a table. An entry may pipe into other tables, and on a
## ranged (dice) table it covers a span of die values such as 01–30.
const MAX_PIPE_COUNT := 99
var id: String = ""
var text: String = ""
## Optional longer description (may contain BBCode).
var details: String = ""
## Relative chance on a plain table; also the number of copies in card mode.
## 0 means it never comes up. Ignored on ranged tables.
var weight: int = 1
## IDs of the tables this entry rolls on next (unique; one pipe per target).
var pipes: Array[String] = []
## target table id -> how many times to roll it (missing = 1).
var pipe_count: Dictionary = {}
## target table id -> variable name to save the result under (missing = none).
var pipe_save: Dictionary = {}
var has_range: bool = false
var range_lo: int = 1
var range_hi: int = 1
func _init(p_id: String = "", p_text: String = "") -> void:
id = p_id
text = p_text
## How many die faces this entry covers. Plain entries cover exactly one.
func span() -> int:
return range_hi - range_lo + 1 if has_range else 1
## How many times the pipe to `target` rolls.
func count_for(target: String) -> int:
return clampi(int(pipe_count.get(target, 1)), 1, MAX_PIPE_COUNT)
## Variable name the pipe to `target` saves into, or "".
func save_for(target: String) -> String:
return str(pipe_save.get(target, ""))
func set_pipe_count(target: String, n: int) -> void:
n = clampi(n, 1, MAX_PIPE_COUNT)
if n == 1:
pipe_count.erase(target)
else:
pipe_count[target] = n
func set_pipe_save(target: String, name: String) -> void:
name = name.strip_edges()
if name == "":
pipe_save.erase(target)
else:
pipe_save[target] = name
## Adds a pipe if it isn't there already.
func add_pipe(target: String, count: int = 1, save_as: String = "") -> void:
if not pipes.has(target):
pipes.append(target)
set_pipe_count(target, count)
set_pipe_save(target, save_as)
## Removes a pipe along with its options.
func remove_pipe(target: String) -> void:
pipes.erase(target)
pipe_count.erase(target)
pipe_save.erase(target)
func to_dict() -> Dictionary:
var d := {"id": id, "text": text}
if details != "":
d["details"] = details
if weight != 1:
d["weight"] = weight
if not pipes.is_empty():
var list: Array = []
for p in pipes:
var n := count_for(p)
var s := save_for(p)
if n == 1 and s == "":
list.append(p)
else:
var po := {"table": p}
if n != 1:
po["count"] = n
if s != "":
po["save_as"] = s
list.append(po)
d["pipes"] = list
if has_range:
d["range"] = [range_lo, range_hi]
return d
static func from_dict(d: Dictionary) -> TableEntry:
var e := TableEntry.new(str(d.get("id", "")), str(d.get("text", "")))
e.details = str(d.get("details", ""))
e.weight = maxi(0, int(d.get("weight", 1)))
for p: Variant in d.get("pipes", []):
if p is Dictionary:
var target := str(p.get("table", ""))
if target != "":
e.add_pipe(target, int(p.get("count", 1)), str(p.get("save_as", "")))
elif str(p) != "":
e.add_pipe(str(p))
var r: Variant = d.get("range")
if r is Array and r.size() == 2:
e.has_range = true
e.range_lo = int(r[0])
e.range_hi = int(r[1])
return e

1
core/table_entry.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://de7ufd65vpyxu

259
core/text_expander.gd Normal file
View file

@ -0,0 +1,259 @@
class_name TextExpander
extends RefCounted
## Expands inline table references and variables in entry text.
##
## Syntax (expanded strictly left to right, so a chain variable must be saved
## before it's used):
## [[Table]] roll on Table and insert the result
## [[Table -> var]] ...and save it as chain variable "var"
## [[Table -> @var]] ...and save it as persistent variable "@var"
## [[3x Gems]] roll 3 times, joined with ", "
## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K)
## {var} {@var} insert a saved value
## {@var|Table} use the saved value, else roll on Table, save, insert
##
## Inserted pieces are wrapped in internal url tags so the UI can show hover
## pop-ups through RichTextLabel's meta_hover_started signal:
## [url=table:<id>]<summary>[/url] one roll on a table
## [url=var:<name>]<value>[/url] a variable ("@town" for persistent ones)
## [url=missing:<name>]⚠ <name>[/url] a table that doesn't exist
## [url=unset:<name>]{<name>?}[/url] a variable that isn't set
## [url=deep:<id>]⚠ chain too deep[/url] the depth limit was reached
##
## BBCode is untouched: known tags (including ones with parameters such as
## [url={"a":1}]) are copied as-is, and ordinary bracket text like [x] stays text.
## A reference's name can't contain "[" or "]", so "[[b]x[/b]]" is not one.
## Use [lb] to write a literal "[[".
## Upper limit for [[Nx Table]] and [[NdM Table]] counts.
const MAX_REPEAT := 100
const DEEP_TEXT := "⚠ chain too deep"
const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}"
const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*)[dD](\\d+)(?:\\s*([+-])\\s*(\\d+))?)\\s+(\\S.*)$"
const _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
static var _res: Dictionary = {}
## Expands `text` and returns:
## text: String the expanded BBCode, with open tags closed at the end
## children: Array the result nodes rolled inline, in order (one per roll,
## so [[3x Gems]] adds three)
static func expand(text: String, ctx: RollContext) -> Dictionary:
var out: String = ""
var children: Array = []
var i: int = 0
var n: int = text.length()
while i < n:
var c: String = text[i]
if c == "[":
if i + 1 < n and text[i + 1] == "[":
var ref: Dictionary = _ref_at(text, i)
if not ref.is_empty():
out += _expand_ref(ref, ctx, children)
i = ref["end"]
continue
out += c
i += 1
continue
var tag: Dictionary = Formatter.tag_at(text, i)
if not tag.is_empty():
out += tag["raw"]
i += (tag["raw"] as String).length()
continue
elif c == "{":
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
if m != null and m.get_start() == i:
out += _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children)
i = m.get_end()
continue
out += c
i += 1
return {"text": Formatter.close_open_tags(out), "children": children}
## Names of the tables referenced in `text`, without rolling, in order of first
## appearance and without duplicates. Covers [[...]] references (minus any count
## prefix and "-> var" part) and the table in {@var|Table}. With a resolver
## (func(name) -> id), a name like "3x Gems" that is itself a table name is kept
## whole, the same way expand() decides.
static func references(text: String, resolve: Callable = Callable()) -> Array[String]:
var out: Array[String] = []
var i: int = 0
var n: int = text.length()
while i < n:
var c: String = text[i]
var name: String = ""
if c == "[" and i + 1 < n and text[i + 1] == "[":
var ref: Dictionary = _ref_at(text, i)
if not ref.is_empty():
var whole: String = ref["name"]
name = whole
var count: Dictionary = _parse_count(whole)
if not count.is_empty():
var whole_ok: bool = resolve.is_valid() and str(resolve.call(whole)) != ""
if not whole_ok:
name = count["name"]
i = ref["end"]
elif c == "[":
var tag: Dictionary = Formatter.tag_at(text, i)
if not tag.is_empty():
i += (tag["raw"] as String).length()
continue
elif c == "{":
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
if m != null and m.get_start() == i:
name = m.get_string(2).strip_edges()
i = m.get_end()
if name != "":
if not out.has(name):
out.append(name)
continue
i += 1
return out
## The marker for a reference to a table that doesn't exist.
static func missing_marker(name: String) -> String:
return "[url=missing:%s]⚠ %s[/url]" % [name, name]
## The marker for a variable that hasn't been saved. `name` includes any "@".
static func unset_marker(name: String) -> String:
return "[url=unset:%s]{%s?}[/url]" % [name, name]
## The marker for a reference past the depth limit. The roller can use it as the
## summary of a node it stopped for depth.
static func deep_marker(table_id: String) -> String:
return "[url=deep:%s]%s[/url]" % [table_id, DEEP_TEXT]
## Rolls an NdM+K expression ("1d4", "d6", "2d6+1", "3d8-2") with `rng`.
## Returns -1 when the expression isn't valid.
static func roll_dice(expr: String, rng: RandomNumberGenerator) -> int:
var m: RegExMatch = _re("^\\s*(\\d*)[dD](\\d+)\\s*(?:([+-])\\s*(\\d+))?\\s*$").search(expr)
if m == null:
return -1
return _roll_parts(m.get_string(1), m.get_string(2), m.get_string(3), m.get_string(4), rng)
static func _roll_parts(num: String, sides: String, op: String, mod: String, rng: RandomNumberGenerator) -> int:
var dice: int = int(num) if num != "" else 1
var faces: int = int(sides)
if faces < 1 or dice > MAX_REPEAT:
return -1
var total: int = 0
for _k in dice:
total += rng.randi_range(1, faces)
if mod != "":
total += int(mod) if op == "+" else -int(mod)
return total
## Parses "[[...]]" at `pos`. Returns {name, save, end} or {} if it isn't a
## valid reference (no closing "]]", empty, or containing "[", "]" or a newline).
static func _ref_at(text: String, pos: int) -> Dictionary:
var close: int = text.find("]]", pos + 2)
if close < 0:
return {}
var body: String = text.substr(pos + 2, close - pos - 2)
if body.strip_edges() == "" or body.contains("[") or body.contains("]") or body.contains("\n"):
return {}
var name: String = body
var save_as: String = ""
var arrow: int = body.rfind("->")
if arrow >= 0:
var target: String = body.substr(arrow + 2).strip_edges()
if _re(_SAVE_PATTERN).search(target) != null:
save_as = target
name = body.substr(0, arrow)
name = name.strip_edges()
if name == "":
return {}
return {"name": name, "save": save_as, "end": close + 2}
## Splits "3x Gems" / "1d4+1 Coins" into {kind: "times"|"dice", ...parts, name}.
static func _parse_count(name: String) -> Dictionary:
var m: RegExMatch = _re(_COUNT_PATTERN).search(name)
if m == null:
return {}
if m.get_string(1) != "":
return {"kind": "times", "times": int(m.get_string(1)), "name": m.get_string(6).strip_edges()}
return {
"kind": "dice", "num": m.get_string(2), "sides": m.get_string(3),
"sign": m.get_string(4), "mod": m.get_string(5), "name": m.get_string(6).strip_edges(),
}
static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> String:
var name: String = ref["name"]
var times: int = 1
var id: String = ctx.resolve(name)
if id == "":
var count: Dictionary = _parse_count(name)
if not count.is_empty():
name = count["name"]
id = ctx.resolve(name)
if count["kind"] == "times":
times = count["times"]
else:
times = _roll_parts(count["num"], count["sides"], count["sign"], count["mod"], ctx.rng)
times = clampi(times, 0, MAX_REPEAT)
if id == "":
return missing_marker(name)
var pieces: PackedStringArray = []
var plain: PackedStringArray = []
for _k in times:
var piece: Dictionary = _roll_one(id, ctx, children)
pieces.append(piece["text"])
plain.append(piece["value"])
var save_as: String = ref["save"]
if save_as != "":
ctx.save(save_as, ", ".join(plain), id)
return ", ".join(pieces)
static func _expand_var(name: String, table: String, ctx: RollContext, children: Array) -> String:
var value: Variant = ctx.lookup(name)
if value != null:
return "[url=var:%s]%s[/url]" % [name, Formatter.close_open_tags(str(value))]
if table == "":
return unset_marker(name)
var id: String = ctx.resolve(table)
if id == "":
return missing_marker(table)
var piece: Dictionary = _roll_one(id, ctx, children)
if not piece["rolled"]:
return piece["text"]
ctx.save(name, piece["value"], id)
return "[url=var:%s]%s[/url]" % [name, piece["value"]]
## One roll on a resolved table. Returns {text (wrapped for display), value
## (export BBCode, for saving), rolled (false for depth/missing markers)}.
static func _roll_one(id: String, ctx: RollContext, children: Array) -> Dictionary:
if ctx.depth > ctx.max_depth:
var deep: String = deep_marker(id)
return {"text": deep, "value": DEEP_TEXT, "rolled": false}
var node: Dictionary = ctx.roll(id)
if node.is_empty():
var missing: String = missing_marker(id)
return {"text": missing, "value": "", "rolled": false}
children.append(node)
var summary: String = Formatter.close_open_tags(str(node.get("summary", "")))
return {
"text": "[url=table:%s]%s[/url]" % [id, summary],
"value": Formatter.to_export_bbcode(summary),
"rolled": true,
}
static func _re(pattern: String) -> RegEx:
if not _res.has(pattern):
var re := RegEx.new()
re.compile(pattern)
_res[pattern] = re
return _res[pattern]

View file

@ -0,0 +1 @@
uid://bdynv8jvjraa1

148
core/tower_board.gd Normal file
View file

@ -0,0 +1,148 @@
class_name TowerBoard
extends RefCounted
## A collection: every table on the board, plus loading and saving as JSON.
## Files carry a format_version; older versions are upgraded by migrate().
const SAVE_PATH := "user://board.json" # The single-board file of format version 1.
const FORMAT_VERSION := 2
static var _counter: int = 0
static var _salt: String = ""
## Stable slug used as the file name and as the key for local state.
var id: String = ""
## Display name; free to change.
var name: String = ""
var tables: Array[RollTable] = []
static func new_id(prefix: String) -> String:
if _salt == "":
_salt = "%x" % (int(Time.get_unix_time_from_system()) % 0xfffff)
_counter += 1
return "%s%s_%d" % [prefix, _salt, _counter]
func get_table(id: String) -> RollTable:
for t in tables:
if t.id == id:
return t
return null
## Removes a table and every pipe that pointed at it.
func remove_table(id: String) -> void:
for i in range(tables.size() - 1, -1, -1):
if tables[i].id == id:
tables.remove_at(i)
for t in tables:
for e in t.entries:
e.pipes.erase(id)
## Upgrades a parsed file to FORMAT_VERSION, one version step at a time.
## To add a version, bump FORMAT_VERSION and add a _migrate_N_to_N1 step here.
static func migrate(d: Dictionary) -> Dictionary:
var v: int = int(d.get("format_version", 1))
while v < FORMAT_VERSION:
match v:
1:
d = _migrate_1_to_2(d)
_:
break
v += 1
d["format_version"] = v
return d
## Version 1 had no id or name; they are filled in by whoever imports the file.
static func _migrate_1_to_2(d: Dictionary) -> Dictionary:
d["format_version"] = 2
if not d.has("id"):
d["id"] = ""
if not d.has("name"):
d["name"] = ""
return d
func to_dict() -> Dictionary:
var list: Array = []
for t in tables:
list.append(t.to_dict())
return {"format_version": FORMAT_VERSION, "id": id, "name": name, "tables": list}
func to_json() -> String:
return JSON.stringify(to_dict(), " ")
## Replaces the board's tables (and id/name, when the text has them) from JSON
## text of any known version. Returns false if the text isn't a board.
func load_json(text: String) -> bool:
var parsed: Variant = JSON.parse_string(text)
if not (parsed is Dictionary) or not (parsed.get("tables") is Array):
return false
return load_dict(parsed as Dictionary)
## Same as load_json for an already parsed Dictionary.
func load_dict(src: Dictionary) -> bool:
if not (src.get("tables") is Array):
return false
var d: Dictionary = migrate(src.duplicate())
var loaded: Array[RollTable] = []
for td in d["tables"]:
if td is Dictionary:
loaded.append(RollTable.from_dict(td))
tables = loaded
if str(d.get("id", "")) != "":
id = str(d["id"])
if str(d.get("name", "")) != "":
name = str(d["name"])
return true
## Writes text to path via a temp file and a rename, so a crash can't leave a
## half-written file. Creates the folder if needed.
static func write_text_atomic(path: String, text: String) -> Error:
var dir := path.get_base_dir()
if not DirAccess.dir_exists_absolute(dir):
var mk := DirAccess.make_dir_recursive_absolute(dir)
if mk != OK:
return mk
var tmp := path + ".tmp"
var f := FileAccess.open(tmp, FileAccess.WRITE)
if f == null:
return FileAccess.get_open_error()
f.store_string(text)
var werr := f.get_error()
f.close()
if werr != OK:
DirAccess.remove_absolute(tmp)
return werr
var err := DirAccess.rename_absolute(tmp, path)
if err != OK and FileAccess.file_exists(path):
# Some platforms won't rename over an existing file.
DirAccess.remove_absolute(path)
err = DirAccess.rename_absolute(tmp, path)
if err != OK:
DirAccess.remove_absolute(tmp)
return err
func save(path: String = SAVE_PATH) -> bool:
var err := write_text_atomic(path, to_json())
if err != OK:
push_warning("Couldn't save the board to %s: %s" % [path, error_string(err)])
return false
return true
## Loads a board file, or returns null if there isn't a usable one.
static func load_saved(path: String = SAVE_PATH) -> TowerBoard:
if not FileAccess.file_exists(path):
return null
var b := TowerBoard.new()
if not b.load_json(FileAccess.get_file_as_string(path)) or b.tables.is_empty():
return null
return b

1
core/tower_board.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c76ox3vxujfce

25
export_presets.cfg Normal file
View file

@ -0,0 +1,25 @@
[preset.0]
name="Linux"
platform="Linux"
runnable=true
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter=""
exclude_filter="tests/*"
export_path="build/linux/TableTower.x86_64"
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false
script_export_mode=2
[preset.0.options]
custom_template/debug=""
custom_template/release=""
debug/export_console_wrapper=1
binary_format/embed_pck=true
binary_format/architecture="x86_64"
ssh_remote_deploy/enabled=false

392
io/canvas_io.gd Normal file
View file

@ -0,0 +1,392 @@
class_name CanvasIO
extends RefCounted
## JSON Canvas 1.0 (jsoncanvas.org) export and import.
##
## Each table is a group node, each entry a text node inside it, each pipe an
## edge from the entry to the target group. Inline [[references]] become edges
## too, coloured and labelled "ref". TableTower's own data rides along in a
## "tabletower" object on nodes, so a round trip is exact; without it, import
## rebuilds what it can from the visible text and labels.
const GROUP_W := 340
const ENTRY_W := 300
const PAD := 20
const GAP := 10
const REF_COLOR := "6"
const _CHARS_PER_LINE := 34
const _RANGE_RE := "^\\s*(\\d+)\\s*[–—-]\\s*(\\d+)\\s*:\\s*(.*)$"
const _WEIGHT_RE := "^\\s*(\\d+(?:\\.\\d+)?)\\s*[×xX]\\s+(.*)$"
const _LABEL_RE := "^\\s*(?:[×xX]\\s*(\\d+))?\\s*(?:(?:→|->)\\s*(.*?))?\\s*$"
# ---------------------------------------------------------------- export
## JSON Canvas text for a collection Dictionary.
static func export_canvas(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var nodes: Array = []
var edges: Array = []
var group_ids := {} # table id -> node id
var entry_ids := {} # "tableid\tentryid" -> node id
var tables: Array = c["tables"]
for ti in tables.size():
var t: Dictionary = tables[ti]
var gid := "t%d" % ti
group_ids[t["id"]] = gid
var dmax := JsonIO.dice_max(str(t.get("dice", "")))
var y := int(t["y"]) + PAD
var x := int(t["x"]) + PAD
var entries: Array = t["entries"]
for ei in entries.size():
var e: Dictionary = entries[ei]
var text := _visible_text(e, dmax)
var h := _node_height(text)
var nid := "t%de%d" % [ti, ei]
entry_ids["%s\t%s" % [t["id"], e["id"]]] = nid
nodes.append({
"id": nid, "type": "text", "text": text,
"x": x, "y": y, "width": ENTRY_W, "height": h,
"tabletower": _entry_extra(e),
})
y += h + GAP
var group_h := maxi(y - int(t["y"]) + (PAD - GAP if not entries.is_empty() else 40), 80)
var extra := {"id": t["id"]}
for key in ["details", "tags", "dice", "card_mode", "deck_empty", "collapsed"]:
if t.has(key):
extra[key] = t[key]
nodes.push_front({
"id": gid, "type": "group", "label": t["name"],
"x": t["x"], "y": t["y"], "width": GROUP_W, "height": group_h,
"tabletower": extra,
})
# Groups first in the file so they draw underneath their entries.
var ordered: Array = []
for n in nodes:
if n["type"] == "group":
ordered.append(n)
ordered.reverse()
for n in nodes:
if n["type"] != "group":
ordered.append(n)
var edge_n := 0
for link in JsonIO.links(c):
var target := str(link["target"])
if target == "" or not group_ids.has(target):
continue
var from_id: String = entry_ids["%s\t%s" % [link["from_table"], link["from_entry"]]]
var edge := {
"id": "edge%d" % edge_n, "fromNode": from_id, "fromSide": "right",
"toNode": group_ids[target], "toSide": "left",
"tabletower": {"kind": link["kind"]},
}
if link["label"] != "":
edge["label"] = link["label"]
if link["kind"] == "ref":
edge["color"] = REF_COLOR
edges.append(edge)
edge_n += 1
var doc := {
"nodes": ordered, "edges": edges,
"tabletower": {"format_version": JsonIO.FORMAT_VERSION, "id": c["id"], "name": c["name"]},
}
return JSON.stringify(doc, "\t", false)
static func _entry_extra(e: Dictionary) -> Dictionary:
var extra := {"id": e["id"], "text": e["text"]}
for key in ["details", "weight", "range", "pipes"]:
if e.has(key):
extra[key] = e[key]
return extra
static func _visible_text(e: Dictionary, dmax: int) -> String:
var plain := JsonIO.strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [JsonIO.range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain
static func _node_height(text: String) -> int:
var lines := 0
for part in text.split("\n"):
lines += maxi(1, ceili(float(part.length()) / _CHARS_PER_LINE))
return 40 + 22 * (lines - 1)
# ---------------------------------------------------------------- import
## Returns {"ok": bool, "collection": Dictionary, "guesses": Array[String],
## "errors": Array[String], "warnings": Array[String]}. Collection ids and
## names fall back to defaults when the canvas has no TableTower data.
static func import_canvas(text: String, sanitize: Callable = Callable()) -> Dictionary:
var guesses: Array[String] = []
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "guesses": guesses, "errors": errors, "warnings": warnings}
var json := JSON.new()
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return result
if not (json.data is Dictionary):
errors.append("Not a JSON Canvas (expected an object with nodes and edges).")
return result
var doc: Dictionary = json.data
var raw_nodes: Variant = doc.get("nodes", [])
var raw_edges: Variant = doc.get("edges", [])
if not (raw_nodes is Array) or not (raw_edges is Array):
errors.append("Not a JSON Canvas (\"nodes\" and \"edges\" must be lists).")
return result
var groups: Array[Dictionary] = []
var texts: Array[Dictionary] = []
var skipped := 0
for n in raw_nodes:
if not (n is Dictionary) or not n.has("id"):
continue
var type := str(n.get("type", ""))
if type == "group":
groups.append(n)
elif type == "text":
texts.append(n)
else:
skipped += 1
if skipped > 0:
guesses.append("Ignored %d file/link node(s); only groups and text nodes become tables and entries." % skipped)
if groups.is_empty():
errors.append("The canvas has no group nodes, so there are no tables to import.")
return result
var doc_extra: Dictionary = doc.get("tabletower", {}) if doc.get("tabletower") is Dictionary else {}
var used := {}
var group_table := {} # group node id -> table dict
var tables: Array = []
var used_fallback_ids := false
for g in groups:
var extra: Dictionary = g.get("tabletower", {}) if g.get("tabletower") is Dictionary else {}
var t := {"x": int(JsonIO._num(g.get("x", 0), 0)), "y": int(JsonIO._num(g.get("y", 0), 0)), "entries": []}
var label := str(g.get("label", "")).strip_edges()
if label == "":
label = "Table %d" % (tables.size() + 1)
guesses.append("A group had no label; named it \"%s\"." % label)
t["name"] = label
var gid := str(extra.get("id", ""))
if gid == "" or used.has(gid):
gid = JsonIO.unique_id(JsonIO.slug(label, "table"), used)
used_fallback_ids = true
else:
used[gid] = true
t["id"] = gid
for key in ["details", "tags", "dice", "card_mode", "deck_empty", "collapsed"]:
if extra.has(key):
t[key] = extra[key]
t["_rich"] = not extra.is_empty()
group_table[str(g["id"])] = t
tables.append(t)
if used_fallback_ids:
guesses.append("Table ids were made up from the group labels.")
# Assign text nodes to the group containing their centre; reading order is top to bottom.
var sorted_texts := texts.duplicate()
var order := {}
for i in sorted_texts.size():
order[str(sorted_texts[i]["id"])] = i
sorted_texts.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
var ya := float(a.get("y", 0))
var yb := float(b.get("y", 0))
if ya != yb:
return ya < yb
var xa := float(a.get("x", 0))
var xb := float(b.get("x", 0))
if xa != xb:
return xa < xb
return order[str(a["id"])] < order[str(b["id"])])
var node_entry := {} # text node id -> {table, entry}
var loose := 0
for tn in sorted_texts:
var owner := _containing_group(tn, groups)
if owner.is_empty():
loose += 1
continue
var table: Dictionary = group_table[str(owner["id"])]
var entry := _entry_from_node(tn, table)
(table["entries"] as Array).append(entry)
node_entry[str(tn["id"])] = {"table": table, "entry": entry}
if loose > 0:
guesses.append("Ignored %d text node(s) that are not inside any group." % loose)
# Fallback structure for groups without TableTower data.
for t2 in tables:
if t2["_rich"]:
continue
_infer_dice(t2, guesses)
for t3 in tables:
t3.erase("_rich")
# Pipes from edges, only for entries that did not carry their own pipes.
var edge_pipes := 0
for ed in raw_edges:
if not (ed is Dictionary):
continue
var from_id := str(ed.get("fromNode", ""))
var to_id := str(ed.get("toNode", ""))
var edge_extra: Dictionary = ed.get("tabletower", {}) if ed.get("tabletower") is Dictionary else {}
var label2 := str(ed.get("label", "")).strip_edges()
if edge_extra.get("kind", "") == "ref" or _is_ref_label(label2):
continue # references come back from the entry text
if not node_entry.has(from_id):
continue
var holder: Dictionary = node_entry[from_id]
var entry2: Dictionary = holder["entry"]
if entry2.get("_has_pipes", false):
continue
var target := _edge_target_table(to_id, group_table, node_entry)
if target.is_empty():
continue
if not group_table.has(to_id):
guesses.append("An edge pointed at an entry; used its table \"%s\" instead." % str(target["name"]))
var pipe: Variant = _pipe_from_label(str(target["id"]), label2)
if not entry2.has("pipes"):
entry2["pipes"] = []
(entry2["pipes"] as Array).append(pipe)
edge_pipes += 1
for t4 in tables:
for e in t4["entries"]:
e.erase("_has_pipes")
if edge_pipes > 0:
guesses.append("Built %d pipe(s) from edges and their labels." % edge_pipes)
var raw := {
"format_version": JsonIO.FORMAT_VERSION,
"id": str(doc_extra.get("id", "")),
"name": str(doc_extra.get("name", "")),
"tables": tables,
}
if doc_extra.is_empty():
guesses.append("No collection name in the canvas; using a default.")
var imported := JsonIO.import_dict(raw, sanitize)
for w in imported["warnings"]:
warnings.append(w)
for er in imported["errors"]:
errors.append(er)
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result
static func _containing_group(node: Dictionary, groups: Array[Dictionary]) -> Dictionary:
var cx := float(node.get("x", 0)) + float(node.get("width", 0)) / 2.0
var cy := float(node.get("y", 0)) + float(node.get("height", 0)) / 2.0
var best: Dictionary = {}
var best_area := INF
for g in groups:
var gx := float(g.get("x", 0))
var gy := float(g.get("y", 0))
var gw := float(g.get("width", 0))
var gh := float(g.get("height", 0))
if cx >= gx and cx <= gx + gw and cy >= gy and cy <= gy + gh and gw * gh < best_area:
best = g
best_area = gw * gh
return best
## Builds an entry; uses the node's tabletower data when present, else parses its text.
static func _entry_from_node(tn: Dictionary, table: Dictionary) -> Dictionary:
var extra: Dictionary = tn.get("tabletower", {}) if tn.get("tabletower") is Dictionary else {}
if extra.has("text"):
var e := {"id": str(extra.get("id", "")), "text": str(extra["text"])}
for key in ["details", "weight", "range", "pipes"]:
if extra.has(key):
e[key] = extra[key]
e["_has_pipes"] = extra.has("pipes")
return e
var raw := str(tn.get("text", "")).strip_edges()
var e2 := {"id": "", "text": raw}
var m := RegEx.create_from_string(_RANGE_RE).search(raw)
if m != null:
e2["text"] = m.get_string(3).strip_edges()
e2["range"] = [m.get_string(1), m.get_string(2)] # raw digits, fixed up in _infer_dice
else:
var wm := RegEx.create_from_string(_WEIGHT_RE).search(raw)
if wm != null:
e2["text"] = wm.get_string(2).strip_edges()
e2["weight"] = JsonIO._num(wm.get_string(1).to_float(), 1)
e2["_has_pipes"] = false
return e2
## For tables rebuilt from text: fixes up range numbers ("00" wraps to the top
## of the die) and infers the dice from the highest range.
static func _infer_dice(t: Dictionary, guesses: Array[String]) -> void:
var ranged: Array = []
for e in t["entries"]:
if e.has("range") and e["range"][0] is String:
ranged.append(e)
if ranged.is_empty():
return
var top := 0
for e in ranged:
for v in e["range"]:
top = maxi(top, int(v))
var wrap := 10
while wrap < top:
wrap *= 10
var any_wrapped := false
for e in ranged:
var r: Array = e["range"]
var nums: Array = []
for v in r:
var s: String = v
var n := s.to_int()
if n == 0:
n = wrap
any_wrapped = true
nums.append(n)
e["range"] = nums
top = maxi(top, int(nums[1]))
if not t.has("dice"):
t["dice"] = "1d%d" % top
guesses.append("Table \"%s\": ranges found, so it is a ranged table; guessed dice 1d%d." % [str(t["name"]), top])
if any_wrapped:
guesses.append("Table \"%s\": read \"00\" as %d." % [str(t["name"]), wrap])
if ranged.size() < (t["entries"] as Array).size():
guesses.append("Table \"%s\": only some entries have ranges; the rest are kept without one." % str(t["name"]))
static func _is_ref_label(label: String) -> bool:
var l := label.to_lower()
return l == "ref" or l.begins_with("ref ") or l.begins_with("ref→")
static func _edge_target_table(to_id: String, group_table: Dictionary, node_entry: Dictionary) -> Dictionary:
if group_table.has(to_id):
return group_table[to_id]
if node_entry.has(to_id):
return node_entry[to_id]["table"]
return {}
## "×2 → weapon" -> {"table", "count": 2, "save_as": "weapon"}; "" -> plain table id.
static func _pipe_from_label(table_id: String, label: String) -> Variant:
if label == "":
return table_id
var m := RegEx.create_from_string(_LABEL_RE).search(label)
if m == null:
return table_id
var count := m.get_string(1).to_int() if m.get_string(1) != "" else 1
var save_as := m.get_string(2).strip_edges()
if count == 1 and save_as == "":
return table_id
var p := {"table": table_id}
if m.get_string(1) != "":
p["count"] = count
if save_as != "":
p["save_as"] = save_as
return p

1
io/canvas_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ds3weqyiwglho

100
io/dot_exporter.gd Normal file
View file

@ -0,0 +1,100 @@
class_name DotExporter
extends RefCounted
## Graphviz DOT export. Each table is an HTML-like label listing its entries;
## pipes and inline [[references]] are edges from the entry's port to the
## target table (references are dashed). Import is not supported.
## Entries beyond this many are folded into one "... and N more" row, unless
## they have a connection.
const MAX_ROWS := 30
## DOT source for a collection Dictionary.
static func export_dot(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var out: Array[String] = []
out.append("digraph TableTower {")
out.append("\tlabel=\"%s\";" % escape_string(str(c["name"])))
out.append("\tlabelloc=t;")
out.append("\trankdir=LR;")
out.append("\tnode [shape=plain, fontname=\"Helvetica\"];")
out.append("\tedge [fontname=\"Helvetica\", fontsize=10];")
var tables: Array = c["tables"]
var node_of := {}
for i in tables.size():
node_of[tables[i]["id"]] = "t%d" % i
var links := JsonIO.links(c)
var linked := {} # "ti:ei" -> true
for link in links:
linked["%d:%d" % [link["table_index"], link["entry_index"]]] = true
for i in tables.size():
var t: Dictionary = tables[i]
var title := JsonIO.strip_bbcode(str(t["name"]))
if t.has("dice"):
title += " (%s)" % t["dice"]
var dmax := JsonIO.dice_max(str(t.get("dice", "")))
var rows: Array[String] = []
rows.append("<TR><TD PORT=\"head\" BGCOLOR=\"#dddddd\"><B>%s</B></TD></TR>" % escape_html(title))
var entries: Array = t["entries"]
var shown := 0
var hidden := 0
for ei in entries.size():
var e: Dictionary = entries[ei]
if shown >= MAX_ROWS and not linked.has("%d:%d" % [i, ei]):
hidden += 1
continue
shown += 1
rows.append("<TR><TD PORT=\"e%d\" ALIGN=\"LEFT\">%s</TD></TR>" % [ei, escape_html(_row_text(e, dmax))])
if hidden > 0:
rows.append("<TR><TD ALIGN=\"LEFT\"><I>… and %d more</I></TD></TR>" % hidden)
out.append("\t%s [label=<<TABLE BORDER=\"1\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"4\">%s</TABLE>>];" % [node_of[t["id"]], "".join(rows)])
var missing := {}
var edges: Array[String] = []
for link in links:
var target: String
if link["target"] != "":
target = "%s:head:w" % node_of[link["target"]]
else:
var key: String = str(link["target_name"]).to_lower()
if not missing.has(key):
missing[key] = {"id": "m%d" % missing.size(), "name": link["target_name"]}
target = "%s:w" % missing[key]["id"]
var from := "%s:e%d:e" % [node_of[link["from_table"]], link["entry_index"]]
var attrs: Array[String] = []
if link["label"] != "":
attrs.append("label=\"%s\"" % escape_string(str(link["label"])))
if link["kind"] == "ref":
attrs.append("style=dashed")
if link["target"] == "":
attrs.append("color=red")
edges.append("\t%s -> %s%s;" % [from, target, (" [" + ", ".join(attrs) + "]") if not attrs.is_empty() else ""])
for key in missing:
out.append("\t%s [label=\"%s\", shape=box, style=dashed, color=red, fontcolor=red];" % [missing[key]["id"], escape_string("missing: " + str(missing[key]["name"]))])
out.append_array(edges)
out.append("}")
return "\n".join(out) + "\n"
## Escapes text for a double-quoted DOT string.
static func escape_string(text: String) -> String:
return text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "").replace("\n", "\\n")
## Escapes text for an HTML-like DOT label.
static func escape_html(text: String) -> String:
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("\n", " ")
static func _row_text(e: Dictionary, dmax: int) -> String:
var plain := JsonIO.strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [JsonIO.range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain

1
io/dot_exporter.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bnjvob7342dt6

245
io/graphml_io.gd Normal file
View file

@ -0,0 +1,245 @@
class_name GraphMLIO
extends RefCounted
## GraphML export and import. Tables are nodes, pipes and inline [[references]]
## are edges. TableTower fields are declared with <key> definitions, and each
## table node carries its entries as a JSON string, so a round trip is exact.
## Foreign GraphML (no entries data) imports as one table per node, with one
## entry per outgoing edge.
const _NS := "http://graphml.graphdrawing.org/xmlns"
# [attr.name, attr.type, applies to]
const _KEYS := [
["format_version", "int", "graph"],
["collection_id", "string", "graph"],
["collection_name", "string", "graph"],
["table_id", "string", "node"],
["name", "string", "node"],
["x", "int", "node"],
["y", "int", "node"],
["collapsed", "boolean", "node"],
["details", "string", "node"],
["tags", "string", "node"],
["dice", "string", "node"],
["card_mode", "string", "node"],
["deck_empty", "string", "node"],
["entries", "string", "node"],
["kind", "string", "edge"],
["label", "string", "edge"],
["entry", "string", "edge"],
["count", "int", "edge"],
["save_as", "string", "edge"],
]
# ---------------------------------------------------------------- export
## GraphML text for a collection Dictionary.
static func export_graphml(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var out: Array[String] = []
out.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
out.append("<graphml xmlns=\"%s\">" % _NS)
for k in _KEYS:
out.append("\t<key id=\"%s_%s\" for=\"%s\" attr.name=\"%s\" attr.type=\"%s\"/>" % [k[2], k[0], k[2], k[0], k[1]])
out.append("\t<graph id=\"G\" edgedefault=\"directed\">")
out.append(_data("graph", "format_version", str(c["format_version"]), 2))
out.append(_data("graph", "collection_id", str(c["id"]), 2))
out.append(_data("graph", "collection_name", str(c["name"]), 2))
var tables: Array = c["tables"]
var node_of := {}
for i in tables.size():
var t: Dictionary = tables[i]
node_of[t["id"]] = "n%d" % i
out.append("\t\t<node id=\"n%d\">" % i)
out.append(_data("node", "table_id", str(t["id"]), 3))
out.append(_data("node", "name", str(t["name"]), 3))
out.append(_data("node", "x", str(t["x"]), 3))
out.append(_data("node", "y", str(t["y"]), 3))
if t.has("collapsed"):
out.append(_data("node", "collapsed", "true", 3))
for key in ["details", "dice"]:
if t.has(key):
out.append(_data("node", key, str(t[key]), 3))
for key in ["tags", "card_mode", "deck_empty"]:
if t.has(key):
out.append(_data("node", key, JSON.stringify(t[key]), 3))
out.append(_data("node", "entries", JSON.stringify(t["entries"]), 3))
out.append("\t\t</node>")
var missing := {}
var edge_lines: Array[String] = []
var ei := 0
for link in JsonIO.links(c):
var target: String
if link["target"] != "":
target = node_of[link["target"]]
else:
var key2: String = str(link["target_name"]).to_lower()
if not missing.has(key2):
missing[key2] = {"id": "x%d" % missing.size(), "name": link["target_name"]}
target = missing[key2]["id"]
edge_lines.append("\t\t<edge id=\"e%d\" source=\"%s\" target=\"%s\">" % [ei, node_of[link["from_table"]], target])
edge_lines.append(_data("edge", "kind", str(link["kind"]), 3))
if link["label"] != "":
edge_lines.append(_data("edge", "label", str(link["label"]), 3))
edge_lines.append(_data("edge", "entry", str(link["from_entry"]), 3))
if link["kind"] == "pipe":
edge_lines.append(_data("edge", "count", str(link["count"]), 3))
if link["save_as"] != "":
edge_lines.append(_data("edge", "save_as", str(link["save_as"]), 3))
edge_lines.append("\t\t</edge>")
ei += 1
# Missing targets are kept visible as placeholder nodes without a table_id.
for key3 in missing:
out.append("\t\t<node id=\"%s\">" % missing[key3]["id"])
out.append(_data("node", "name", "missing: " + str(missing[key3]["name"]), 3))
out.append("\t\t</node>")
out.append_array(edge_lines)
out.append("\t</graph>")
out.append("</graphml>")
return "\n".join(out) + "\n"
static func _data(scope: String, attr: String, value: String, indent: int) -> String:
return "%s<data key=\"%s_%s\">%s</data>" % ["\t".repeat(indent), scope, attr, value.xml_escape(true)]
# ---------------------------------------------------------------- import
## Returns {"ok": bool, "collection": Dictionary, "guesses": Array[String],
## "errors": Array[String], "warnings": Array[String]}.
static func import_graphml(text: String, sanitize: Callable = Callable()) -> Dictionary:
var guesses: Array[String] = []
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "guesses": guesses, "errors": errors, "warnings": warnings}
var key_name := {} # key id -> attr.name
var graph_data := {}
var nodes: Array[Dictionary] = [] # {"xml_id", "data"}
var edges: Array[Dictionary] = [] # {"source", "target", "data"}
var current: Dictionary = {}
var cur_key := ""
var cur_text := ""
var in_data := false
var depth_graph := 0
var saw_graphml := false
var p := XMLParser.new()
if p.open_buffer(text.to_utf8_buffer()) != OK:
errors.append("Couldn't read the XML.")
return result
while true:
var err := p.read()
if err == ERR_FILE_EOF:
break
if err != OK:
errors.append("The XML is malformed.")
return result
var t := p.get_node_type()
if t == XMLParser.NODE_ELEMENT:
var tag := p.get_node_name()
match tag:
"graphml":
saw_graphml = true
"key":
key_name[p.get_named_attribute_value_safe("id")] = p.get_named_attribute_value_safe("attr.name")
"graph":
depth_graph += 1
current = graph_data if depth_graph == 1 else current
"node":
current = {}
nodes.append({"xml_id": p.get_named_attribute_value_safe("id"), "data": current})
"edge":
current = {}
edges.append({"source": p.get_named_attribute_value_safe("source"), "target": p.get_named_attribute_value_safe("target"), "data": current})
"data":
cur_key = p.get_named_attribute_value_safe("key")
cur_text = ""
in_data = not p.is_empty()
if not in_data:
current[key_name.get(cur_key, cur_key)] = ""
elif t == XMLParser.NODE_TEXT or t == XMLParser.NODE_CDATA:
if in_data:
cur_text += p.get_node_data()
elif t == XMLParser.NODE_ELEMENT_END:
var etag := p.get_node_name()
if etag == "data" and in_data:
current[key_name.get(cur_key, cur_key)] = cur_text
in_data = false
elif etag == "node" or etag == "edge":
current = graph_data
if not saw_graphml:
errors.append("Not a GraphML file (no <graphml> element).")
return result
if nodes.is_empty():
errors.append("The GraphML file has no nodes.")
return result
var tables: Array = []
var used := {}
var xml_to_table := {} # xml node id -> table id
var rich := false
for n in nodes:
var d: Dictionary = n["data"]
if not d.has("table_id") and d.has("name") and str(d["name"]).begins_with("missing: ") and not d.has("entries"):
continue # placeholder for a pipe to a missing table
var tname := str(d.get("name", d.get("label", d.get("table_name", ""))))
if tname == "":
tname = str(n["xml_id"])
guesses.append("Node \"%s\" had no name; used its id." % tname)
var t2 := {"name": tname, "x": d.get("x", 0), "y": d.get("y", 0), "entries": []}
var tid := str(d.get("table_id", ""))
if tid == "" or used.has(tid):
tid = JsonIO.unique_id(JsonIO.slug(tname, "table"), used)
else:
used[tid] = true
t2["id"] = tid
xml_to_table[n["xml_id"]] = tid
if str(d.get("collapsed", "")) == "true":
t2["collapsed"] = true
for key in ["details", "dice"]:
if d.has(key) and str(d[key]) != "":
t2[key] = d[key]
for key in ["tags", "card_mode", "deck_empty"]:
if d.has(key):
var parsed: Variant = JSON.parse_string(str(d[key]))
t2[key] = parsed if parsed != null else d[key]
if d.has("entries"):
var ents: Variant = JSON.parse_string(str(d["entries"]))
if ents is Array:
t2["entries"] = ents
rich = true
else:
warnings.append("Table \"%s\": couldn't read its entries." % tname)
tables.append(t2)
if not rich:
guesses.append("No TableTower data in this file; each node became a table and each edge an entry with a pipe.")
var by_table := {}
for t3 in tables:
by_table[t3["id"]] = t3
for ed in edges:
if not xml_to_table.has(ed["source"]) or not xml_to_table.has(ed["target"]):
continue
var src: Dictionary = by_table[xml_to_table[ed["source"]]]
var ed_data: Dictionary = ed["data"]
var etext := str(ed_data.get("label", ed_data.get("name", "")))
if etext == "":
etext = "Go to " + str(by_table[xml_to_table[ed["target"]]]["name"])
(src["entries"] as Array).append({"text": etext, "pipes": [xml_to_table[ed["target"]]]})
var raw := {
"format_version": JsonIO.FORMAT_VERSION,
"id": str(graph_data.get("collection_id", "")),
"name": str(graph_data.get("collection_name", "")),
"tables": tables,
}
var imported := JsonIO.import_dict(raw, sanitize)
for w in imported["warnings"]:
warnings.append(w)
for er in imported["errors"]:
errors.append(er)
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result

1
io/graphml_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cwe1qbrqrqr1u

405
io/json_io.gd Normal file
View file

@ -0,0 +1,405 @@
class_name JsonIO
extends RefCounted
## JSON import and export of a collection, plus the shared helpers every other
## exporter uses. Everything works on plain collection Dictionaries (the JSON
## form), never on the model classes.
##
## Canonical collection form:
## {"format_version": 2, "id", "name", "tables": [table, ...]}
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], entries
## entry: id, text, [details], [weight], [range], [pipes]
## pipe: a table id String, or {"table": id, "count": n, "save_as": name}
const FORMAT_VERSION := 2
const _DICE_RE := "^\\s*(\\d+)\\s*[dD]\\s*(\\d+)\\s*$"
const _BBCODE_RE := "(?<!\\[)\\[/?[A-Za-z_]+(?:[= ][^\\]\\[]*)?\\](?!\\])"
const _REF_RE := "\\[\\[(.+?)\\]\\]"
# ---------------------------------------------------------------- export
## Pretty JSON text for a collection. Only known keys are written, so local
## state (card draws, variables, history) can never leak into an export.
static func export_json(collection: Dictionary) -> String:
return JSON.stringify(canonical(collection), " ", false)
## Returns {"ok": bool, "collection": Dictionary, "errors": Array[String],
## "warnings": Array[String]}. `sanitize` is called with every user-visible
## string (names, details, tags, entry text, variable names) and must return
## the cleaned string. The default leaves strings unchanged.
static func import_json(text: String, sanitize: Callable = Callable()) -> Dictionary:
var json := JSON.new()
var errors: Array[String] = []
var warnings: Array[String] = []
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
if not (json.data is Dictionary):
errors.append("The file is not a collection (expected a JSON object).")
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
return import_dict(json.data, sanitize)
## Validates and cleans an already-parsed collection (used by every importer).
## Gives tables and entries fresh ids where they are missing or collide, and
## keeps pipes pointing at the right tables. Same result shape as import_json.
static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Dictionary:
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
var fv: Variant = _num(data.get("format_version", 1), 1)
if (fv is int or fv is float) and fv > FORMAT_VERSION:
errors.append("format_version %s is newer than this version supports (%d)." % [str(fv), FORMAT_VERSION])
if not (data.get("tables") is Array):
errors.append("The collection has no \"tables\" list.")
return result
var raw_tables: Array = data["tables"]
for ti in raw_tables.size():
var rt: Variant = raw_tables[ti]
if not (rt is Dictionary):
errors.append("Table #%d is not an object." % (ti + 1))
continue
var re_list: Variant = rt.get("entries", [])
if not (re_list is Array):
errors.append("Table #%d: \"entries\" is not a list." % (ti + 1))
continue
for ei in (re_list as Array).size():
var re: Variant = re_list[ei]
if not (re is Dictionary or re is String):
errors.append("Table #%d, entry #%d is not an object or text." % [ti + 1, ei + 1])
if not errors.is_empty():
return result
var c := canonical(data)
var clean := func(s: String) -> String:
if sanitize.is_null():
return s
return str(sanitize.call(s))
c["name"] = clean.call(str(c["name"]))
if str(c["name"]) == "":
c["name"] = "Untitled collection"
warnings.append("The collection had no name; called it \"Untitled collection\".")
if str(c["id"]) == "":
c["id"] = slug(str(c["name"]), "collection")
var tables: Array = c["tables"]
# Reserve the first occurrence of every given table id, then hand out new ones.
var used := {}
var id_map := {} # original id -> final id
var needs_id: Array[int] = []
for i in tables.size():
var t: Dictionary = tables[i]
var tid: String = t["id"]
if tid != "" and not used.has(tid):
used[tid] = true
id_map[tid] = tid
else:
needs_id.append(i)
for i in needs_id:
var t2: Dictionary = tables[i]
var old: String = t2["id"]
var fresh := unique_id(slug(str(t2["name"]), "table"), used)
if old != "":
warnings.append("Table id \"%s\" was used twice; \"%s\" is now \"%s\"." % [old, str(t2["name"]), fresh])
t2["id"] = fresh
var by_name := {}
for t3 in tables:
var key := str(t3["name"]).to_lower()
if not by_name.has(key):
by_name[key] = t3["id"]
for t4 in tables:
var t5: Dictionary = t4
t5["name"] = clean.call(str(t5["name"]))
if t5.has("details"):
t5["details"] = clean.call(str(t5["details"]))
if t5.has("tags"):
var tags: Array = []
for tag in t5["tags"]:
tags.append(clean.call(str(tag)))
t5["tags"] = tags
var elist: Array = t5["entries"]
# Entry ids only need to be unique within their table.
var seen := {}
var redo: Array[Dictionary] = []
for e in elist:
var eid: String = e["id"]
if eid == "" or seen.has(eid):
redo.append(e)
else:
seen[eid] = true
var enext := 1
for e1 in redo:
while seen.has("e%d" % enext):
enext += 1
e1["id"] = "e%d" % enext
seen[e1["id"]] = true
for e2 in elist:
var ed: Dictionary = e2
ed["text"] = clean.call(str(ed["text"]))
if ed.has("details"):
ed["details"] = clean.call(str(ed["details"]))
if ed.has("range"):
var r: Array = ed["range"]
if int(r[0]) > int(r[1]):
warnings.append("\"%s\": range %d-%d is backwards; dropped." % [str(ed["text"]), int(r[0]), int(r[1])])
ed.erase("range")
if ed.has("pipes"):
var pipes: Array = []
for p in ed["pipes"]:
var info := pipe_info(p)
var target: String = info["table"]
if id_map.has(target):
target = id_map[target]
elif by_name.has(target.to_lower()):
target = by_name[target.to_lower()]
else:
warnings.append("\"%s\" pipes to unknown table \"%s\"." % [str(ed["text"]), target])
if p is Dictionary:
var np: Dictionary = (p as Dictionary).duplicate()
np["table"] = target
if np.has("save_as"):
np["save_as"] = clean.call(str(np["save_as"]))
pipes.append(np)
else:
pipes.append(target)
ed["pipes"] = pipes
result["ok"] = true
result["collection"] = c
return result
# ------------------------------------------------------------ canonical
## Normalizes a collection to format version 2: legacy keys are converted
## (`die` -> `dice`, `triggers` -> `pipes`, `collection` -> `name`), missing
## optional keys are tolerated and unknown keys are dropped.
static func canonical(src: Dictionary) -> Dictionary:
var tables: Array = []
var src_tables: Variant = src.get("tables", [])
if src_tables is Array:
for t in src_tables:
if t is Dictionary:
tables.append(_canon_table(t))
var cname := str(src.get("name", src.get("collection", "")))
return {"format_version": FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
static func _canon_table(td: Dictionary) -> Dictionary:
var t := {
"id": str(td.get("id", "")),
"name": str(td.get("name", "")),
"x": int(_num(td.get("x", 0), 0)),
"y": int(_num(td.get("y", 0), 0)),
}
if bool(td.get("collapsed", false)):
t["collapsed"] = true
var details := str(td.get("details", ""))
if details != "":
t["details"] = details
var tags: Array = []
var src_tags: Variant = td.get("tags", [])
if src_tags is Array:
for tag in src_tags:
tags.append(str(tag))
if not tags.is_empty():
t["tags"] = tags
var dice := str(td.get("dice", "")).strip_edges()
if dice == "" and td.has("die"):
var die: Variant = _num(td["die"], 0)
if (die is int or die is float) and die > 0:
dice = "1d%d" % int(die)
if dice != "":
t["dice"] = dice
for key in ["card_mode", "deck_empty"]:
var v: Variant = td.get(key)
if v != null and not (v is bool and not v) and not (v is String and v == ""):
t[key] = v
var entries: Array = []
var src_entries: Variant = td.get("entries", [])
if src_entries is Array:
for e in src_entries:
entries.append(_canon_entry(e))
t["entries"] = entries
return t
static func _canon_entry(ev: Variant) -> Dictionary:
if ev is String:
return {"id": "", "text": ev}
var ed: Dictionary = ev
var e := {"id": str(ed.get("id", "")), "text": str(ed.get("text", ""))}
var details := str(ed.get("details", ""))
if details != "":
e["details"] = details
var w: Variant = _num(ed.get("weight", 1), 1)
if (w is int or w is float) and w != 1:
e["weight"] = w
var r: Variant = ed.get("range")
if r is Array and (r as Array).size() == 2:
e["range"] = [int(_num(r[0], 0)), int(_num(r[1], 0))]
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = []
if src_pipes is Array:
for p in src_pipes:
if p is String and p != "":
pipes.append(p)
elif p is Dictionary and str(p.get("table", "")) != "":
var np := {"table": str(p["table"])}
if p.has("count"):
np["count"] = int(_num(p["count"], 1))
if str(p.get("save_as", "")) != "":
np["save_as"] = str(p["save_as"])
pipes.append(np)
if not pipes.is_empty():
e["pipes"] = pipes
return e
# -------------------------------------------------------------- helpers
## Turns whole floats (as JSON parsing gives) into ints; returns `fallback`
## for anything that isn't a number.
static func _num(v: Variant, fallback: Variant) -> Variant:
if v is int:
return v
if v is float:
return int(v) if is_equal_approx(v, roundf(v)) else v
if v is String and (v as String).is_valid_float():
return _num((v as String).to_float(), fallback)
return fallback
## Lower-case identifier text: "Melee Weapons" -> "melee_weapons".
static func slug(text: String, fallback: String = "item") -> String:
var re := RegEx.create_from_string("[^a-z0-9]+")
var s := re.sub(text.to_lower(), "_", true)
s = s.trim_prefix("_").trim_suffix("_")
return s if s != "" else fallback
## `base`, or `base_2`, `base_3`... whichever isn't in `used`; marks it used.
static func unique_id(base: String, used: Dictionary) -> String:
var id := base
var n := 2
while used.has(id):
id = "%s_%d" % [base, n]
n += 1
used[id] = true
return id
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as"}.
static func pipe_info(p: Variant) -> Dictionary:
if p is Dictionary:
return {"table": str(p.get("table", "")), "count": int(_num(p.get("count", 1), 1)), "save_as": str(p.get("save_as", ""))}
return {"table": str(p), "count": 1, "save_as": ""}
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon".
static func pipe_label(info: Dictionary) -> String:
var parts: Array[String] = []
if int(info["count"]) != 1:
parts.append("×%d" % int(info["count"]))
if str(info["save_as"]) != "":
parts.append("→ " + str(info["save_as"]))
return " ".join(parts)
## Removes BBCode tags such as [b] or [color=red]. `[[Table]]` references stay.
static func strip_bbcode(text: String) -> String:
return RegEx.create_from_string(_BBCODE_RE).sub(text, "", true)
## Inline references in entry text: Array of {"name", "var"}.
static func find_refs(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for m in RegEx.create_from_string(_REF_RE).search_all(text):
var inner := m.get_string(1)
var parts := inner.split("->", true, 1)
var ref_name := parts[0].strip_edges()
if ref_name == "":
continue
out.append({"name": ref_name, "var": parts[1].strip_edges() if parts.size() > 1 else ""})
return out
## Highest value a dice string can roll ("1d100" -> 100, "2d6" -> 12); 0 if unparsable.
static func dice_max(dice: String) -> int:
var m := RegEx.create_from_string(_DICE_RE).search(dice)
if m == null:
return 0
return m.get_string(1).to_int() * m.get_string(2).to_int()
## Id of the table whose name matches (case-insensitive), or "".
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
var want := table_name.strip_edges().to_lower()
for t in collection.get("tables", []):
if str(t.get("name", "")).to_lower() == want:
return str(t.get("id", ""))
return ""
## Every connection in a collection, pipes and inline references, in
## table/entry order. Each item: kind ("pipe" or "ref"), table_index,
## entry_index, from_table, from_entry (ids), target (table id, or "" when the
## table is missing), target_name (as written), label, count, save_as,
## entry_text (BBCode stripped). Expects a canonical collection.
static func links(collection: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var tables: Array = collection.get("tables", [])
var ids := {}
for t in tables:
ids[str(t["id"])] = true
for ti in tables.size():
var t2: Dictionary = tables[ti]
var elist: Array = t2.get("entries", [])
for ei in elist.size():
var e: Dictionary = elist[ei]
for p in e.get("pipes", []):
var info := pipe_info(p)
var tgt: String = info["table"]
out.append({
"kind": "pipe", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": tgt if ids.has(tgt) else "", "target_name": tgt,
"label": pipe_label(info), "count": info["count"], "save_as": info["save_as"],
"entry_text": strip_bbcode(str(e["text"])),
})
for ref in find_refs(str(e["text"])):
var rid := table_id_by_name(collection, ref["name"])
out.append({
"kind": "ref", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": rid, "target_name": ref["name"],
"label": ("ref → " + ref["var"]) if ref["var"] != "" else "ref",
"count": 1, "save_as": ref["var"],
"entry_text": strip_bbcode(str(e["text"])),
})
return out
## Display label for a table number range, zero padded; the top of a d100 or
## d1000 reads as zeros ("96–00").
static func range_text(lo: int, hi: int, dmax: int) -> String:
return "%s–%s" % [_num_text(lo, dmax), _num_text(hi, dmax)]
static func _num_text(n: int, dmax: int) -> String:
if dmax >= 100 and _is_power_of_ten(dmax):
if n == dmax:
return "0".repeat(str(dmax - 1).length())
return str(n).pad_zeros(str(dmax - 1).length())
return str(n).pad_zeros(str(maxi(dmax, 1)).length())
static func _is_power_of_ten(n: int) -> bool:
while n >= 10 and n % 10 == 0:
n /= 10
return n == 1

1
io/json_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cnxt27u466kyx

71
io/mermaid_exporter.gd Normal file
View file

@ -0,0 +1,71 @@
class_name MermaidExporter
extends RefCounted
## Mermaid flowchart export (renders in Forgejo and GitHub Markdown).
## One node per table, solid arrows for pipes, dashed arrows for inline
## [[references]]. Pipes to tables that don't exist point at a red dashed
## "missing" node.
const MAX_EDGE_TEXT := 32
## Mermaid source ("graph LR ...") for a collection Dictionary.
static func export_mermaid(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var lines: Array[String] = ["graph LR"]
var node_of := {} # table id -> mermaid node id
var tables: Array = c["tables"]
for i in tables.size():
var t: Dictionary = tables[i]
node_of[t["id"]] = "t%d" % i
var label := JsonIO.strip_bbcode(str(t["name"]))
if t.has("dice"):
label += " (%s)" % t["dice"]
lines.append("\tt%d[\"%s\"]" % [i, escape_label(label)])
var missing := {} # target name -> mermaid node id
var edges: Array[String] = []
for link in JsonIO.links(c):
var target: String
if link["target"] != "":
target = node_of[link["target"]]
else:
var mkey: String = str(link["target_name"]).to_lower()
if not missing.has(mkey):
missing[mkey] = "m%d" % missing.size()
target = missing[mkey]
var from: String = node_of[link["from_table"]]
var text := _short(str(link["entry_text"]))
var extra := str(link["label"])
if link["kind"] == "pipe":
var label2 := text if extra == "" else "%s · %s" % [text, extra]
edges.append("\t%s -->|\"%s\"| %s" % [from, escape_label(label2), target])
else:
edges.append("\t%s -.->|\"%s\"| %s" % [from, escape_label("%s · %s" % [text, extra]), target])
for key in missing:
var shown := "missing: " + _name_for_missing(c, key)
lines.append("\t%s[\"%s\"]:::missing" % [missing[key], escape_label(shown)])
lines.append_array(edges)
if not missing.is_empty():
lines.append("\tclassDef missing stroke:#d33,stroke-dasharray:4 3,color:#d33")
return "\n".join(lines) + "\n"
## Makes text safe inside a double-quoted Mermaid label using entity codes.
static func escape_label(text: String) -> String:
var s := text.replace("\r", " ").replace("\n", " ")
s = s.replace("#", "#35;")
for pair in [["\"", "#quot;"], ["&", "#38;"], ["<", "#lt;"], [">", "#gt;"], ["[", "#91;"], ["]", "#93;"], ["{", "#123;"], ["}", "#125;"], ["|", "#124;"], ["`", "#96;"], ["\\", "#92;"]]:
s = s.replace(pair[0], pair[1])
return s
static func _short(text: String) -> String:
var t := text.replace("\n", " ").strip_edges()
return t if t.length() <= MAX_EDGE_TEXT else t.substr(0, MAX_EDGE_TEXT - 1) + "…"
## The first spelling of a missing target (keys are lower-cased).
static func _name_for_missing(c: Dictionary, key: String) -> String:
for link in JsonIO.links(c):
if link["target"] == "" and str(link["target_name"]).to_lower() == key:
return str(link["target_name"])
return key

View file

@ -0,0 +1 @@
uid://47n4wgfy3851

View file

@ -11,5 +11,16 @@ config_version=5
[application]
config/name="TableTower"
run/main_scene="res://ui/main.tscn"
config/features=PackedStringArray("4.7", "Forward Plus")
boot_splash/bg_color=Color(0.0706, 0.1882, 0.1216, 1)
config/icon="res://icon.svg"
[display]
window/size/viewport_width=1440
window/size/viewport_height=900
[rendering]
environment/defaults/default_clear_color=Color(0.0706, 0.1882, 0.1216, 1)

230
tests/test_integration.gd Normal file
View file

@ -0,0 +1,230 @@
extends SceneTree
## Headless checks for the roller working with RollContext, TextExpander,
## pipes that save variables, card decks and StateStore.
## Run: godot --headless --path . -s res://tests/test_integration.gd
var _failures := 0
func _init() -> void:
_test_refs_and_vars()
_test_pipe_save()
_test_persistent_across_rolls()
_test_depth_limit()
_test_missing_and_unset()
_test_decks_through_state()
_test_lit_and_steps()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _entry(id: String, text: String, weight: int = 1) -> TableEntry:
var e := TableEntry.new(id, text)
e.weight = weight
return e
func _table(id: String, name: String, texts: Array) -> RollTable:
var t := RollTable.new(id, name)
for i in texts.size():
t.entries.append(_entry("%s%d" % [id, i], texts[i]))
return t
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
b.id = "test-coll"
for t in tables:
b.tables.append(t)
return b
func _rng(seed_value: int) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
## A quest board: Quest uses refs, chain vars and a persistent var.
func _quest_board() -> TowerBoard:
var quest := _table("quest", "Quest Hook", ["[[Names -> hero]] seeks [[Relics]] in {@town|Towns}. {hero} is [b]sure[/b] of it."])
var names := _table("names", "Names", ["Aldric"])
var relics := _table("relics", "[i]Relics[/i]", ["the Crown"])
var towns := _table("towns", "Towns", ["Riverton"])
return _board([quest, names, relics, towns])
func _test_refs_and_vars() -> void:
var b := _quest_board()
var n := Roller.roll(b, "quest", _rng(1))
var summary: String = n["summary"]
_check(summary.contains("[url=table:names]Aldric[/url]"), "inline [[Names -> hero]] expands: %s" % summary)
_check(summary.contains("[url=table:relics]the Crown[/url]"), "reference matches a name with BBCode")
_check(summary.contains("[url=var:@town]Riverton[/url]"), "{@town|Towns} rolls and inserts")
_check(summary.contains("[url=var:hero]Aldric[/url]"), "{hero} reuses the chain variable")
_eq(Formatter.strip_tags(summary), "Aldric seeks the Crown in Riverton. Aldric is sure of it.", "plain text of the result")
var kids: Array = n["children"]
_check(kids.size() == 3, "three inline children (names, relics, towns), got %d" % kids.size())
var all_inline := true
for c: Dictionary in kids:
all_inline = all_inline and c.get("inline", false)
_check(all_inline, "inline children are marked inline")
var steps := Roller.flatten(n, [])
_check(steps.size() == 4 and steps[1].get("inline", false) and not steps[0].has("inline"), "steps mark inline rolls")
_check(int(steps[1]["depth"]) == 1 and int(steps[0]["depth"]) == 0, "steps carry their depth")
_check((steps[0]["text"] as String).contains("[b]sure[/b]"), "steps carry BBCode text")
_check(Roller.ref_targets(b, b.get_table("quest").entries[0].text) == ["names", "relics", "towns"], "ref_targets resolves names: %s" % str(Roller.ref_targets(b, b.get_table("quest").entries[0].text)))
func _test_pipe_save() -> void:
var src := _table("src", "Source", ["Go {foe}, then {@pal?}"])
var dst := _table("dst", "Foes", ["[b]Ogre[/b]"])
var pals := _table("pals", "Pals", ["Mira"])
src.entries[0].add_pipe("dst", 2, "foe")
src.entries[0].add_pipe("pals", 1, "@pal")
var b := _board([src, dst, pals])
var store := {}
var ctx := Roller.new_context(b, _rng(3), store, {})
var n := Roller.roll(b, "src", ctx.rng, 0, {}, ctx)
# Text is expanded before pipes roll, so {foe} isn't set yet in the same entry.
_check((n["summary"] as String).contains("{foe?}"), "pipes roll after the entry's text")
_eq(ctx.lookup("foe"), "[b]Ogre[/b]", "pipe save_as stores the export BBCode in a chain var")
_check(not (ctx.lookup("foe") as String).contains("url="), "saved value has no internal markers")
_check(store.has("pal") and store["pal"]["value"] == "Mira" and store["pal"]["source"] == "pals", "@ save goes to persistent vars with source: %s" % str(store))
_check(ctx.persistent_changed, "persistent_changed after a pipe save")
# A later table in the same chain sees the chain var.
var a := _table("a", "A", ["start"])
var c := _table("c", "C", ["uses {foe}"])
a.entries[0].add_pipe("dst", 1, "foe")
a.entries[0].add_pipe("c")
var b2 := _board([a, c, dst])
var n2 := Roller.roll(b2, "a", _rng(4))
var used: String = (n2["children"] as Array)[1]["summary"]
_eq(used, "uses [url=var:foe][b]Ogre[/b][/url]", "chain var from a pipe is used by a later pipe")
func _test_persistent_across_rolls() -> void:
var b := _quest_board()
var store := {}
var decks := {}
var r := _rng(5)
var ctx := Roller.new_context(b, r, store, decks)
Roller.roll(b, "quest", r, 0, {}, ctx)
_check(store.has("town") and store["town"]["value"] == "Riverton", "first roll saves @town")
# Change the town by hand; the next roll uses it instead of rolling.
store["town"]["value"] = "Hilltop"
var ctx2 := Roller.new_context(b, r, store, decks)
var n := Roller.roll(b, "quest", r, 0, {}, ctx2)
_check((n["summary"] as String).contains("Hilltop"), "persistent var survives into the next roll")
_check(ctx2.chain_vars.has("hero") and not ctx2.chain_vars.has("town"), "chain vars are fresh per roll")
var inline_tables := []
for c: Dictionary in n["children"]:
inline_tables.append((c["table"] as RollTable).id)
_check(not inline_tables.has("towns"), "no reroll of Towns while @town is set")
# Through StateStore dictionaries (names without "@").
var dir := "user://test_integration_state"
var st := StateStore.new(dir)
st.reload()
for k in store:
st.set_variable(b.id, k, store[k]["value"], store[k]["source"])
st.save()
var st2 := StateStore.new(dir)
var back := st2.get_variables(b.id)
_check(back.has("town") and back["town"]["value"] == "Hilltop" and back["town"]["source"] == "towns", "persistent vars round-trip through StateStore")
var ctx3 := Roller.new_context(b, r, back, {})
_eq(ctx3.lookup("@town"), "Hilltop", "RollContext reads StateStore's variables")
DirAccess.remove_absolute(st.state_path())
DirAccess.remove_absolute(dir.path_join("state"))
DirAccess.remove_absolute(dir)
func _test_depth_limit() -> void:
_check(Roller.MAX_DEPTH == 32, "depth limit is 32")
var loop := _table("loop", "Loop", ["again [[Loop]]"])
var b := _board([loop])
var n := Roller.roll(b, "loop", _rng(6))
var steps := Roller.flatten(n, [])
_check(steps.size() == Roller.MAX_DEPTH + 1, "self-reference stops at the depth limit (%d steps)" % steps.size())
var deepest: Dictionary = steps[steps.size() - 1]
_check((deepest["text"] as String).contains(TextExpander.DEEP_TEXT), "deepest text shows the chain-too-deep marker")
_check(int(deepest["depth"]) == Roller.MAX_DEPTH, "deepest step is at the limit")
# Mixed: pipes and references count the same depth.
var ta := _table("ta", "TA", ["[[TB]]"])
var tb := _table("tb", "TB", ["pipe"])
tb.entries[0].add_pipe("ta")
var b2 := _board([ta, tb])
var n2 := Roller.roll(b2, "ta", _rng(7))
var worst := 0
for s in Roller.flatten(n2, []):
worst = maxi(worst, int(s["depth"]))
_check(worst <= Roller.MAX_DEPTH + 1, "mixed pipes and refs never go past the limit (%d)" % worst)
func _test_missing_and_unset() -> void:
var t := _table("t", "T", ["[[Nowhere]] and {ghost}"])
var n := Roller.roll(_board([t]), "t", _rng(8))
_eq(n["summary"], "[url=missing:Nowhere]⚠ Nowhere[/url] and [url=unset:ghost]{ghost?}[/url]", "missing and unset markers")
_eq(Formatter.strip_tags(n["summary"]), "⚠ Nowhere (missing table) and {ghost?}", "markers read as text")
func _test_decks_through_state() -> void:
var deck := _table("deck", "Deck", ["A", "B", "C"])
deck.card_mode = true
var b := _board([deck])
var dir := "user://test_integration_decks"
var st := StateStore.new(dir)
st.reload()
var r := _rng(9)
var seen := {}
# Each roll loads the deck from the store and saves it back, like Main does.
for i in 3:
var decks := {}
var saved := st.get_deck(b.id, "deck")
if not saved.is_empty():
decks["deck"] = DeckState.from_dict(saved)
var n := Roller.roll(b, "deck", r, 0, decks)
seen[(n["entry"] as TableEntry).text] = true
_check(not n.has("reshuffled"), "no reshuffle while cards are left")
st.set_deck(b.id, "deck", (decks["deck"] as DeckState).to_dict())
st.save()
_check(seen.size() == 3, "three rolls through the store deal three different cards")
var st2 := StateStore.new(dir)
var restored := DeckState.from_dict(st2.get_deck(b.id, "deck"))
_check(restored.cards_left(deck) == Vector2i(0, 3), "a reloaded store remembers the empty deck")
var decks2 := {"deck": restored}
var n4 := Roller.roll(b, "deck", r, 0, decks2)
_check(n4.get("reshuffled", false), "empty deck from the store reshuffles")
_check(Roller.step_of(n4).get("reshuffled", false), "step notes the reshuffle")
st2.forget_table(b.id, "deck")
_check(st2.get_deck(b.id, "deck").is_empty(), "forget_table drops the deck")
DirAccess.remove_absolute(st.state_path())
DirAccess.remove_absolute(dir.path_join("state"))
DirAccess.remove_absolute(dir)
func _test_lit_and_steps() -> void:
var b := _quest_board()
b.get_table("quest").entries[0].add_pipe("names")
var n := Roller.roll(b, "quest", _rng(10))
var le := {}
var lp := {}
var lt := {}
Roller.collect_lit(n, le, lp, lt)
_check(lp.has(Roller.ref_key("quest", "quest0", "names")), "reference pipe is lit")
_check(lp.has(Roller.pipe_key("quest", "quest0", "names")), "real pipe is lit too")
_check(Roller.is_ref_key(Roller.ref_key("a", "b", "c")) and not Roller.is_ref_key(Roller.pipe_key("a", "b", "c")), "ref keys are told apart")
_check((lt[Roller.entry_key("quest", "quest0")] as String).contains("Aldric"), "lit texts hold the expanded text")
# Steps survive JSON (history is saved as JSON).
var steps := Roller.flatten(n, [])
var back: Variant = JSON.parse_string(JSON.stringify(steps))
_check(back is Array and (back as Array).size() == steps.size() and back[0]["text"] == steps[0]["text"], "steps round-trip through JSON")
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(got == want, "%s\n got: %s\n want: %s" % [what, str(got), str(want)])
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

View file

@ -0,0 +1 @@
uid://b8wmtk471t5hv

274
tests/test_io.gd Normal file
View file

@ -0,0 +1,274 @@
extends SceneTree
## Headless checks for the import/export converters.
## Run: godot --headless --path . -s res://tests/test_io.gd
const TMP_DIR := "user://test_io_tmp/"
var _failures := 0
func _init() -> void:
DirAccess.make_dir_recursive_absolute(TMP_DIR)
_test_json()
_test_canvas()
_test_canvas_stripped()
_test_mermaid_dot()
_test_graphml()
_cleanup()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## Two tables with weights, ranges, count/save_as pipes, an inline reference, a
## missing target, BBCode, quotes and brackets.
func _small() -> Dictionary:
return {
"format_version": 2, "id": "demo", "name": "Demo \"Set\"",
"tables": [
{"id": "loot", "name": "Loot", "x": 40, "y": 60, "details": "Treasure [b]stuff[/b]\nline 2", "tags": ["a", "b"], "entries": [
{"id": "e1", "text": "Gold coins", "weight": 3},
{"id": "e2", "text": "[b]Melee[/b] weapon \"sharp\" [1]", "details": "A [i]nice[/i] one",
"pipes": [{"table": "weapons", "count": 2, "save_as": "weapon"}, "ghost"]},
{"id": "e3", "text": "Try [[Weapons -> w2]] again"},
]},
{"id": "weapons", "name": "Weapons", "x": 420, "y": 80, "dice": "1d6", "card_mode": true, "entries": [
{"id": "e1", "text": "Dagger", "range": [1, 2]},
{"id": "e2", "text": "Sword", "range": [3, 5], "pipes": ["loot"]},
{"id": "e3", "text": "Warhammer", "range": [6, 6]},
]},
],
}
func _test_json() -> void:
var sample := SampleBoard.create().to_dict()
var text := JsonIO.export_json(sample)
var res := JsonIO.import_json(text)
_check(res["ok"], "sample JSON imports")
var col: Dictionary = res["collection"]
var canon := JsonIO.canonical(sample)
_check(col["tables"] == canon["tables"], "sample JSON round-trips its tables")
_check(col["format_version"] == 2 and str(col["id"]) != "" and str(col["name"]) != "", "legacy file gets version 2, id and name")
var wild: Dictionary = {}
for t in col["tables"]:
if t["id"] == "wilderness":
wild = t
_check(wild.get("dice", "") == "1d100" and not wild.has("die"), "legacy die: 100 becomes dice 1d100")
var small := _small()
var res2 := JsonIO.import_json(JsonIO.export_json(small))
_check(res2["ok"] and res2["collection"] == JsonIO.canonical(small), "small collection round-trips exactly")
_check(not JsonIO.export_json({"tables": [], "state": {"draws": 1}}).contains("state"), "export drops unknown/local keys")
# Legacy keys: triggers, die, collection name.
var legacy := JsonIO.import_json('{"format_version":1,"collection":"Old","tables":[{"id":"a","name":"A","die":20,"entries":[{"text":"x","triggers":["a"]}]}]}')
_check(legacy["ok"] and legacy["collection"]["name"] == "Old", "legacy collection key becomes name")
var lt: Dictionary = legacy["collection"]["tables"][0]
_check(lt["dice"] == "1d20" and lt["entries"][0]["pipes"] == ["a"] and lt["entries"][0]["id"] == "e1", "legacy die/triggers/missing entry id handled")
# Id collisions: duplicate and missing table ids, duplicate entry ids; pipes keep pointing right.
var dup := {"tables": [
{"id": "t", "name": "First", "entries": [{"id": "x", "text": "a", "pipes": ["t"]}, {"id": "x", "text": "b"}]},
{"id": "t", "name": "Second", "entries": [{"text": "c", "pipes": ["First"]}]},
{"name": "Third Table", "entries": [{"text": "d", "pipes": ["t"]}]},
]}
var dres := JsonIO.import_dict(dup)
_check(dres["ok"], "colliding ids still import")
var dt: Array = dres["collection"]["tables"]
var ids := {}
for t in dt:
ids[t["id"]] = true
_check(ids.size() == 3, "table ids are unique after import")
_check(dt[0]["id"] == "t" and dt[1]["id"] != "t" and dt[2]["id"] == "third_table", "first keeps id, others get fresh ones")
_check(dt[0]["entries"][0]["id"] != dt[0]["entries"][1]["id"], "duplicate entry ids are fixed")
_check(dt[1]["entries"][0]["pipes"] == ["t"], "pipe by table name is resolved to the id")
_check(dt[2]["entries"][0]["pipes"] == ["t"], "pipe to the original id keeps pointing at the first table")
# Validation.
_check(not JsonIO.import_json("not json")["ok"], "garbage is rejected")
_check(not JsonIO.import_json("[1,2]")["ok"], "non-object is rejected")
_check(not JsonIO.import_json('{"nope":1}')["ok"], "missing tables is rejected")
_check(not JsonIO.import_json('{"tables":[3]}')["ok"], "non-object table is rejected")
_check(not JsonIO.import_json('{"format_version":9,"tables":[]}')["ok"], "future version is rejected")
_check((JsonIO.import_json("not json")["errors"] as Array).size() == 1, "errors are listed")
# Sanitize hook reaches every visible string.
var san := func(s: String) -> String: return s.replace("[b]", "").replace("[/b]", "").to_upper()
var sres := JsonIO.import_json(JsonIO.export_json(small), san)
var st: Dictionary = sres["collection"]["tables"][0]
_check(st["name"] == "LOOT" and st["entries"][1]["text"].begins_with("MELEE WEAPON"), "sanitize applies to names and entry text")
_check(st["details"] == "TREASURE STUFF\nLINE 2" and st["tags"] == ["A", "B"], "sanitize applies to details and tags")
_check(st["entries"][1]["pipes"][0]["save_as"] == "WEAPON" and st["entries"][1]["pipes"][0]["table"] == "weapons", "sanitize touches save_as but not ids")
func _test_canvas() -> void:
var small := _small()
var text := CanvasIO.export_canvas(small)
var doc: Variant = JSON.parse_string(text)
_check(doc is Dictionary and doc["nodes"] is Array and doc["edges"] is Array, "canvas is valid JSON with nodes and edges")
var groups := 0
var texts: Array[String] = []
for n in doc["nodes"]:
if n["type"] == "group":
groups += 1
else:
texts.append(n["text"])
_check(groups == 2, "canvas has a group per table")
_check(texts.has("3 × Gold coins") and texts.has("1–2: Dagger") and texts.has("6–6: Warhammer"), "canvas text shows weights and ranges (%s)" % str(texts))
var labels: Array[String] = []
for e in doc["edges"]:
labels.append(str(e.get("label", "")))
_check(labels.has("×2 → weapon") and labels.has("ref → w2"), "canvas edge labels (%s)" % str(labels))
_check(doc["edges"].size() == 3, "canvas edges: 2 pipes + 1 ref (missing target skipped), got %d" % doc["edges"].size())
var res := CanvasIO.import_canvas(text)
_check(res["ok"], "canvas imports")
var want := JsonIO.canonical(small)
var got: Dictionary = res["collection"]
_check(got["tables"] == want["tables"], "canvas round trip keeps every field")
_check(got["id"] == "demo" and got["name"] == small["name"], "canvas round trip keeps collection id and name")
# Group sizing: entries sit inside their group.
var ok_inside := true
var group_rects := {}
for n in doc["nodes"]:
if n["type"] == "group":
group_rects[n["id"]] = Rect2(n["x"], n["y"], n["width"], n["height"])
for n in doc["nodes"]:
if n["type"] == "text":
var r := Rect2(n["x"], n["y"], n["width"], n["height"])
var inside := false
for gr in group_rects.values():
if (gr as Rect2).encloses(r):
inside = true
ok_inside = ok_inside and inside
_check(ok_inside, "every entry node fits inside a group")
var sample := SampleBoard.create().to_dict()
var big := CanvasIO.import_canvas(CanvasIO.export_canvas(sample))
_check(big["ok"] and big["collection"]["tables"] == JsonIO.canonical(sample)["tables"], "sample board survives a canvas round trip")
func _test_canvas_stripped() -> void:
var text := CanvasIO.export_canvas(_small())
var doc: Dictionary = JSON.parse_string(text)
doc.erase("tabletower")
for n in doc["nodes"]:
n.erase("tabletower")
for e in doc["edges"]:
e.erase("tabletower")
var res := CanvasIO.import_canvas(JSON.stringify(doc))
_check(res["ok"], "stripped canvas imports")
_check(not (res["guesses"] as Array).is_empty(), "stripped canvas reports guesses")
var tables: Array = res["collection"]["tables"]
_check(tables.size() == 2, "stripped: two tables")
var loot: Dictionary = tables[0]
var weapons: Dictionary = tables[1]
_check(loot["name"] == "Loot" and loot["x"] == 40 and loot["y"] == 60, "stripped: name and position")
_check(loot["entries"].size() == 3 and loot["entries"][0]["text"] == "Gold coins" and loot["entries"][0]["weight"] == 3, "stripped: weighted entry recovered")
_check(not loot.has("dice"), "stripped: unranged table has no dice")
_check(weapons.get("dice", "") == "1d6", "stripped: dice inferred from ranges")
_check(weapons["entries"][1]["range"] == [3, 5] and weapons["entries"][1]["text"] == "Sword", "stripped: ranges recovered")
_check(loot["entries"][1]["text"] == "Melee weapon \"sharp\" [1]", "stripped: BBCode is gone from visible text")
var pipe: Variant = loot["entries"][1].get("pipes", [])[0]
_check(pipe is Dictionary and pipe["table"] == weapons["id"] and pipe["count"] == 2 and pipe["save_as"] == "weapon", "stripped: count and save_as parsed from edge label")
_check(weapons["entries"][1].get("pipes", []) == [loot["id"]], "stripped: plain pipe becomes a table id")
_check(not loot["entries"][2].has("pipes"), "stripped: reference edges do not become pipes")
var found := false
for g in res["guesses"]:
found = found or (g as String).contains("1d6")
_check(found, "stripped: dice guess is reported")
# A d100 table written with 00 for the top.
var d100 := CanvasIO.import_canvas(CanvasIO.export_canvas({"tables": [{"id": "w", "name": "W", "dice": "1d100", "entries": [
{"text": "low", "range": [1, 95]}, {"text": "high", "range": [96, 100]}]}]}).replace("\"tabletower\"", "\"zz\""))
var wt: Dictionary = d100["collection"]["tables"][0]
_check(wt["entries"][1]["range"] == [96, 100] and wt["dice"] == "1d100", "stripped: 96–00 reads as 96-100")
_check(not CanvasIO.import_canvas("{}")["collection"].has("tables") or not CanvasIO.import_canvas("{}")["ok"], "empty canvas is not ok")
_check(not CanvasIO.import_canvas("nope")["ok"], "invalid canvas JSON is not ok")
func _test_mermaid_dot() -> void:
var small := _small()
var m := MermaidExporter.export_mermaid(small)
_check(m.begins_with("graph LR"), "mermaid starts with graph LR")
_check(m.contains("t0[\"Loot\"]") and m.contains("t1[\"Weapons (1d6)\"]"), "mermaid nodes, dice in label")
_check(m.contains("t0 -->|\"") and m.contains("×2 → weapon") and m.contains("| t1"), "mermaid pipe edge with count and save_as")
_check(m.contains("t0 -.->|\"") , "mermaid dashed edge for reference")
_check(m.contains("t1 -->|\"Sword") and m.contains("| t0"), "mermaid pipe back to Loot")
_check(m.contains("missing: ghost") and m.contains(":::missing"), "mermaid marks the missing target")
_check(not m.contains("[b]") and not m.contains("[/b]"), "mermaid strips BBCode")
_check(m.contains("#quot;sharp#quot;") and m.contains("#91;1#93;"), "mermaid escapes quotes and brackets")
for line in m.split("\n"):
if line.contains("-->|") or line.contains("-.->|"):
# Between the pipes there must be exactly one quoted string.
var inner: String = line.get_slice("|", 1)
_check(inner.begins_with("\"") and inner.ends_with("\"") and inner.count("\"") == 2, "mermaid label is one clean quoted string: " + line)
var d := DotExporter.export_dot(small)
_check(d.begins_with("digraph TableTower {") and d.strip_edges().ends_with("}"), "dot has a digraph wrapper")
_check(d.contains("Weapons (1d6)") and d.contains("PORT=\"e1\""), "dot table labels and entry ports")
_check(d.contains("t0:e1:e -> t1:head:w [label=\"×2 → weapon\"]"), "dot pipe edge from entry port to table")
_check(d.contains("t0:e2:e -> t1:head:w [label=\"ref → w2\", style=dashed]"), "dot dashed reference edge")
_check(d.contains("t1:e1:e -> t0:head:w;"), "dot plain pipe edge")
_check(d.contains("missing: ghost") and d.contains("color=red"), "dot marks the missing target")
_check(d.contains("&quot;sharp&quot;") and not d.contains("[b]"), "dot escapes quotes in HTML labels and strips BBCode")
_check(d.contains("label=\"Demo \\\"Set\\\"\""), "dot escapes quotes in strings")
_check(DotExporter.escape_string("a\"b\\c\nd") == "a\\\"b\\\\c\\nd", "dot string escaping")
_check(DotExporter.escape_html("<a&b>") == "&lt;a&amp;b&gt;", "dot html escaping")
# Big tables don't explode.
var sm := MermaidExporter.export_mermaid(SampleBoard.create().to_dict())
var sd := DotExporter.export_dot(SampleBoard.create().to_dict())
_check(sm.contains("graph LR") and sd.contains("more"), "sample board exports to mermaid and dot")
func _test_graphml() -> void:
var small := _small()
var text := GraphMLIO.export_graphml(small)
_check(text.contains("<key id=\"node_dice\"") and text.contains("<edge ") and text.contains("&quot;sharp"), "graphml has keys, edges and escaped text")
var p := XMLParser.new()
p.open_buffer(text.to_utf8_buffer())
var parsed := true
while true:
var err := p.read()
if err == ERR_FILE_EOF:
break
if err != OK:
parsed = false
break
_check(parsed, "graphml is well-formed XML")
var res := GraphMLIO.import_graphml(text)
_check(res["ok"], "graphml imports: " + str(res["errors"]))
_check(res["collection"] == JsonIO.canonical(small), "graphml round trip keeps everything")
var sample := SampleBoard.create().to_dict()
var big := GraphMLIO.import_graphml(GraphMLIO.export_graphml(sample))
_check(big["ok"] and big["collection"]["tables"] == JsonIO.canonical(sample)["tables"], "sample board survives a graphml round trip")
# Foreign GraphML: nodes become tables, edges entries.
var foreign := '<?xml version="1.0"?><graphml xmlns="http://graphml.graphdrawing.org/xmlns"><key id="d0" for="node" attr.name="name" attr.type="string"/><graph edgedefault="directed"><node id="a"><data key="d0">Alpha</data></node><node id="b"><data key="d0">Beta</data></node><edge source="a" target="b"/></graph></graphml>'
var fres := GraphMLIO.import_graphml(foreign)
_check(fres["ok"] and fres["collection"]["tables"].size() == 2 and not (fres["guesses"] as Array).is_empty(), "foreign graphml imports with guesses")
_check(fres["collection"]["tables"][0]["entries"][0]["pipes"] == ["beta"], "foreign graphml edge becomes a pipe")
_check(not GraphMLIO.import_graphml("<nope/>")["ok"], "non-graphml is rejected")
# Write a file once to make sure the text survives disk.
var path := TMP_DIR + "x.graphml"
var f := FileAccess.open(path, FileAccess.WRITE)
f.store_string(text)
f.close()
_check(GraphMLIO.import_graphml(FileAccess.get_file_as_string(path))["collection"] == JsonIO.canonical(small), "graphml survives a file")
func _cleanup() -> void:
var dir := DirAccess.open(TMP_DIR)
if dir != null:
for f in dir.get_files():
dir.remove(f)
DirAccess.remove_absolute(TMP_DIR)
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

1
tests/test_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://7axb3khxugbb

374
tests/test_model.gd Normal file
View file

@ -0,0 +1,374 @@
extends SceneTree
## Headless checks for dice, weights, pipe options, card mode and JSON.
## Run: godot --headless --path . -s res://tests/test_model.gd
var _failures := 0
func _init() -> void:
_test_dice()
_test_weights()
_test_ranged_dice()
_test_pipes()
_test_cards()
_test_cycles()
_test_seed()
_test_json()
_test_sample()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _entry(id: String, text: String, weight: int = 1) -> TableEntry:
var e := TableEntry.new(id, text)
e.weight = weight
return e
func _ranged(id: String, dice: String, spans: Array) -> RollTable:
var t := RollTable.new(id, id)
t.dice = dice
for i in spans.size():
var e := _entry("%s%d" % [id, i], "r%d" % i)
e.has_range = true
e.range_lo = spans[i][0]
e.range_hi = spans[i][1]
t.entries.append(e)
return t
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
for t in tables:
b.tables.append(t)
return b
func _rng(seed_value: int) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
func _test_dice() -> void:
var d := Dice.parse("2d6")
_check(d.valid and d.min_value() == 2 and d.max_value() == 12, "2d6 parses with range 2–12")
var d2 := Dice.parse(" 1D8 + 2 ")
_check(d2.valid and d2.min_value() == 3 and d2.max_value() == 10 and d2.expression() == "1d8+2", "1d8+2 parses (spaces, case)")
var d3 := Dice.parse("3d4-1")
_check(d3.valid and d3.min_value() == 2 and d3.max_value() == 11, "3d4-1 parses")
_check(Dice.parse("d20").valid and Dice.parse("d20").count == 1, "d20 means 1d20")
for bad in ["", "abc", "0d6", "21d6", "1d1", "1d1001", "2d", "2d6+", "1d6*2", "-1d6", "1d6+x", "1d6+99999"]:
_check(not Dice.parse(bad).valid, "invalid dice rejected: '%s'" % bad)
_check(Dice.parse("nope").min_value() == 0 and Dice.parse("nope").roll(_rng(1)) == 0, "invalid dice roll nothing")
_check(d.label() == "2d6" and Dice.parse("1d100").label() == "d100" and d2.label() == "1d8+2", "dice labels")
for expr in ["2d6", "1d100", "1d8+2", "20d1000", "3d4-1"]:
var dist := Dice.parse(expr).distribution()
var sum := 0.0
for v: int in dist:
sum += float(dist[v])
_check(absf(sum - 1.0) < 1e-9, "distribution of %s sums to 1 (%.12f)" % [expr, sum])
var two := d.distribution()
_check(absf(float(two[7]) - 1.0 / 6.0) < 1e-12 and absf(float(two[2]) - 1.0 / 36.0) < 1e-12, "2d6: P(7)=1/6, P(2)=1/36")
_check(not two.has(1) and not two.has(13), "2d6 has no impossible totals")
_check(d2.distribution().has(3) and not d2.distribution().has(2), "1d8+2 distribution starts at 3")
var r := _rng(7)
var seen := {}
for i in 3000:
var v := d.roll(r)
seen[v] = seen.get(v, 0) + 1
_check(seen.size() == 11, "2d6 rolls cover 2–12")
_check(absf(float(seen[7]) / 3000.0 - 1.0 / 6.0) < 0.03, "2d6 rolls land on 7 about 1/6 of the time")
func _test_weights() -> void:
var t := RollTable.new("w", "W")
t.entries.append(_entry("a", "Gold", 3))
t.entries.append(_entry("b", "Silver", 1))
t.entries.append(_entry("c", "Never", 0))
_check(absf(t.chance(t.entries[0]) - 0.75) < 1e-9 and t.chance(t.entries[2]) == 0.0, "weighted chance() is weight/total")
_check(t.die_size() == 3 and t.dice_label() == "d3", "plain table die size stays the entry count")
_check(t.num_label(t.entries[2], 2) == "3", "plain num_label stays the row number")
var b := _board([t])
var r := _rng(99)
var counts := {}
for i in 8000:
var n := Roller.roll(b, "w", r)
var text: String = (n["entry"] as TableEntry).text
counts[text] = counts.get(text, 0) + 1
_check(absf(float(counts["Gold"]) / 8000.0 - 0.75) < 0.02, "weight 3 of 4 comes up about 75%")
_check(not counts.has("Never"), "weight 0 never comes up")
t.entries[0].weight = 0
t.entries[1].weight = 0
_check(Roller.roll(b, "w", r).has("stop"), "all-zero weights stop instead of crashing")
_check(t.chance(t.entries[0]) == 0.0, "all-zero weights give 0 chance")
func _test_ranged_dice() -> void:
var t := _ranged("wx", "2d6", [[2, 4], [5, 9], [10, 12]])
_check(t.is_ranged() and t.die_size() == 12 and t.min_value() == 2, "2d6 ranged table spans 2–12")
_check(t.dice_label() == "2d6", "dice_label is 2d6")
_check(t.range_problems() == "", "2d6 ranges 2–12 are clean")
var total := 0.0
for e in t.entries:
total += t.chance(e)
_check(absf(total - 1.0) < 1e-9, "2d6 chances sum to 1")
_check(absf(t.chance(t.entries[0]) - 6.0 / 36.0) < 1e-9, "2–4 on 2d6 is 6/36")
_check(absf(t.chance(t.entries[1]) - 24.0 / 36.0) < 1e-9, "5–9 on 2d6 is 24/36")
var seven := _ranged("s", "2d6", [[2, 6], [7, 7], [8, 12]])
_check(seven.chance(seven.entries[1]) > seven.chance(seven.entries[0]) / 5.0, "7 is the most likely single value")
_check(t.fmt(5) == "5" and t.num_label(t.entries[1], 1) == "5–9", "2d6 uses plain numbers")
var gappy := _ranged("g", "2d6", [[2, 5], [7, 14]])
_check(gappy.range_problems().contains("No result for 6."), "gap inside 2–12 reported: %s" % gappy.range_problems())
_check(gappy.range_problems().contains("outside"), "out-of-span range reported: %s" % gappy.range_problems())
var one_low := _ranged("l", "2d6", [[1, 12]])
_check(one_low.range_problems().contains("outside"), "range starting below min reported")
var d100 := _ranged("h", "1d100", [[1, 50], [51, 100]])
_check(d100.fmt(100) == "00" and d100.fmt(7) == "07", "1d100 table formats 00 and two digits")
var d6 := _ranged("k", "1d8+2", [[3, 10]])
_check(d6.fmt(10) == "10" and d6.fmt(3) == "3" and d6.dice_label() == "1d8+2", "1d8+2 uses plain numbers")
var r := _rng(5)
var b := _board([t])
var low := 0
for i in 4000:
var n := Roller.roll(b, "wx", r)
_check(int(n["value"]) >= 2 and int(n["value"]) <= 12, "ranged value in span")
if int(n["index"]) == 0:
low += 1
_check(absf(float(low) / 4000.0 - 6.0 / 36.0) < 0.025, "ranged 2d6 roll frequencies follow the distribution")
func _test_pipes() -> void:
var src := RollTable.new("src", "Src")
var e := _entry("e1", "Go")
e.add_pipe("dst", 3, "foe")
e.add_pipe("other")
e.add_pipe("dst", 3, "foe")
src.entries.append(e)
_check(e.pipes.size() == 2, "pipe targets stay unique")
var dst := RollTable.new("dst", "Dst")
dst.entries.append(_entry("d1", "Thing"))
var other := RollTable.new("other", "Other")
other.entries.append(_entry("o1", "Else"))
var b := _board([src, dst, other])
var n := Roller.roll(b, "src", _rng(1))
var kids: Array = n["children"]
_check(kids.size() == 4, "count 3 plus one plain pipe gives 4 children (got %d)" % kids.size())
var saved := 0
for c: Dictionary in kids:
if c.get("save_as", "") == "foe":
saved += 1
_check(saved == 3, "save_as is set on the 3 counted children")
_check(not (kids[3] as Dictionary).has("save_as"), "plain pipe has no save_as")
_check(not n.has("save_as"), "root node has no save_as")
_check(Roller.flatten(n, []).size() == 5, "flatten walks counted children")
var lit_e := {}
var lit_p := {}
Roller.collect_lit(n, lit_e, lit_p)
_check(lit_p.has(Roller.pipe_key("src", "e1", "dst")), "counted pipe is lit")
e.remove_pipe("dst")
_check(e.pipes == ["other"] and e.pipe_count.is_empty() and e.pipe_save.is_empty(), "remove_pipe clears options")
_check(e.count_for("other") == 1 and e.save_for("other") == "", "defaults are count 1, no save")
e.set_pipe_count("other", 0)
_check(e.count_for("other") == 1, "count below 1 clamps to 1")
e.set_pipe_save("other", "@loot")
_check(e.to_dict()["pipes"] == [{"table": "other", "save_as": "@loot"}], "save-only pipe serializes as object")
func _test_cards() -> void:
var t := RollTable.new("deck", "Deck")
t.card_mode = true
t.entries.append(_entry("a", "A"))
t.entries.append(_entry("b", "B", 2))
t.entries.append(_entry("c", "C"))
t.entries.append(_entry("z", "Z", 0))
var b := _board([t])
var decks := {}
var r := _rng(21)
var got := {}
for i in 4:
var n := Roller.roll(b, "deck", r, 0, decks)
var tx: String = (n["entry"] as TableEntry).text
got[tx] = got.get(tx, 0) + 1
_check(not n.has("reshuffled"), "no reshuffle mid-deck")
_check(got.get("A", 0) == 1 and got.get("B", 0) == 2 and got.get("C", 0) == 1 and not got.has("Z"), "4 draws deal each copy once: %s" % str(got))
var dk: DeckState = decks["deck"]
_check(dk.cards_left(t) == Vector2i(0, 4), "deck shows 0 of 4 left")
var n5 := Roller.roll(b, "deck", r, 0, decks)
_check(n5.get("reshuffled", false) == true and not n5.has("stop"), "empty deck reshuffles and flags the node")
_check(dk.cards_left(t) == Vector2i(3, 4), "after reshuffle one card is drawn")
# Persisting through a dict.
var restored := DeckState.from_dict(dk.to_dict())
_check(restored.cards_left(t) == dk.cards_left(t), "DeckState round-trips through a dictionary")
# Stop mode.
t.deck_empty = "stop"
var d2 := {}
for i in 4:
Roller.roll(b, "deck", r, 0, d2)
var stopped := Roller.roll(b, "deck", r, 0, d2)
_check(stopped.get("stop", "") == "Deck empty", "stop mode returns Deck empty")
(d2["deck"] as DeckState).reshuffle()
_check(not Roller.roll(b, "deck", r, 0, d2).has("stop"), "manual reshuffle deals again")
# Edits.
t.deck_empty = "reshuffle"
var d3 := DeckState.new()
for i in 4:
d3.draw(t, r)
_check(d3.cards_left(t) == Vector2i(0, 4), "fully drawn deck")
t.entries[0].weight = 3
_check(d3.cards_left(t) == Vector2i(2, 6), "raising a weight adds copies")
t.entries.append(_entry("n", "New"))
_check(d3.cards_left(t) == Vector2i(3, 7), "new entries start undrawn")
t.entries.remove_at(1)
_check(d3.cards_left(t) == Vector2i(3, 5), "deleted entries drop out")
var first := d3.draw(t, r)
_check(first.has("index"), "can still draw after edits")
t.entries[0].weight = 1
_check(d3.cards_left(t).x == 1 and d3.cards_left(t).y == 3, "lowering a weight removes copies (%s)" % str(d3.cards_left(t)))
# Ranged deck.
var rt := _ranged("rd", "2d6", [[2, 6], [7, 7], [8, 12]])
rt.card_mode = true
var rb := _board([rt])
var rd := {}
var seen := {}
for i in 3:
var n := Roller.roll(rb, "rd", r, 0, rd)
var idx: int = n["index"]
var v: int = n["value"]
seen[idx] = true
var e: TableEntry = rt.entries[idx]
_check(v >= e.range_lo and v <= e.range_hi, "ranged card value %d is inside its range" % v)
_check(seen.size() == 3, "ranged deck deals every entry once")
_check(Roller.roll(rb, "rd", r, 0, rd).get("reshuffled", false) == true, "ranged deck reshuffles")
func _test_cycles() -> void:
var a := RollTable.new("a", "A")
var ea := _entry("ea", "to b")
ea.add_pipe("b")
a.entries.append(ea)
var bt := RollTable.new("b", "B")
var eb := _entry("eb", "to a")
eb.add_pipe("a")
bt.entries.append(eb)
var board := _board([a, bt])
_check(Roller.endless_cycles(board) == ["a", "b"], "two-table loop is endless")
bt.entries.append(_entry("eb2", "exit"))
_check(Roller.endless_cycles(board).is_empty(), "an exit entry fixes the loop")
bt.entries[1].weight = 0
_check(Roller.endless_cycles(board).size() == 2, "a zero-weight exit does not count")
bt.entries[1].weight = 1
var self_t := RollTable.new("s", "S")
var es := _entry("es", "again")
es.add_pipe("s")
self_t.entries.append(es)
_check(Roller.endless_cycles(_board([self_t])) == ["s"], "sole self-pipe is endless")
self_t.entries.append(_entry("es2", "done"))
_check(Roller.endless_cycles(_board([self_t])).is_empty(), "self-pipe on some entries is fine")
# An entry that pipes into a cycle and a fine table is still stuck.
var ok := RollTable.new("ok", "Ok")
ok.entries.append(_entry("k", "fine"))
var mix := RollTable.new("mix", "Mix")
var em := _entry("em", "both")
em.add_pipe("ok")
em.add_pipe("mix")
mix.entries.append(em)
_check(Roller.endless_cycles(_board([ok, mix])) == ["mix"], "entry needing a cycle blocks its table")
_check(Roller.endless_cycles(SampleBoard.create()).is_empty(), "sample board has no endless cycles")
func _test_seed() -> void:
var board := SampleBoard.create()
var texts: Array[String] = []
for run in 2:
var r := _rng(2024)
var decks := {}
var out := PackedStringArray()
for i in 25:
for s in Roller.flatten(Roller.roll(board, "wilderness", r, 0, decks), []):
out.append("%s=%s" % [s["table"], s["text"]])
for s in Roller.flatten(Roller.roll(board, "party_roles", r, 0, decks), []):
out.append("%s=%s" % [s["table"], s["text"]])
texts.append("|".join(out))
_check(texts[0] == texts[1] and texts[0].length() > 100, "same seed gives the same chains")
var other := _rng(2025)
var diff := PackedStringArray()
for i in 25:
for s in Roller.flatten(Roller.roll(board, "wilderness", other), []):
diff.append("%s=%s" % [s["table"], s["text"]])
_check(not texts[0].begins_with("|".join(diff)), "a different seed gives a different run")
func _test_json() -> void:
var legacy := {"tables": [{"id": "old", "name": "Old", "x": 1, "y": 2, "die": 20, "entries": [
{"id": "e1", "text": "Low", "range": [1, 10], "pipes": ["x", {"table": "y", "count": 2, "save_as": "@pal"}]},
{"id": "e2", "text": "High", "range": [11, 20], "weight": 4, "details": "[b]hi[/b]"}]}]}
var b := TowerBoard.new()
_check(b.load_json(JSON.stringify(legacy)), "legacy board loads")
var t := b.get_table("old")
_check(t.dice == "1d20" and t.die_size() == 20 and t.dice_label() == "d20", "legacy die 20 becomes 1d20")
var e := t.entries[0]
_check(e.pipes == ["x", "y"] and e.count_for("y") == 2 and e.save_for("y") == "@pal" and e.count_for("x") == 1, "mixed string/object pipes load")
_check(t.entries[1].weight == 4 and t.entries[1].details == "[b]hi[/b]", "weight and entry details load")
var d := t.to_dict()
_check(not d.has("die") and d["dice"] == "1d20", "die is no longer written")
var ed: Dictionary = d["entries"][0]
_check(ed["pipes"] == ["x", {"table": "y", "count": 2, "save_as": "@pal"}], "pipes save in contract form")
_check(not (d["entries"][1] as Dictionary).has("pipes"), "empty pipes omitted")
var plain := RollTable.new("p", "P")
plain.entries.append(_entry("e", "x"))
var pd := plain.to_dict()
for k in ["collapsed", "details", "tags", "dice", "card_mode", "deck_empty"]:
_check(not pd.has(k), "default %s omitted" % k)
_check(not (pd["entries"][0] as Dictionary).has("weight") and not (pd["entries"][0] as Dictionary).has("details"), "default entry fields omitted")
plain.details = "Hello"
plain.tags.append("a")
plain.tags.append("b")
plain.card_mode = true
plain.deck_empty = "stop"
var back := RollTable.from_dict(JSON.parse_string(JSON.stringify(plain.to_dict())))
_check(back.details == "Hello" and back.tags == ["a", "b"] and back.card_mode and back.deck_empty == "stop", "details, tags, card mode round-trip")
_check(back.to_dict() == plain.to_dict(), "table dict round-trips")
var sample := SampleBoard.create()
var copy := TowerBoard.new()
_check(copy.load_json(sample.to_json()) and copy.to_json() == sample.to_json(), "sample board JSON round-trips")
func _test_sample() -> void:
var s := SampleBoard.create()
var ids := {}
for t in s.tables:
_check(not ids.has(t.id), "unique table id %s" % t.id)
ids[t.id] = true
var eids := {}
for e in t.entries:
_check(not eids.has(e.id), "unique entry ids in %s" % t.id)
eids[e.id] = true
for p in e.pipes:
_check(s.get_table(p) != null, "pipe target %s exists" % p)
var loot := s.get_table("loot")
_check(loot.entries[0].weight == 3 and absf(loot.chance(loot.entries[0]) - 3.0 / 8.0) < 1e-9, "gold weight 3 of 8")
var roles := s.get_table("party_roles")
_check(roles.card_mode and roles.entries.size() == 6 and roles.position == Vector2(1440, 330), "Party Roles is a 6-card deck")
var w := s.get_table("weather")
_check(w.dice == "2d6" and w.position == Vector2(1790, 380) and w.range_problems() == "", "Weather is a clean 2d6 table")
_check(s.get_table("monsters").entries[0].details != "" and s.get_table("wilderness").details != "", "sample has details")
_check(s.get_table("wilderness").position == Vector2(40, 180) and s.get_table("quality").position == Vector2(1790, 130), "existing positions kept")
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

1
tests/test_model.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dut8l77y7pcoa

103
tests/test_roller.gd Normal file
View file

@ -0,0 +1,103 @@
extends SceneTree
## Headless checks for the data model and roller.
## Run: godot --headless --path . -s res://tests/test_roller.gd
var _failures := 0
func _init() -> void:
var board := SampleBoard.create()
var rng := RandomNumberGenerator.new()
rng.seed = 12345
var trinkets := board.get_table("trinkets")
_check(trinkets.entries.size() == 100, "trinkets has 100 entries")
_check(trinkets.die_size() == 100, "trinkets rolls a d100")
var unique := {}
for e in trinkets.entries:
unique[e.text] = true
_check(unique.size() == 100, "trinket entries are unique")
_check(trinkets.num_label(trinkets.entries[0], 0) == "01", "first trinket is numbered 01")
_check(trinkets.num_label(trinkets.entries[99], 99) == "00", "last trinket is numbered 00")
var wild := board.get_table("wilderness")
_check(wild.is_ranged() and wild.die_size() == 100, "wilderness is a ranged d100")
_check(wild.range_problems() == "", "wilderness ranges have no gaps or overlaps")
_check(wild.num_label(wild.entries[5], 5) == "96–00", "last range reads 96–00")
for e in wild.entries:
_check(e.pipes.size() == 1, "range %s has exactly one pipe" % e.text)
# Range weighting: 01–30 should come up about 30% of the time.
var counts := {}
for i in 20000:
var n := Roller.roll(board, "wilderness", rng)
var text: String = (n["entry"] as TableEntry).text
counts[text] = counts.get(text, 0) + 1
var share := float(counts.get("Travelers on the road", 0)) / 20000.0
_check(absf(share - 0.30) < 0.02, "01–30 rolls about 30%% of the time (got %.3f)" % share)
var rare := float(counts.get("An odd find", 0)) / 20000.0
_check(absf(rare - 0.05) < 0.01, "96–00 rolls about 5%% of the time (got %.3f)" % rare)
# Chains follow pipes.
var reached := false
for i in 500:
var n := Roller.roll(board, "wilderness", rng)
if Roller.reaches(n, "trinkets"):
reached = true
_check(Roller.flatten(n, []).size() == 2, "wilderness → trinkets chain has two steps")
break
_check(reached, "wilderness can reach trinkets")
# Gaps and overlaps are reported.
wild.entries[1].range_lo = 35
_check(wild.range_problems() == "No result for 31–34.", "gap reported: %s" % wild.range_problems())
wild.entries[1].range_lo = 25
_check(wild.range_problems() == "25–30 matches more than one result.", "overlap reported: %s" % wild.range_problems())
wild.entries[1].range_lo = 31
var n_gap := RollTable.new("g", "Gappy")
var only := TableEntry.new("e1", "Low")
only.has_range = true
only.range_lo = 1
only.range_hi = 50
n_gap.entries.append(only)
var stops := 0
for i in 200:
var b2 := TowerBoard.new()
b2.tables.append(n_gap)
if Roller.roll(b2, "g", rng).has("stop"):
stops += 1
_check(stops > 50 and stops < 150, "rolls into a gap stop with a message (%d/200)" % stops)
# A self-pipe stops at the depth limit instead of looping forever.
var loop := RollTable.new("loop", "Loop")
var again := TableEntry.new("e1", "Again")
again.pipes.append("loop")
loop.entries.append(again)
var b3 := TowerBoard.new()
b3.tables.append(loop)
var steps := Roller.flatten(Roller.roll(b3, "loop", rng), [])
_check(steps.size() == Roller.MAX_DEPTH + 2, "self-pipe stops after the depth limit (%d steps)" % steps.size())
# JSON round trip keeps everything.
var copy := TowerBoard.new()
_check(copy.load_json(board.to_json()), "board JSON loads back")
_check(copy.to_json() == board.to_json(), "board JSON round-trips unchanged")
_check(copy.get_table("trinkets").collapsed, "collapsed state is saved")
# Removing a table removes pipes into it.
copy.remove_table("loot")
var dangling := false
for t in copy.tables:
for e in t.entries:
if e.pipes.has("loot"):
dangling = true
_check(not dangling and copy.get_table("loot") == null, "removing a table removes pipes into it")
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

1
tests/test_roller.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dsu5lvppc8ixo

174
tests/test_shell.gd Normal file
View file

@ -0,0 +1,174 @@
extends SceneTree
## Headless checks for the app-shell logic: table settings, collections, import.
## Run: godot --headless --path . -s res://tests/test_shell.gd
const ROOT := "user://test_shell_tmp"
var _failures := 0
func _init() -> void:
_wipe(ROOT)
_test_settings()
_test_ranges()
_test_wrap()
_test_collections()
_test_import()
_test_export()
_wipe(ROOT)
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _plain_table(n: int = 4) -> RollTable:
var t := RollTable.new("t", "Loot")
for i in n:
t.entries.append(TableEntry.new("e%d" % i, "Item %d" % i))
return t
func _test_settings() -> void:
var t := _plain_table()
var r := TableSettingsDialog.apply_settings(t, {"name": " Gems ", "details": "[b]x[/b]", "tags": "a, b ,, a",
"ranged": false, "dice": "1d100", "card_mode": true, "deck_empty": "stop"})
_check(r["ok"], "plain settings apply")
_check(t.name == "Gems" and t.details == "[b]x[/b]", "name trimmed, details kept")
_check(t.tags == ["a", "b"], "tags split and de-duplicated")
_check(t.card_mode and t.deck_empty == "stop", "card mode and deck_empty set")
_check(r["deck_reset"], "card mode change resets the deck")
var bad := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "banana", "name": "Changed"})
_check(not bad["ok"] and t.name == "Gems" and not t.is_ranged(), "invalid dice changes nothing")
var ok := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "2d6", "name": "Gems",
"card_mode": true, "deck_empty": "stop"})
_check(ok["ok"] and t.is_ranged() and t.dice == "2d6", "converted to ranged 2d6")
_check(t.range_problems() == "", "default ranges cover 2d6 cleanly: '%s'" % t.range_problems())
var back := TableSettingsDialog.apply_settings(t, {"ranged": false, "dice": "2d6", "name": "Gems",
"card_mode": true, "deck_empty": "stop"})
_check(back["ok"] and not t.is_ranged(), "converted back to plain drops ranges")
_check(t.to_dict().has("dice") == false, "plain table saves no dice")
var r2 := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "1d20", "name": "Gems"})
_check(r2["ok"] and t.dice == "1d20" and t.range_problems() == "", "ranged 1d20 is clean")
var r3 := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "1d8", "name": "Gems"})
_check(r3["ok"] and t.dice == "1d8" and t.range_problems() != "", "shrinking dice reports range problems")
func _test_ranges() -> void:
# Weighted: 1 and 3 on a d100 -> 25 and 75 values.
var t := _plain_table(2)
t.entries[0].weight = 1
t.entries[1].weight = 3
t.dice = "1d100"
TableSettingsDialog.assign_ranges(t)
_check(t.entries[0].range_lo == 1 and t.entries[0].range_hi == 25, "weight 1 of 4 gets 1-25")
_check(t.entries[1].range_lo == 26 and t.entries[1].range_hi == 100, "weight 3 of 4 gets 26-100")
# More entries than values: everything stays valid and in span.
var many := _plain_table(8)
many.dice = "1d6"
TableSettingsDialog.assign_ranges(many)
var lit := 0
for e in many.entries:
if e.has_range:
lit += 1
_check(e.range_lo >= 1 and e.range_hi <= 6 and e.range_lo <= e.range_hi, "range inside 1d6")
_check(lit == 6, "six values -> six ranges, got %d" % lit)
# Weight 0 entries get no range; extra pipes are dropped.
var z := _plain_table(3)
z.entries[1].weight = 0
z.entries[0].pipes = ["a", "b"] as Array[String]
TableSettingsDialog.assign_ranges(z)
_check(not z.entries[1].has_range and z.entries[0].pipes.size() == 1, "weight 0 skipped, extra pipe dropped")
_check(z.entries[2].range_hi == 100, "last live entry reaches the top")
func _test_wrap() -> void:
var r := TableSettingsDialog.wrap_text("hello world", Vector2i(0, 5), "[b]", "[/b]")
_check(r["text"] == "[b]hello[/b] world" and r["caret"] == 12, "bold wraps selection")
var r2 := TableSettingsDialog.wrap_text("ab", Vector2i(1, 1), "[i]", "[/i]")
_check(r2["text"] == "a[i][/i]b" and r2["caret"] == 4, "empty selection inserts a pair")
func _test_collections() -> void:
var state := StateStore.new(ROOT)
var lib := LibraryStore.new(ROOT, state)
var a := CollectionSwitcher.create_collection(lib, null, "Alpha")
a.tables.append(_plain_table())
var b := CollectionSwitcher.create_collection(lib, a, "Beta")
_check(lib.list().size() == 2, "two collections after create")
_check(lib.load_collection(a.id).tables.size() == 1, "creating saves the current collection first")
var back := CollectionSwitcher.switch_collection(lib, b, a.id)
_check(back != null and back.id == a.id and back.tables.size() == 1, "switch loads the other collection")
_check(CollectionSwitcher.switch_collection(lib, a, "missing") == null, "switch to a missing id is null")
_check(not CollectionSwitcher.rename_collection(lib, a, " "), "blank rename refused")
_check(CollectionSwitcher.rename_collection(lib, a, "Alpha Prime"), "rename works")
_check(lib.load_collection(a.id).name == "Alpha Prime" and a.id == "alpha", "rename keeps the id")
var copy := CollectionSwitcher.duplicate_collection(lib, a, "Alpha copy")
_check(copy != null and copy.id != a.id and copy.tables.size() == 1, "duplicate copies the tables")
state.set_variable(a.id, "x", "1")
var next := CollectionSwitcher.delete_collection(lib, copy)
_check(next != null and next.id != copy.id and not lib.exists(copy.id), "delete returns another collection")
_check(state.get_variables(a.id).has("x"), "delete leaves other collections' state")
for e in lib.list():
var c := lib.load_collection(str(e["id"]))
CollectionSwitcher.delete_collection(lib, c)
_check(lib.list().size() == 1, "deleting the last collection leaves a fresh empty one")
func _test_import() -> void:
var lib := LibraryStore.new(ROOT, StateStore.new(ROOT))
var before := lib.list().size()
var canvas := JSON.stringify({
"nodes": [
{"id": "g1", "type": "group", "label": "Loot [url=https://x.example]link[/url]", "x": 0, "y": 0, "width": 400, "height": 300},
{"id": "n1", "type": "text", "text": "Coins [img]res://icon.svg[/img][b]bold[/b]", "x": 10, "y": 40, "width": 300, "height": 60},
{"id": "n2", "type": "text", "text": "A [color=red]gem[/color]", "x": 10, "y": 120, "width": 300, "height": 60},
],
"edges": [],
})
var r := IoMenu.import_as_collection(lib, canvas, "loot.canvas")
_check(r["ok"], "canvas import ok: %s" % str(r["errors"]))
var b: TowerBoard = r["board"]
_check(b != null and lib.list().size() == before + 1 and lib.exists(b.id), "import adds a new collection")
var all := ""
for t in b.tables:
all += t.name + "|"
for e in t.entries:
all += e.text + "|"
_check(not all.contains("[url") and not all.contains("[img") and not all.contains("res://"), "import is sanitized: " + all)
_check(all.contains("[b]bold[/b]") and all.contains("[color=red]gem[/color]"), "safe tags survive: " + all)
var r2 := IoMenu.import_as_collection(lib, canvas, "loot.canvas")
_check(r2["ok"] and r2["board"].id != b.id, "importing twice makes two collections")
var bad := IoMenu.import_as_collection(lib, "{not json", "x.json")
_check(not bad["ok"] and not (bad["errors"] as Array).is_empty() and lib.list().size() == before + 2, "bad file adds nothing")
_check(IoMenu.detect_format("a.canvas", "") == "canvas" and IoMenu.detect_format("a", "<graphml/>") == "graphml", "format detection")
func _test_export() -> void:
var s := SampleBoard.create()
s.name = "Sample"
for f in IoMenu.EXPORTS:
var text := IoMenu.export_text(f["key"], s)
_check(text.length() > 50, "export %s has content" % f["key"])
_check(IoMenu.export_text("mermaid_md", s).contains("```mermaid"), "markdown export has a mermaid fence")
_check(IoMenu.export_text("json", s).contains("\"tables\""), "json export has tables")
_check(IoMenu.default_file_name(s, IoMenu.EXPORTS[1]) == "sample.canvas", "default file name")
func _wipe(path: String) -> void:
var abs := ProjectSettings.globalize_path(path)
if not DirAccess.dir_exists_absolute(abs):
return
var d := DirAccess.open(abs)
for sub in d.get_directories():
_wipe(path.path_join(sub))
for f in d.get_files():
DirAccess.remove_absolute(abs.path_join(f))
DirAccess.remove_absolute(abs)
func _check(cond: bool, msg: String) -> void:
if not cond:
_failures += 1
print("FAIL: ", msg)

1
tests/test_shell.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dpooyjdrrmwk2

204
tests/test_storage.gd Normal file
View file

@ -0,0 +1,204 @@
extends SceneTree
## Headless checks for collections, LibraryStore and StateStore.
## Run: godot --headless --path . -s res://tests/test_storage.gd
const ROOT := "user://test_storage_tmp"
var _failures := 0
func _init() -> void:
_wipe(ROOT)
_test_versions()
_test_library()
_test_migration()
_test_corrupt()
_test_state()
_wipe(ROOT)
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _test_versions() -> void:
var sample := SampleBoard.create()
var v1 := JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]})
var b := TowerBoard.new()
_check(b.load_json(v1), "v1 text loads")
_check(b.tables.size() == sample.tables.size(), "v1 keeps every table")
_check(b.id == "" and b.name == "", "v1 has no id or name")
var d := b.to_dict()
_check(int(d["format_version"]) == 2, "saving writes format_version 2")
var b2 := TowerBoard.new()
b2.id = "x"
b2.name = "X"
b2.tables = b.tables
var b3 := TowerBoard.new()
_check(b3.load_json(b2.to_json()), "v2 text loads")
_check(b3.id == "x" and b3.name == "X", "v2 round-trips id and name")
_check(not TowerBoard.new().load_json("not json"), "garbage is rejected")
_check(TowerBoard.migrate({"format_version": 1, "tables": []})["format_version"] == 2, "migrate steps 1 to 2")
func _test_library() -> void:
var root := ROOT + "/lib"
var lib := LibraryStore.new(root)
_check(lib.list().is_empty(), "empty library lists nothing")
var a := lib.create("Fantasy Loot")
_check(a.id == "fantasy-loot", "slug id from name")
var a2 := lib.create("Fantasy Loot")
_check(a2.id == "fantasy-loot-2", "duplicate names get unique ids")
_check(LibraryStore.slugify(" !! ") == "collection", "empty slug falls back")
_check(lib.exists("fantasy-loot") and not lib.exists("nope") and not lib.exists("../x"), "exists")
a.tables = SampleBoard.create().tables
_check(lib.save(a), "save succeeds")
var back := lib.load_collection("fantasy-loot")
_check(back != null and back.tables.size() == a.tables.size() and back.name == "Fantasy Loot", "load round trip")
_check(lib.rename("fantasy-loot", "Dark Loot"), "rename succeeds")
_check(lib.load_collection("fantasy-loot").name == "Dark Loot", "rename keeps id, changes name")
var copy := lib.duplicate("fantasy-loot", "Dark Loot Copy")
_check(copy != null and copy.id == "dark-loot-copy" and copy.tables.size() == a.tables.size(), "duplicate copies tables")
var names: Array = []
for e in lib.list():
names.append(e["name"])
_check(names == ["Dark Loot", "Dark Loot Copy", "Fantasy Loot"], "list sorted by name: %s" % str(names))
# No temp files left behind by saves.
var leftovers := 0
for f in DirAccess.get_files_at(lib.collections_dir()):
if not f.ends_with(".json"):
leftovers += 1
_check(leftovers == 0, "atomic save leaves no temp files")
# Delete removes the file and its state.
lib.state.set_deck("fantasy-loot", "loot", {"drawn": [1]})
lib.state.set_variable("fantasy-loot", "weapon", "Dagger", "loot")
lib.state.add_history({"collection": "fantasy-loot", "root": "loot"})
lib.state.add_history({"collection": "dark-loot-copy", "root": "loot"})
lib.state.set_setting("last_collection", "fantasy-loot")
_check(lib.delete("fantasy-loot"), "delete succeeds")
_check(not lib.exists("fantasy-loot"), "deleted file is gone")
_check(lib.state.get_deck("fantasy-loot", "loot").is_empty(), "delete drops decks")
_check(lib.state.get_variables("fantasy-loot").is_empty(), "delete drops variables")
_check(lib.state.get_history("fantasy-loot").is_empty() and lib.state.get_history().size() == 1, "delete drops only its history")
_check(lib.state.get_setting("last_collection") == null, "delete clears last_collection if it pointed there")
_check(not lib.delete("fantasy-loot"), "deleting twice returns false")
_check(lib.load_collection("fantasy-loot") == null, "loading a missing collection returns null")
func _test_migration() -> void:
var root := ROOT + "/mig"
DirAccess.make_dir_recursive_absolute(root)
var legacy := root + "/board.json"
var sample := SampleBoard.create()
var f := FileAccess.open(legacy, FileAccess.WRITE)
f.store_string(JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]}))
f.close()
var lib := LibraryStore.new(root)
var b := lib.migrate_legacy()
_check(b != null and b.name == "My Tables" and b.id == "my-tables", "legacy board imported as My Tables")
_check(lib.load_collection("my-tables").tables.size() == sample.tables.size(), "imported tables are saved")
_check(not FileAccess.file_exists(legacy) and FileAccess.file_exists(legacy + ".bak"), "old file renamed to .bak")
_check(lib.migrate_legacy() == null, "migration is a no-op once done")
# Not run when collections already exist.
var f2 := FileAccess.open(legacy, FileAccess.WRITE)
f2.store_string(JSON.stringify({"format_version": 1, "tables": sample.to_dict()["tables"]}))
f2.close()
_check(lib.migrate_legacy() == null and FileAccess.file_exists(legacy), "no migration when collections exist")
func _test_corrupt() -> void:
var root := ROOT + "/bad"
var lib := LibraryStore.new(root)
lib.create("Good")
var f := FileAccess.open(lib.path_for("broken"), FileAccess.WRITE)
f.store_string("{ this is not json")
f.close()
var f2 := FileAccess.open(lib.path_for("wrongshape"), FileAccess.WRITE)
f2.store_string("[1, 2, 3]")
f2.close()
_check(lib.load_collection("broken") == null, "corrupt collection loads as null")
var ids: Array = []
for e in lib.list():
ids.append(e["id"])
_check(ids == ["good"], "list skips unreadable files: %s" % str(ids))
_check(not lib.errors.is_empty(), "errors are recorded")
# Corrupt legacy file is left alone.
var legacy := root + "/board.json"
var f3 := FileAccess.open(legacy, FileAccess.WRITE)
f3.store_string("nope")
f3.close()
var lib2 := LibraryStore.new(root + "/empty")
_check(lib2.migrate_legacy(legacy) == null and FileAccess.file_exists(legacy), "corrupt legacy file is not touched")
# Corrupt state file starts fresh.
var st := StateStore.new(root)
DirAccess.make_dir_recursive_absolute(root + "/state")
var f4 := FileAccess.open(st.state_path(), FileAccess.WRITE)
f4.store_string("garbage")
f4.close()
_check(st.get_variables("c").is_empty(), "corrupt state file reads as empty")
st.set_setting("k", 1)
_check(st.save() and FileAccess.file_exists(st.state_path() + ".corrupt"), "corrupt state moved aside, new one saved")
func _test_state() -> void:
var root := ROOT + "/state"
var st := StateStore.new(root)
_check(st.save() and not FileAccess.file_exists(st.state_path()), "saving an untouched store writes nothing")
st.set_deck("c1", "t1", {"drawn": [3, 5], "n": 10})
st.set_deck("c1", "t2", {"drawn": []})
st.set_variable("c1", "weapon", "Dagger", "t1")
st.set_variable("c1", "armor", "Plate", "t2")
st.set_setting("last_collection", "c1")
for i in 60:
st.add_history({"collection": "c1", "n": i})
_check(st.is_dirty(), "mutation sets dirty")
_check(st.save() and not st.is_dirty(), "save clears dirty")
_check(not FileAccess.file_exists(st.state_path() + ".tmp"), "no temp file after state save")
var st2 := StateStore.new(root)
var deck := st2.get_deck("c1", "t1")
_check(deck.get("n") == 10.0 and (deck["drawn"] as Array).size() == 2, "deck round trip")
_check(st2.get_deck("c1", "nope").is_empty() and st2.get_deck("zz", "t1").is_empty(), "missing deck is empty")
_check(st2.get_variables("c1")["weapon"] == {"value": "Dagger", "source": "t1"}, "variable round trip")
_check(st2.get_setting("last_collection") == "c1" and st2.get_setting("none", "d") == "d", "settings round trip")
var h := st2.get_history()
_check(h.size() == StateStore.HISTORY_CAP, "history capped at 50 (got %d)" % h.size())
_check(h[0]["n"] == 59.0 and h[49]["n"] == 10.0, "history is most recent first")
st2.clear_variable("c1", "weapon")
_check(not st2.get_variables("c1").has("weapon") and st2.get_variables("c1").has("armor"), "clear one variable")
st2.forget_table("c1", "t2")
_check(st2.get_deck("c1", "t2").is_empty() and not st2.get_variables("c1").has("armor"), "forget_table drops deck and its variables")
_check(not st2.get_deck("c1", "t1").is_empty(), "forget_table leaves other tables")
st2.clear_deck("c1", "t1")
_check(st2.get_deck("c1", "t1").is_empty(), "clear_deck")
st2.set_variable("c1", "a", "1")
st2.clear_variables("c1")
_check(st2.get_variables("c1").is_empty(), "clear all variables")
st2.clear_history()
_check(st2.get_history().is_empty(), "clear_history")
st2.save()
var st3 := StateStore.new(root)
_check(st3.get_history().is_empty() and st3.get_deck("c1", "t1").is_empty(), "cleared state persists")
func _wipe(path: String) -> void:
if not DirAccess.dir_exists_absolute(path):
return
for d in DirAccess.get_directories_at(path):
_wipe(path.path_join(d))
for f in DirAccess.get_files_at(path):
DirAccess.remove_absolute(path.path_join(f))
DirAccess.remove_absolute(path)
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

View file

@ -0,0 +1 @@
uid://d10dfnkj6mc2y

219
tests/test_text.gd Normal file
View file

@ -0,0 +1,219 @@
extends SceneTree
## Headless checks for RollContext, TextExpander and Formatter.
## Run: godot --headless --path . -s res://tests/test_text.gd
const TABLES := {
"names": "Names",
"gems": "[b]Gems[/b]",
"towns": "Towns",
"loop": "Loop",
"bold": "Bold",
}
## Each stub table returns its results in order, cycling.
const RESULTS := {
"names": ["Alice", "Bob", "Cora"],
"gems": ["Ruby", "Opal", "Jade", "Onyx"],
"towns": ["Riverton", "Hilltop"],
"bold": ["[b]heavy"],
}
var _failures := 0
var _ctx: RollContext
var _rolls: Dictionary = {}
func _init() -> void:
_test_expander()
_test_formatter()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _new_ctx(persistent: Dictionary = {}) -> RollContext:
var rng := RandomNumberGenerator.new()
rng.seed = 7
_ctx = RollContext.new(persistent, rng)
_ctx.resolve_table = _resolve
_ctx.roll_table = _roll
_rolls = {}
return _ctx
func _resolve(name_or_id: String) -> String:
if TABLES.has(name_or_id):
return name_or_id
var want := RollContext.normalize_name(name_or_id)
for id: String in TABLES:
if RollContext.normalize_name(TABLES[id]) == want:
return id
return ""
func _roll(table_id: String, depth: int) -> Dictionary:
if not TABLES.has(table_id):
return {}
var k: int = int(_rolls.get(table_id, 0))
_rolls[table_id] = k + 1
if table_id == "loop":
_ctx.depth = depth + 1
var r := TextExpander.expand("again [[Loop]]", _ctx)
return {"summary": r["text"], "children": r["children"], "depth": depth}
var list: Array = RESULTS[table_id]
return {"summary": list[k % list.size()], "table": table_id, "depth": depth}
func _x(text: String, ctx: RollContext) -> String:
return TextExpander.expand(text, ctx)["text"]
func _test_expander() -> void:
var ctx := _new_ctx()
# Plain reference, by name, case-insensitive, BBCode in the table name ignored.
var r := TextExpander.expand("A [[gems]] ring", ctx)
_eq(r["text"], "A [url=table:gems]Ruby[/url] ring", "reference by name")
_check((r["children"] as Array).size() == 1, "reference adds one child")
_eq(_x("[[Names]]", ctx), "[url=table:names]Alice[/url]", "reference by name, plain")
# Left to right: a chain var used before it's saved is unset, after it's set.
ctx = _new_ctx()
_eq(_x("{hero} [[Names -> hero]] {hero}", ctx),
"[url=unset:hero]{hero?}[/url] [url=table:names]Alice[/url] [url=var:hero]Alice[/url]",
"left to right ordering")
_eq(ctx.lookup("hero"), "Alice", "chain var saved")
_check(ctx.lookup("nobody") == null, "unset lookup is null")
r = TextExpander.expand("[[Names]] then [[Gems]] then [[Names]]", ctx)
var kids: Array = r["children"]
_check(kids.size() == 3 and kids[0]["summary"] == "Bob" and kids[1]["summary"] == "Ruby" and kids[2]["summary"] == "Cora",
"children in text order")
# Chain vs persistent scope.
var store := {}
ctx = _new_ctx(store)
_x("[[Towns -> @town]] [[Names -> hero]]", ctx)
_check(store.has("town") and store["town"]["value"] == "Riverton" and store["town"]["source"] == "towns",
"persistent var saved into the caller's dictionary: %s" % store)
_check(not store.has("hero") and ctx.chain_vars.has("hero"), "chain var stays in the chain")
_check(ctx.persistent_changed, "persistent_changed set")
ctx = _new_ctx(store)
_eq(_x("{hero} in {@town}", ctx), "[url=unset:hero]{hero?}[/url] in [url=var:@town]Riverton[/url]",
"new roll: chain var gone, persistent kept")
_check(not ctx.persistent_changed, "reading doesn't set persistent_changed")
# {@var|Table}: existing value is reused without rolling.
_eq(_x("{@town|Towns}", ctx), "[url=var:@town]Riverton[/url]", "{@var|Table} uses the saved value")
_check(not _rolls.has("towns"), "{@var|Table} didn't reroll")
ctx = _new_ctx({})
r = TextExpander.expand("{@town|Towns}, again {@town|Towns}", ctx)
_eq(r["text"], "[url=var:@town]Riverton[/url], again [url=var:@town]Riverton[/url]", "{@var|Table} rolls once when unset")
_check(int(_rolls.get("towns", 0)) == 1 and (r["children"] as Array).size() == 1, "{@var|Table} rolled exactly once")
_eq(ctx.lookup("@town"), "Riverton", "{@var|Table} saved")
_eq(_x("{@port|Nowhere}", ctx), "[url=missing:Nowhere]⚠ Nowhere[/url]", "{@var|Missing} shows missing marker")
_check(ctx.lookup("@port") == null, "{@var|Missing} saves nothing")
# Count forms.
ctx = _new_ctx()
r = TextExpander.expand("[[3x Gems]]", ctx)
_eq(r["text"], "[url=table:gems]Ruby[/url], [url=table:gems]Opal[/url], [url=table:gems]Jade[/url]", "3x")
_check((r["children"] as Array).size() == 3, "3x adds three children")
ctx = _new_ctx()
_x("[[2 x Gems -> loot]]", ctx)
_eq(ctx.lookup("loot"), "Ruby, Opal", "Nx with save joins the values")
for s in 20:
ctx = _new_ctx()
ctx.rng.seed = s
r = TextExpander.expand("[[1d4 Gems]]", ctx)
var c: int = (r["children"] as Array).size()
_check(c >= 1 and c <= 4, "1d4 rolls 1–4 times (got %d)" % c)
_check((r["text"] as String).count("[url=table:gems]") == c, "1d4 inserts one piece per roll")
ctx = _new_ctx()
_check(TextExpander.roll_dice("2d6+3", ctx.rng) >= 5 and TextExpander.roll_dice("2d6+3", ctx.rng) <= 15, "NdM+K in range")
_check(TextExpander.roll_dice("d1-1", ctx.rng) == 0, "dM-K")
_check(TextExpander.roll_dice("banana", ctx.rng) == -1, "bad dice expression")
_eq(TextExpander.expand("[[0x Gems]]", ctx)["text"], "", "0x inserts nothing")
# Missing tables, unset vars, depth.
ctx = _new_ctx()
r = TextExpander.expand("A [[Dragons]] and [[2x Dragons]].", ctx)
_eq(r["text"], "A [url=missing:Dragons]⚠ Dragons[/url] and [url=missing:Dragons]⚠ Dragons[/url].", "missing table marker")
_check((r["children"] as Array).is_empty(), "missing table adds no children")
_eq(_x("{@nope}", ctx), "[url=unset:@nope]{@nope?}[/url]", "unset persistent marker")
ctx = _new_ctx()
ctx.max_depth = 5
var deep := _x("[[Loop]]", ctx)
_check(deep.contains(TextExpander.deep_marker("loop")), "depth marker present")
_eq(int(_rolls.get("loop", 0)), 6, "loop rolled depths 0..5 then stopped")
_eq(deep.count("again"), 6, "six levels of text")
_eq(ctx.depth, 0, "depth restored after expansion")
ctx = _new_ctx()
ctx.depth = 40
_eq(_x("[[Names]]", ctx), "[url=deep:names]⚠ chain too deep[/url]", "default max depth 32")
# Brackets and BBCode.
ctx = _new_ctx()
_eq(_x("[x] marks [optional] spot", ctx), "[x] marks [optional] spot", "ordinary brackets untouched")
_eq(_x("[b][[Names]][/b] [i]{hero}[/i]", ctx), "[b][url=table:names]Alice[/url][/b] [i][url=unset:hero]{hero?}[/url][/i]",
"BBCode around references")
_eq(_x("[color=red][[Gems]][/color]", ctx), "[color=red][url=table:gems]Ruby[/url][/color]", "reference inside color")
_eq(_x("[url={\"a\":1}]x[/url]", ctx), "[url={\"a\":1}]x[/url]", "braces in a tag parameter aren't variables")
_eq(_x("[[b]x[/b]] and [lb][lb]Names]]", ctx), "[[b]x[/b]] and [lb][lb]Names]]", "not references")
_eq(_x("{not a var} {} {1x}", ctx), "{not a var} {} {1x}", "braces that aren't variables")
_eq(_x("A [[Bold]] thing", ctx), "A [url=table:bold][b]heavy[/b][/url] thing", "child's open tag closed inside its piece")
_eq(_x("[i]left open [[Names]]", ctx), "[i]left open [url=table:names]Bob[/url][/i]", "entry's open tag closed at end")
# references()
_new_ctx()
var refs := TextExpander.references("[[Names -> hero]] [[3x Gems]] {@town|Towns} [[1d4+1 Coins]] [x] [b]y[/b] [[Names]] {hero}")
_check(refs == (["Names", "Gems", "Towns", "Coins"] as Array[String]), "references: %s" % [refs])
var tricky := TextExpander.references("[[3x Gems]]", func(n: String) -> String: return "t" if n == "3x Gems" else "")
_check(tricky == (["3x Gems"] as Array[String]), "references keeps a whole name that resolves: %s" % [tricky])
_check(_rolls.is_empty(), "references doesn't roll")
func _test_formatter() -> void:
# close_open_tags
_eq(Formatter.close_open_tags("[b]bold"), "[b]bold[/b]", "close one")
_eq(Formatter.close_open_tags("[b][i]x"), "[b][i]x[/i][/b]", "close nested in order")
_eq(Formatter.close_open_tags("[b][i]x[/b] y"), "[b][i]x[/i][/b] y", "mismatched close fixes inner")
_eq(Formatter.close_open_tags("x[/b] y"), "x[lb]/b] y", "stray close escaped")
_eq(Formatter.close_open_tags("[color=#ff0000]r[font_size=20]big"), "[color=#ff0000]r[font_size=20]big[/font_size][/color]", "params")
_eq(Formatter.close_open_tags("[x] [lb] [b]ok[/b]"), "[x] [lb] [b]ok[/b]", "balanced and unknown untouched")
_eq(Formatter.close_open_tags("[ul bullet=*]\na\nb"), "[ul bullet=*]\na\nb[/ul]", "list closed")
# strip_tags
_eq(Formatter.strip_tags("[b]Bold[/b] [color=red]red[/color] [x] [lb]b]"), "Bold red [x] [b]", "strip basic")
_eq(Formatter.strip_tags("[url=table:gems]Ruby[/url] and [url=missing:Dragons]⚠ Dragons[/url] for [url=unset:hero]{hero?}[/url]"),
"Ruby and ⚠ Dragons (missing table) for {hero?}", "strip markers")
_eq(Formatter.strip_tags("a[img]res://icon.svg[/img]b[br]c[char=41]"), "ab\ncA", "strip img, br, char")
_eq(Formatter.strip_tags("[url={\"a\":1}]link[/url]"), "link", "strip JSON url")
# to_export_bbcode
_eq(Formatter.to_export_bbcode("[b][url=table:gems]Ruby[/url][/b] [url=var:@town]Hilltop[/url] [url=https://x.org]site[/url]"),
"[b]Ruby[/b] Hilltop [url=https://x.org]site[/url]", "export drops only internal urls")
_eq(Formatter.to_export_bbcode("[url=table:a]x [url=table:b]y[/url] z[/url]"), "x y z", "export nested internal urls")
# sanitize_import
_eq(Formatter.sanitize_import("[img]/etc/passwd[/img]hi [url=file:///x]there[/url]"), "hi there", "import strips img and url")
_eq(Formatter.sanitize_import("[img=10x10]a.png[/img][font=res://f.ttf]t[/font]"), "t", "import strips img with param and font")
_eq(Formatter.sanitize_import("[b]b[/b] [color=red]r[/color] [color=#ff0000]h[/color] [font_size=20]s[/font_size] [x]"),
"[b]b[/b] [color=red]r[/color] [color=#ff0000]h[/color] [font_size=20]s[/font_size] [x]", "import keeps allowed tags")
_eq(Formatter.sanitize_import("[url=missing:Fake]⚠ Fake[/url]"), "⚠ Fake", "import can't forge markers")
_eq(Formatter.sanitize_import("[color=red onclick]x[/color][b]open"), "x[b]open[/b]", "bad params dropped, open closed")
_eq(Formatter.sanitize_import("[ul bullet=*]\na\n[/ul][lb]b]"), "[ul bullet=*]\na\n[/ul][lb]b]", "import keeps lists and lb")
# escape_literal
_eq(Formatter.escape_literal("[b]x[/b]"), "[lb]b]x[lb]/b]", "escape tags")
_eq(Formatter.strip_tags(Formatter.escape_literal("[b]x[/b] [[Gems]]")), "[b]x[/b] [[Gems]]", "escaped text strips back")
_eq(TextExpander.expand(Formatter.escape_literal("[[Gems]]"), _new_ctx())["text"], "[lb][lb]Gems]]", "escaped reference not expanded")
_eq(RollContext.normalize_name(" [b]Gems[/b] "), "gems", "normalize_name")
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(got == want, "%s\n got: %s\n want: %s" % [what, got, want])
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

1
tests/test_text.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bepb7t5s0bsdc

22
tools/test_window.sh Executable file
View file

@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Runs TableTower in a window for automated checks (screenshots, smoke tests).
#
# While it runs, a temporary override.cfg renames the project to "TableTower Test",
# so its window class is "TableTower Test". A KWin window rule keeps windows of
# that class in the background without focus. The file is removed on exit, so
# normal runs from the editor are unaffected.
#
# Usage: tools/test_window.sh [project dir] -- [user args, e.g. --screenshot=/tmp/x.png]
set -euo pipefail
GODOT="${GODOT:-$HOME/apps/Godot_v4.7.2-stable_linux.x86_64}"
PROJECT="$(pwd)"
if [[ $# -gt 0 && "$1" != "--" ]]; then PROJECT="$(cd "$1" && pwd)"; shift; fi
[[ "${1:-}" == "--" ]] && shift
OVERRIDE="$PROJECT/override.cfg"
if [[ -e "$OVERRIDE" ]]; then
echo "override.cfg already exists in $PROJECT; is another test window running?" >&2
exit 1
fi
printf '[application]\n\nconfig/name="TableTower Test"\n' > "$OVERRIDE"
trap 'rm -f "$OVERRIDE"' EXIT
"$GODOT" --path "$PROJECT" -- "$@"

154
ui/board_view.gd Normal file
View file

@ -0,0 +1,154 @@
class_name BoardView
extends Control
## The felt board. Holds a scaled "world" with three layers: pipes behind the
## cards, the cards, and the ports (pipe ends) on top. Drag the felt to pan,
## Ctrl+wheel or pinch to zoom.
const MIN_ZOOM := 0.35
const MAX_ZOOM := 1.5
const WORLD_SIZE := 40000.0
var main: Main
var world: Control
var pipes: PipeLayer
var cards: CardLayer
var ports: PortLayer
var zoom: float = 1.0
var _panning := false
var _glow: GradientTexture2D
var _dots: ImageTexture
func setup(p_main: Main) -> void:
main = p_main
clip_contents = true
mouse_filter = MOUSE_FILTER_STOP
size_flags_vertical = SIZE_EXPAND_FILL
texture_repeat = CanvasItem.TEXTURE_REPEAT_ENABLED
world = Control.new()
world.mouse_filter = MOUSE_FILTER_IGNORE
add_child(world)
pipes = PipeLayer.new()
pipes.main = main
world.add_child(pipes)
cards = CardLayer.new()
world.add_child(cards)
ports = PortLayer.new()
ports.main = main
world.add_child(ports)
var img := Image.create(6, 6, false, Image.FORMAT_RGBA8)
img.fill(Color(0, 0, 0, 0))
img.set_pixel(1, 1, Color(1, 1, 1, 0.06))
_dots = ImageTexture.create_from_image(img)
var g := Gradient.new()
g.set_color(0, Color(1, 1, 1, 0.06))
g.set_color(1, Color(1, 1, 1, 0))
_glow = GradientTexture2D.new()
_glow.gradient = g
_glow.fill = GradientTexture2D.FILL_RADIAL
_glow.fill_from = Vector2(0.35, 0.3)
_glow.fill_to = Vector2(0.8, 0.3)
_glow.width = 256
_glow.height = 256
resized.connect(queue_redraw)
func _draw() -> void:
var r := Rect2(Vector2.ZERO, size)
draw_rect(r, Style.FELT)
draw_texture_rect(_glow, r, false)
draw_texture_rect(_dots, r, true)
func world_mouse() -> Vector2:
return world.get_local_mouse_position()
func screen_to_world(p: Vector2) -> Vector2:
return (p - world.position) / zoom
func set_zoom(z: float, around: Vector2 = Vector2(-1, -1)) -> void:
if around.x < 0.0:
around = size / 2.0
var anchor := screen_to_world(around)
zoom = clampf(snappedf(z, 0.01), MIN_ZOOM, MAX_ZOOM)
world.scale = Vector2(zoom, zoom)
world.position = around - anchor * zoom
## Zooms to show every table, centred horizontally.
func fit() -> void:
var first := true
var bounds := Rect2()
for c in cards.get_children():
var card := c as Control
var r := Rect2(card.position, card.size)
bounds = r if first else bounds.merge(r)
first = false
if first:
return
bounds = bounds.grow(20.0)
zoom = clampf(minf(1.0, minf((size.x - 16.0) / bounds.size.x, (size.y - 16.0) / bounds.size.y)), MIN_ZOOM, MAX_ZOOM)
world.scale = Vector2(zoom, zoom)
world.position = Vector2(maxf(8.0, (size.x - bounds.size.x * zoom) / 2.0), 8.0) - bounds.position * zoom
func _gui_input(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb:
match mb.button_index:
MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MIDDLE:
if mb.pressed:
if mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD:
var key := pipes.pipe_at(world_mouse(), 11.0)
if key != "":
main.open_pipe_options(key, mb.global_position)
accept_event()
return
_panning = true
mouse_default_cursor_shape = CURSOR_DRAG
else:
_panning = false
mouse_default_cursor_shape = CURSOR_ARROW
accept_event()
MOUSE_BUTTON_WHEEL_UP, MOUSE_BUTTON_WHEEL_DOWN:
if mb.pressed:
var up := mb.button_index == MOUSE_BUTTON_WHEEL_UP
if mb.ctrl_pressed:
set_zoom(zoom * (1.1 if up else 1.0 / 1.1), mb.position)
elif mb.shift_pressed:
world.position.x += 60.0 if up else -60.0
else:
world.position.y += 60.0 if up else -60.0
accept_event()
MOUSE_BUTTON_WHEEL_LEFT, MOUSE_BUTTON_WHEEL_RIGHT:
if mb.pressed:
world.position.x += 60.0 if mb.button_index == MOUSE_BUTTON_WHEEL_LEFT else -60.0
accept_event()
return
var mm := ev as InputEventMouseMotion
if mm:
if _panning:
world.position += mm.relative
elif main.mode == Main.Mode.BUILD:
pipes.hover_key = pipes.pipe_at(world_mouse(), 11.0)
mouse_default_cursor_shape = CURSOR_POINTING_HAND if pipes.hover_key != "" else CURSOR_ARROW
return
var pan := ev as InputEventPanGesture
if pan:
world.position -= pan.delta * 16.0
accept_event()
return
var mag := ev as InputEventMagnifyGesture
if mag:
set_zoom(zoom * mag.factor, mag.position)
accept_event()
func _notification(what: int) -> void:
if what == NOTIFICATION_MOUSE_EXIT and pipes:
pipes.hover_key = ""

1
ui/board_view.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dpaqwq3fuc00

23
ui/card_layer.gd Normal file
View file

@ -0,0 +1,23 @@
class_name CardLayer
extends Control
## Holds the table cards and paints their hard drop shadow underneath them.
var _shadow: StyleBoxFlat
func _init() -> void:
mouse_filter = MOUSE_FILTER_IGNORE
# Controls only draw inside their own rect, so cover the whole world.
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
_shadow = Style.box(Color(0, 0, 0, 0.22), 10)
func _process(_delta: float) -> void:
queue_redraw()
func _draw() -> void:
for c in get_children():
var card := c as Control
if card and card.visible:
draw_style_box(_shadow, Rect2(card.position + Vector2(0, 5), card.size))

1
ui/card_layer.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b1tlofrm8dg8a

29
ui/chevron_button.gd Normal file
View file

@ -0,0 +1,29 @@
class_name ChevronButton
extends Button
## Collapse/expand toggle: a chevron pointing down when open, right when collapsed.
var open: bool = true:
set(value):
open = value
queue_redraw()
func _init() -> void:
custom_minimum_size = Vector2(26, 26)
flat = false
focus_mode = FOCUS_ALL
var normal := Style.box(Color(0, 0, 0, 0), 6)
var hover := Style.box(Color("#e6dfcd"), 6)
Style.skin_button(self, normal, hover, hover, Style.MUTED)
mouse_entered.connect(queue_redraw)
mouse_exited.connect(queue_redraw)
func _draw() -> void:
var c := size / 2.0
var pts: PackedVector2Array
if open:
pts = PackedVector2Array([c + Vector2(-4, -2), c + Vector2(0, 2), c + Vector2(4, -2)])
else:
pts = PackedVector2Array([c + Vector2(-2, -4), c + Vector2(2, 0), c + Vector2(-2, 4)])
draw_polyline(pts, Style.INK if is_hovered() else Style.MUTED, 2.0, true)

1
ui/chevron_button.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://gmcbyiw30505

122
ui/collection_switcher.gd Normal file
View file

@ -0,0 +1,122 @@
class_name CollectionSwitcher
extends MenuButton
## Top-bar dropdown that names the current collection and offers switching,
## New, Rename, Duplicate and Delete. The storage rules are static functions
## (create_collection and friends) so tests can run them on a temporary
## LibraryStore; Main does the UI side (rebuilding cards, dialogs).
const ID_NEW := 1000
const ID_RENAME := 1001
const ID_DUPLICATE := 1002
const ID_DELETE := 1003
const MAX_LABEL := 22
var main: Main
var _ids: Array[String] = []
func setup(p_main: Main) -> void:
main = p_main
var ref := ModalCard.bar_menu_button("")
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
add_theme_color_override(c, ref.get_theme_color(c))
add_theme_color_override("font_disabled_color", Style.ON_FELT)
add_theme_font_override("font", Style.body_bold())
add_theme_font_size_override("font_size", 15)
ref.free()
mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
flat = false
tooltip_text = "Collections"
ModalCard.style_popup(get_popup())
get_popup().about_to_popup.connect(_fill)
get_popup().id_pressed.connect(_on_id)
refresh()
func refresh() -> void:
var n := main.data.name if main.data.name != "" else "Untitled"
text = "%s ▾" % (n if n.length() <= MAX_LABEL else n.substr(0, MAX_LABEL - 1) + "…")
tooltip_text = "Collection: %s" % n
func _fill() -> void:
var pm := get_popup()
pm.clear()
_ids.clear()
var can := main.collections_enabled()
if can:
for entry in main.library.list():
var id := str(entry["id"])
var current := id == main.data.id
pm.add_item(("● " if current else " ") + str(entry["name"]), _ids.size())
_ids.append(id)
else:
pm.add_item("● " + main.data.name, 0)
pm.set_item_disabled(0, true)
_ids.append(main.data.id)
pm.add_separator()
pm.add_item("New collection…", ID_NEW)
pm.add_item("Rename…", ID_RENAME)
pm.add_item("Duplicate", ID_DUPLICATE)
pm.add_item("Delete…", ID_DELETE)
if not can:
for id in [ID_NEW, ID_RENAME, ID_DUPLICATE, ID_DELETE]:
pm.set_item_disabled(pm.get_item_index(id), true)
pm.add_separator()
pm.add_item("Saving is off in this session", -1)
pm.set_item_disabled(pm.item_count - 1, true)
func _on_id(id: int) -> void:
match id:
ID_NEW: main.new_collection()
ID_RENAME: main.rename_collection()
ID_DUPLICATE: main.duplicate_collection()
ID_DELETE: main.delete_collection()
_:
if id >= 0 and id < _ids.size() and _ids[id] != main.data.id:
main.switch_collection(_ids[id])
# ---------- Storage rules (no UI) ----------
## Saves `current`, then makes and returns a new empty collection.
static func create_collection(library: LibraryStore, current: TowerBoard, coll_name: String) -> TowerBoard:
if current:
library.save(current)
return library.create(coll_name)
## Saves `current`, then loads another collection. Null if it can't be loaded.
static func switch_collection(library: LibraryStore, current: TowerBoard, id: String) -> TowerBoard:
if current:
library.save(current)
return library.load_collection(id)
## Renames `current` in memory and on disk. False for a blank name.
static func rename_collection(library: LibraryStore, current: TowerBoard, new_name: String) -> bool:
if new_name.strip_edges() == "":
return false
current.name = new_name.strip_edges()
return library.save(current)
## Saves `current` and returns its copy (new id, no local state), or null.
static func duplicate_collection(library: LibraryStore, current: TowerBoard, new_name: String = "") -> TowerBoard:
library.save(current)
return library.duplicate(current.id, new_name)
## Deletes `current` with its local state. Returns the collection to show next:
## the first remaining one, or a fresh empty one if it was the last.
static func delete_collection(library: LibraryStore, current: TowerBoard) -> TowerBoard:
if not library.delete(current.id):
return null
for entry in library.list():
var b := library.load_collection(str(entry["id"]))
if b:
return b
return library.create("Untitled")

View file

@ -0,0 +1 @@
uid://b08qeiv25l87s

217
ui/details_popup.gd Normal file
View file

@ -0,0 +1,217 @@
class_name DetailsPopup
extends PanelContainer
## The hover pop-up for table and entry details, result chips and the
## [[references]] / {variables} inside rendered text.
##
## It ignores the mouse, so it never blocks clicks, stays inside the window,
## and hides itself as soon as the control that opened it is no longer hovered.
const WIDTH := 300.0
const DELAY := 0.28
const OFFSET := Vector2(14, 20)
var main: Main
var _owner_ctrl: Control
var _title: Label
var _sub: Label
var _body: RichTextLabel
var _wait := 0.0
var _pending := false
func setup(p_main: Main) -> void:
main = p_main
mouse_filter = MOUSE_FILTER_IGNORE
z_index = 100
top_level = true
var sb := Style.box(Style.CARD, 9, [13, 10, 13, 11])
sb.border_width_top = 3
sb.border_color = Style.COPPER
sb.shadow_color = Color(0, 0, 0, 0.35)
sb.shadow_size = 14
sb.shadow_offset = Vector2(0, 6)
add_theme_stylebox_override("panel", sb)
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 3)
v.mouse_filter = MOUSE_FILTER_IGNORE
add_child(v)
_title = Style.make_label("", Style.display(), 18, Style.INK)
_title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_title.custom_minimum_size = Vector2(WIDTH, 0)
_title.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_title)
_sub = Style.make_label("", Style.body(), 12, Style.MUTED)
_sub.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_sub)
_body = RichText.label("", 14, Style.INK, false)
_body.custom_minimum_size = Vector2(WIDTH, 0)
_body.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_body)
hide()
## Shows the pop-up for `owner` after a short delay. Empty parts are hidden.
func show_for(owner: Control, title: String, body: String, sub: String = "") -> void:
if owner == null:
return
if not owner.has_meta("_details_hooked"):
owner.set_meta("_details_hooked", true)
owner.mouse_exited.connect(_on_owner_exited.bind(owner))
_owner_ctrl = owner
_title.text = title
_title.visible = title != ""
_sub.text = sub
_sub.visible = sub != ""
_body.text = body
_body.visible = body != ""
_wait = DELAY if not visible else 0.0
_pending = true
if visible:
_place()
## Hides the pop-up if `owner` opened it (or always, when owner is null).
func hide_for(owner: Control = null) -> void:
if owner == null or owner == _owner_ctrl:
_pending = false
_owner_ctrl = null
hide()
func _on_owner_exited(owner: Control) -> void:
hide_for(owner)
## Shows the prepared pop-up at a fixed spot until hide_for() (screenshots).
func pin(at: Vector2) -> void:
_owner_ctrl = null
_pending = false
show()
reset_size()
global_position = at
func _process(delta: float) -> void:
if _owner_ctrl == null:
return
# The owner may be rebuilt away (a card re-rendering) without a mouse_exited.
if not is_instance_valid(_owner_ctrl) or not _owner_ctrl.is_visible_in_tree():
hide_for()
return
if _pending:
_wait -= delta
if _wait <= 0.0:
_pending = false
show()
_place()
elif visible:
_place()
func _place() -> void:
reset_size()
var view := get_viewport_rect().size
var p := get_global_mouse_position() + OFFSET
if p.x + size.x > view.x - 8.0:
p.x = view.x - size.x - 8.0
if p.y + size.y > view.y - 8.0:
p.y = get_global_mouse_position().y - size.y - 12.0
global_position = Vector2(maxf(8.0, p.x), maxf(8.0, p.y))
# ---------- Content ----------
func show_table(owner: Control, tid: String, only_if_details: bool = false) -> void:
var t := main.data.get_table(tid) if main.data else null
if t == null:
return
if only_if_details and t.details.strip_edges() == "":
return
show_for(owner, Formatter.strip_tags(t.name), t.details, table_summary(t))
func show_entry(owner: Control, tid: String, eid: String) -> void:
var t := main.data.get_table(tid)
var e := t.find_entry(eid) if t else null
if e == null or e.details.strip_edges() == "":
return
var shown := main.lit_text(tid, eid)
if shown == "":
shown = RichText.preview(e.text, main.data)
show_for(owner, _short(Formatter.strip_tags(shown)), e.details, Formatter.strip_tags(t.name))
## Plain one-line title, cut down to a readable length.
static func _short(s: String) -> String:
s = s.strip_edges().replace("\n", " ")
while s.contains(" "):
s = s.replace(" ", " ")
return s if s.length() <= 90 else s.substr(0, 88).strip_edges() + "…"
## A result chip: the entry's details, else the table's.
func show_step(owner: Control, step: Dictionary) -> void:
var t := main.data.get_table(str(step.get("table_id", "")))
if t == null:
return
var e := t.find_entry(str(step.get("entry_id", "")))
var body := e.details if e and e.details.strip_edges() != "" else t.details
if body.strip_edges() == "":
return
var title := _short(Formatter.strip_tags(str(step.get("text", "")))) if e and e.details.strip_edges() != "" else Formatter.strip_tags(t.name)
show_for(owner, title, body, Formatter.strip_tags(t.name) if e and e.details.strip_edges() != "" else table_summary(t))
## True when a result chip has something to show.
func step_has_details(step: Dictionary) -> bool:
var t := main.data.get_table(str(step.get("table_id", "")))
if t == null:
return false
var e := t.find_entry(str(step.get("entry_id", "")))
return t.details.strip_edges() != "" or (e != null and e.details.strip_edges() != "")
## A [url] meta inside rendered text (see TextExpander's marker formats).
func show_meta(owner: Control, meta: String) -> void:
var kind := meta.get_slice(":", 0)
var arg := meta.substr(kind.length() + 1)
match kind:
"table":
show_table(owner, arg)
"var":
_show_var(owner, arg)
"missing":
show_for(owner, "Missing table", "There's no table called [b]%s[/b]. Check the spelling, or add a table with that name." % RichText.plain(arg))
"unset":
show_for(owner, "{%s} isn't set" % arg, "Nothing has saved this variable yet. Save it earlier in the roll with [lb][lb]Table -> %s]] or a pipe's [i]Save as[/i]." % RichText.plain(arg))
"deep":
show_for(owner, "Chain too deep", "The roll stopped after %d levels so a loop can't run forever." % Roller.MAX_DEPTH)
func _show_var(owner: Control, name: String) -> void:
var persistent := name.begins_with("@")
var value: Variant = null
var source := ""
if persistent:
var v: Variant = main.persistent_vars.get(name.substr(1))
if v is Dictionary:
value = str(v.get("value", ""))
source = str(v.get("source", ""))
else:
value = (main.current.get("chain_vars", {}) as Dictionary).get(name)
var sub := "Saved for this collection" if persistent else "Saved for this roll"
var st := main.data.get_table(source) if source != "" else null
if st:
sub += " · from %s" % Formatter.strip_tags(st.name)
var body := str(value) if value != null else "[i]Not set[/i]"
show_for(owner, "{%s}" % name, body, sub)
## "d100 · 6 ranges · 4 / 6 cards left"
func table_summary(t: RollTable) -> String:
var parts := PackedStringArray([t.dice_label()])
parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"])
if t.card_mode:
var left := main.cards_left(t.id)
parts.append("%d / %d cards left" % [left.x, left.y])
return " · ".join(parts)

1
ui/details_popup.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://btqlxvnbjdgt0

46
ui/die_icon.gd Normal file
View file

@ -0,0 +1,46 @@
class_name DieIcon
extends Control
## A three-pip die face. Tumbles while `spinning` is on.
var color: Color = Style.BRASS
var spinning: bool = false:
set(value):
spinning = value
if not value:
_angle = 0.0
set_process(value)
queue_redraw()
var _angle: float = 0.0
var _frame: StyleBoxFlat
func _init() -> void:
custom_minimum_size = Vector2(20, 20)
size = custom_minimum_size
mouse_filter = MOUSE_FILTER_IGNORE
_frame = StyleBoxFlat.new()
_frame.draw_center = false
_frame.set_border_width_all(2)
_frame.set_corner_radius_all(3)
_frame.anti_aliasing = true
set_process(false)
func _ready() -> void:
# Godot turns processing on for nodes with _process when they become ready.
set_process(spinning)
func _process(delta: float) -> void:
_angle = fmod(_angle + delta * TAU * 2.0, TAU)
queue_redraw()
func _draw() -> void:
draw_set_transform(size / 2.0, _angle)
_frame.border_color = color
draw_style_box(_frame, Rect2(-7.5, -7.5, 15, 15))
for p in [Vector2(-3, -3), Vector2(0, 0), Vector2(3, 3)]:
draw_circle(p, 1.45, color)
draw_set_transform(Vector2.ZERO)

1
ui/die_icon.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://d3cq3mih7ocns

20
ui/icons.gd Normal file
View file

@ -0,0 +1,20 @@
class_name Icons
extends RefCounted
## Small vector icons drawn with CanvasItem calls.
## The TableTower mark: a tower outline with a brass doorway. Drawn in a 22x26 box.
static func draw_tower(ci: CanvasItem, origin: Vector2, scale: float, color: Color, accent: Color) -> void:
var pts := PackedVector2Array([
Vector2(3, 25), Vector2(3, 8), Vector2(6, 6), Vector2(6, 2), Vector2(9, 2), Vector2(9, 5),
Vector2(13, 5), Vector2(13, 2), Vector2(16, 2), Vector2(16, 6), Vector2(19, 8), Vector2(19, 25), Vector2(3, 25),
])
for i in pts.size():
pts[i] = origin + pts[i] * scale
ci.draw_polyline(pts, color, 1.7 * scale, true)
var door := PackedVector2Array([origin + Vector2(7, 25) * scale, origin + Vector2(7, 19) * scale])
for k in range(17):
var a := PI + PI * k / 16.0
door.append(origin + (Vector2(11, 19) + Vector2(cos(a), sin(a)) * 4.0) * scale)
door.append(origin + Vector2(15, 25) * scale)
ci.draw_polyline(door, accent, 1.7 * scale, true)

1
ui/icons.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bny3o5yhddwbm

160
ui/io_menu.gd Normal file
View file

@ -0,0 +1,160 @@
class_name IoMenu
extends MenuButton
## The Build-mode "Board ▾" menu (reset, import, export) plus the import and
## export logic as static functions, so it can be tested without a window.
const ID_RESET := 1
const ID_IMPORT := 2
const ID_EXPORT := 100
## Export formats: label, file extension, FileDialog filter.
const EXPORTS := [
{"key": "json", "label": "TableTower JSON", "ext": "json", "filter": "*.json ; TableTower JSON"},
{"key": "canvas", "label": "JSON Canvas", "ext": "canvas", "filter": "*.canvas ; JSON Canvas"},
{"key": "mermaid", "label": "Mermaid diagram (.mmd)", "ext": "mmd", "filter": "*.mmd ; Mermaid"},
{"key": "mermaid_md", "label": "Mermaid in Markdown (.md)", "ext": "md", "filter": "*.md ; Markdown"},
{"key": "dot", "label": "Graphviz DOT", "ext": "dot", "filter": "*.dot, *.gv ; Graphviz DOT"},
{"key": "graphml", "label": "GraphML", "ext": "graphml", "filter": "*.graphml, *.xml ; GraphML"},
]
const IMPORT_FILTERS: Array[String] = [
"*.json, *.canvas, *.graphml, *.xml ; TableTower, JSON Canvas or GraphML",
"*.json ; TableTower JSON",
"*.canvas ; JSON Canvas",
"*.graphml, *.xml ; GraphML",
]
signal reset_requested
signal import_requested
signal export_requested(format: Dictionary)
func setup(can_reset: bool, can_import: bool) -> void:
var ref := ModalCard.bar_menu_button("")
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
add_theme_color_override(c, ref.get_theme_color(c))
add_theme_font_size_override("font_size", 15)
ref.free()
mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
flat = false
text = "Board ▾"
tooltip_text = "Reset, import and export"
var pm := get_popup()
ModalCard.style_popup(pm)
pm.add_item("Reset sample", ID_RESET)
pm.add_separator("Import")
pm.add_item("Import as new collection…", ID_IMPORT)
pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import)
pm.add_separator("Export this collection")
for i in EXPORTS.size():
pm.add_item("Export as " + str(EXPORTS[i]["label"]) + "…", ID_EXPORT + i)
pm.id_pressed.connect(func(id: int) -> void:
if id == ID_RESET:
reset_requested.emit()
elif id == ID_IMPORT:
import_requested.emit()
elif id >= ID_EXPORT and id < ID_EXPORT + EXPORTS.size():
export_requested.emit(EXPORTS[id - ID_EXPORT])
)
# ---------- Export ----------
## Text for one export format. Works from the board's saved form only, so local
## state (decks, variables, history) can never end up in an export.
static func export_text(format_key: String, board: TowerBoard) -> String:
var c := board.to_dict()
match format_key:
"canvas": return CanvasIO.export_canvas(c)
"mermaid": return MermaidExporter.export_mermaid(c)
"mermaid_md": return "# %s\n\n```mermaid\n%s\n```\n" % [board.name, MermaidExporter.export_mermaid(c).strip_edges()]
"dot": return DotExporter.export_dot(c)
"graphml": return GraphMLIO.export_graphml(c)
_: return JsonIO.export_json(c)
static func default_file_name(board: TowerBoard, format: Dictionary) -> String:
return "%s.%s" % [LibraryStore.slugify(board.name), format["ext"]]
# ---------- Import ----------
## Guesses the format from the file name, then from the text.
static func detect_format(file_name: String, text: String) -> String:
match file_name.get_extension().to_lower():
"canvas": return "canvas"
"graphml", "xml": return "graphml"
"json": return "json"
var t := text.strip_edges()
if t.begins_with("<"):
return "graphml"
if t.begins_with("{") and t.contains("\"nodes\"") and not t.contains("\"tables\""):
return "canvas"
return "json"
## Parses text with the right importer. Same result shape as the importers:
## {ok, collection, errors, warnings, guesses}.
static func parse_import(text: String, format_key: String) -> Dictionary:
var sanitize: Callable = Formatter.sanitize_import
var r: Dictionary
match format_key:
"canvas": r = CanvasIO.import_canvas(text, sanitize)
"graphml": r = GraphMLIO.import_graphml(text, sanitize)
_: r = JsonIO.import_json(text, sanitize)
for k in ["errors", "warnings", "guesses"]:
if not r.has(k):
r[k] = []
return r
## Imports text as a NEW collection in the library: sanitized, converted with
## TowerBoard.load_dict and saved under a fresh id. Result: {ok, board, errors,
## warnings, guesses}; board is null on failure. Nothing existing is touched.
static func import_as_collection(library: LibraryStore, text: String, file_name: String) -> Dictionary:
var r := parse_import(text, detect_format(file_name, text))
var out := {"ok": false, "board": null, "errors": r["errors"], "warnings": r["warnings"], "guesses": r["guesses"]}
if not r["ok"]:
return out
var b := TowerBoard.new()
if not b.load_dict(r["collection"]):
(out["errors"] as Array).append("The file didn't contain any tables.")
return out
if b.name.strip_edges() == "":
b.name = file_name.get_file().get_basename()
if b.name.strip_edges() == "":
b.name = "Imported collection"
b.id = library.unique_id(LibraryStore.slugify(b.name))
if not library.save(b):
(out["errors"] as Array).append("Couldn't save the imported collection.")
return out
out["ok"] = true
out["board"] = b
return out
## Card-styled report of an import: errors, warnings and guesses.
static func report_dialog(title: String, result: Dictionary) -> ModalCard:
var d := ModalCard.new(title, 540.0)
var any := false
for spec in [["errors", "Problems", Style.WARN_INK], ["warnings", "Warnings", Style.COPPER_DARK],
["guesses", "Guesses made", Style.INK]]:
var items: Array = result.get(spec[0], [])
if items.is_empty():
continue
any = true
d.body.add_child(ModalCard.section("%s (%d)" % [spec[1], items.size()]))
for m in items:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 8)
var dot := Style.make_label("•", Style.body_bold(), 16, spec[2])
dot.size_flags_vertical = SIZE_SHRINK_BEGIN
row.add_child(dot)
row.add_child(ModalCard.note(str(m), Style.INK))
d.body.add_child(row)
if not any:
d.body.add_child(ModalCard.note("Nothing to report."))
d.add_button("Done", "primary", d.close)
return d

1
ui/io_menu.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://scc3qijhaa05

1240
ui/main.gd Normal file

File diff suppressed because it is too large Load diff

1
ui/main.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b8w14kan84qjw

12
ui/main.tscn Normal file
View file

@ -0,0 +1,12 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://ui/main.gd" id="1_main"]
[node name="Main" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_main")

276
ui/modal_card.gd Normal file
View file

@ -0,0 +1,276 @@
class_name ModalCard
extends Control
## A card-styled modal dialog: dimmed backdrop, a paper-coloured card with a
## Rokkitt title, a scrolling body and a right-aligned footer of buttons.
## Add it to the app with `host.add_child(dialog)`; it frees itself on close().
signal closed
var card: PanelContainer
var body: VBoxContainer
var footer: HBoxContainer
var title_label: Label
var close_on_backdrop := true
var _scroll: ScrollContainer
var _width := 520.0
func _init(title: String = "", width: float = 520.0) -> void:
_width = width
set_anchors_and_offsets_preset(PRESET_FULL_RECT)
mouse_filter = Control.MOUSE_FILTER_STOP
theme = make_theme()
var dim := ColorRect.new()
dim.color = Color(0, 0, 0, 0.55)
dim.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
dim.gui_input.connect(func(ev: InputEvent) -> void:
if close_on_backdrop and ev is InputEventMouseButton and ev.pressed:
close()
)
add_child(dim)
var center := CenterContainer.new()
center.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
center.mouse_filter = Control.MOUSE_FILTER_IGNORE
add_child(center)
card = PanelContainer.new()
var sb := Style.box(Style.CARD, 14, [26, 22, 26, 20])
sb.shadow_color = Color(0, 0, 0, 0.5)
sb.shadow_size = 28
sb.shadow_offset = Vector2(0, 12)
card.add_theme_stylebox_override("panel", sb)
card.custom_minimum_size.x = width
center.add_child(card)
var col := VBoxContainer.new()
col.add_theme_constant_override("separation", 14)
card.add_child(col)
title_label = Style.make_label(title, Style.display(), 28, Style.INK)
title_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
col.add_child(title_label)
_scroll = ScrollContainer.new()
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
_scroll.size_flags_vertical = SIZE_EXPAND_FILL
col.add_child(_scroll)
body = VBoxContainer.new()
body.add_theme_constant_override("separation", 12)
body.size_flags_horizontal = SIZE_EXPAND_FILL
_scroll.add_child(body)
footer = HBoxContainer.new()
footer.add_theme_constant_override("separation", 10)
footer.alignment = BoxContainer.ALIGNMENT_END
col.add_child(footer)
func _ready() -> void:
resized.connect(_fit)
_fit()
await get_tree().process_frame
_fit()
func _fit() -> void:
card.custom_minimum_size.x = minf(_width, maxf(240.0, size.x - 32.0))
var want := body.get_combined_minimum_size().y
_scroll.custom_minimum_size.y = clampf(minf(want, size.y - 190.0), 40.0, 4000.0)
func _input(event: InputEvent) -> void:
if event.is_action_pressed("ui_cancel") and is_inside_tree():
get_viewport().set_input_as_handled()
close()
func close() -> void:
closed.emit()
queue_free()
# ---------- Building blocks ----------
## kind: "primary" (felt), "plain" (outlined) or "danger".
func add_button(text: String, kind: String, on_press: Callable) -> Button:
var b := make_button(text, kind)
b.pressed.connect(on_press)
footer.add_child(b)
return b
static func make_button(text: String, kind: String = "plain") -> Button:
var b := Button.new()
b.text = text
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 16)
var m := [16, 7, 16, 7]
match kind:
"primary":
Style.skin_button(b, Style.box(Style.FELT, 8, m), Style.box(Style.FELT_HOVER, 8, m),
Style.box(Style.FELT_HOVER, 8, m), Style.BRASS)
"danger":
Style.skin_button(b, Style.box(Style.DANGER_INK, 8, m), Style.box(Style.DANGER_INK.lightened(0.12), 8, m),
Style.box(Style.DANGER_INK.lightened(0.12), 8, m), Color.WHITE)
_:
var n := Style.bordered(Style.box(Color(0, 0, 0, 0), 8, m), 1, Style.DASH)
var h := Style.bordered(Style.box(Style.HOVER_ROW, 8, m), 1, Style.DASH)
Style.skin_button(b, n, h, h, Style.INK)
b.add_theme_color_override("font_disabled_color", Style.MUTED)
return b
## Small caps heading above a group of fields.
static func section(text: String) -> Label:
var l := Style.make_label(text.to_upper(), Style.caps(), 12, Style.MUTED)
return l
static func note(text: String, color: Color = Style.MUTED) -> Label:
var l := Style.make_label(text, Style.body(), 14, color)
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.size_flags_horizontal = SIZE_EXPAND_FILL
return l
## A label above a control, as one block.
static func field(heading: String, control: Control) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 4)
v.add_child(section(heading))
v.add_child(control)
return v
## A segmented choice: options are strings; returns the row. `on_change` gets the index.
static func segmented(options: Array, selected: int, on_change: Callable) -> PanelContainer:
var seg := PanelContainer.new()
seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.07), 9, [3, 3, 3, 3]))
seg.size_flags_horizontal = SIZE_SHRINK_BEGIN
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 0)
seg.add_child(row)
var group := ButtonGroup.new()
for i in options.size():
var b := Button.new()
b.text = str(options[i])
b.toggle_mode = true
b.button_group = group
b.add_theme_font_override("font", Style.body_bold())
b.add_theme_font_size_override("font_size", 15)
var normal := Style.box(Color(0, 0, 0, 0), 7, [14, 5, 14, 5])
var hover := Style.box(Color(0, 0, 0, 0.06), 7, [14, 5, 14, 5])
var pressed := Style.box(Style.FELT, 7, [14, 5, 14, 5])
Style.skin_button(b, normal, hover, pressed, Style.MUTED, Style.INK, Style.BRASS)
b.set_pressed_no_signal(i == selected)
b.pressed.connect(on_change.bind(i))
row.add_child(b)
return seg
static func style_line_edit(le: LineEdit) -> void:
le.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.DASH))
le.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
le.add_theme_color_override("font_color", Style.INK)
le.add_theme_color_override("caret_color", Style.INK)
le.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
le.add_theme_color_override("font_placeholder_color", Style.MUTED)
le.add_theme_constant_override("minimum_character_width", 4)
le.size_flags_horizontal = SIZE_EXPAND_FILL
static func style_text_edit(te: TextEdit) -> void:
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 7, 10, 7]), 1, Style.DASH))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 7, 10, 7]), 1, Style.COPPER))
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("background_color", Color(0, 0, 0, 0))
## Styles a popup menu like a small card (used by the top-bar menus too).
static func style_popup(pm: PopupMenu) -> void:
pm.add_theme_stylebox_override("panel", Style.bordered(Style.box(Style.CARD, 10, [6, 6, 6, 6]), 1, Style.DASH))
pm.add_theme_stylebox_override("hover", Style.box(Style.HOVER_ROW, 6))
pm.add_theme_stylebox_override("separator", Style.box(Style.RULE, 0, [0, 0, 0, 0]))
pm.add_theme_color_override("font_color", Style.INK)
pm.add_theme_color_override("font_hover_color", Style.INK)
pm.add_theme_color_override("font_disabled_color", Style.MUTED)
pm.add_theme_color_override("font_separator_color", Style.MUTED)
pm.add_theme_font_override("font", Style.body())
pm.add_theme_font_size_override("font_size", 16)
pm.add_theme_constant_override("v_separation", 8)
pm.add_theme_constant_override("item_start_padding", 8)
pm.add_theme_constant_override("item_end_padding", 8)
## A top-bar styled MenuButton (same look as Style.bar_button).
static func bar_menu_button(text: String) -> MenuButton:
var mb := MenuButton.new()
mb.text = text
var ref := Style.bar_button(text)
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
mb.add_theme_color_override(c, ref.get_theme_color(c))
mb.add_theme_color_override("font_disabled_color", Style.ON_FELT_MUTED)
mb.add_theme_font_size_override("font_size", 15)
mb.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
mb.flat = false
style_popup(mb.get_popup())
ref.free()
return mb
static func make_theme() -> Theme:
var th := Style.card_theme()
th.set_color("default_color", "RichTextLabel", Style.INK)
th.set_font("normal_font", "RichTextLabel", Style.body())
th.set_font("bold_font", "RichTextLabel", Style.body_bold())
th.set_font("italics_font", "RichTextLabel", Style.body_italic())
th.set_font_size("normal_font_size", "RichTextLabel", 16)
th.set_font_size("bold_font_size", "RichTextLabel", 16)
th.set_font_size("italics_font_size", "RichTextLabel", 16)
th.set_color("font_color", "TooltipLabel", Style.INK)
th.set_stylebox("panel", "TooltipPanel", Style.box(Style.CARD, 6, [8, 5, 8, 5]))
return th
# ---------- Ready-made dialogs ----------
## Asks for one line of text; calls on_ok(text) with non-blank text.
static func ask_text(title: String, prompt: String, initial: String, ok_text: String, on_ok: Callable) -> ModalCard:
var d := ModalCard.new(title, 420.0)
var le := LineEdit.new()
le.text = initial
style_line_edit(le)
d.body.add_child(field(prompt, le))
var accept := func() -> void:
var t := le.text.strip_edges()
if t == "":
return
d.close()
on_ok.call(t)
le.text_submitted.connect(func(_t: String) -> void: accept.call())
d.add_button("Cancel", "plain", d.close)
d.add_button(ok_text, "primary", accept)
d.ready.connect(func() -> void:
le.grab_focus()
le.select_all()
)
return d
## A yes/no question; calls on_ok when confirmed. `danger` makes the button red.
static func confirm(title: String, message: String, ok_text: String, on_ok: Callable, danger: bool = false) -> ModalCard:
var d := ModalCard.new(title, 420.0)
d.body.add_child(note(message, Style.INK))
d.add_button("Cancel", "plain", d.close)
d.add_button(ok_text, "danger" if danger else "primary", func() -> void:
d.close()
on_ok.call()
)
return d

1
ui/modal_card.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ceo7ujpvqc4c

213
ui/pipe_layer.gd Normal file
View file

@ -0,0 +1,213 @@
class_name PipeLayer
extends Control
## Draws the copper pipes between cards, lit pipes in brass, and the glowing bead
## that travels down a pipe during a roll. Sits behind the cards.
##
## [[References]] in an entry's text draw as thinner dashed pipes. They come from
## the text, so they can't be clicked or removed here.
const SAMPLES := 40
var main: Main
var hover_key: String = ""
## The pipe whose options are open in Build mode.
var select_key: String = ""
var pulse_key: String = ""
var pulse_t: float = 0.0
## pipe key -> polyline in world coordinates, from the last frame.
var _paths: Dictionary = {}
var _label_box: StyleBoxFlat
func _init() -> void:
mouse_filter = MOUSE_FILTER_IGNORE
# Controls only draw inside their own rect, so cover the whole world.
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
_label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2])
Style.bordered(_label_box, 1, Style.COPPER_DARK)
func _process(_delta: float) -> void:
queue_redraw()
static func curve(a: Vector2, b: Vector2) -> PackedVector2Array:
var dx := maxf(70.0, absf(b.x - a.x) / 2.0)
var c1 := a + Vector2(dx, 0)
var c2 := b - Vector2(dx, 0)
var pts := PackedVector2Array()
for i in SAMPLES + 1:
pts.append(a.bezier_interpolate(c1, c2, b, float(i) / SAMPLES))
return pts
func _draw() -> void:
_paths.clear()
var lit_list: Array = []
var lit_refs: Array = []
var labels: Array = []
var build := main.mode == Main.Mode.BUILD
for t in main.data.tables:
var card := main.card_for(t.id)
if card == null:
continue
for e in t.entries:
var refs := main.ref_targets_for(e)
if e.pipes.is_empty() and refs.is_empty():
continue
var a := card.anchor_for(e.id)
if a.is_empty():
continue
for to in refs:
var target := main.card_for(to)
if target == null:
continue
var key := Roller.ref_key(t.id, e.id, to)
var pts := curve(a["pos"], target.inlet_point())
_paths[key] = pts
if main.lit_pipes.has(key):
lit_refs.append(pts)
else:
_draw_ref(pts, false)
for to in e.pipes:
var target := main.card_for(to)
if target == null:
continue
var key := Roller.pipe_key(t.id, e.id, to)
var pts := curve(a["pos"], target.inlet_point())
_paths[key] = pts
if main.lit_pipes.has(key):
lit_list.append(pts)
else:
_draw_pipe(pts, false, build and (key == hover_key or key == select_key))
var tag := _pipe_tag(e, to)
if tag != "":
labels.append([pts, tag])
# Lit pipes go on top so the path of the last roll reads clearly.
for pts in lit_refs:
_draw_ref(pts, true)
for pts in lit_list:
_draw_pipe(pts, true, false)
for l in labels:
_draw_tag(l[0], l[1])
if pulse_key != "" and _paths.has(pulse_key):
var p := point_along(_paths[pulse_key], pulse_t)
var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0
draw_circle(p, 13.0 * r, Color(Style.BRASS, 0.3))
draw_circle(p, 9.0 * r, Color(Style.BRASS, 0.5))
draw_circle(p, 7.0 * r, Style.PULSE)
## "×2 → foe" for a pipe with options, or "".
static func _pipe_tag(e: TableEntry, to: String) -> String:
var parts := PackedStringArray()
if e.count_for(to) > 1:
parts.append("×%d" % e.count_for(to))
if e.save_for(to) != "":
parts.append("→ " + e.save_for(to))
return " ".join(parts)
func _draw_tag(pts: PackedVector2Array, text: String) -> void:
var font := Style.body_bold(true)
var fs := 12
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var mid := point_along(pts, 0.5)
var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
draw_style_box(_label_box, r)
draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.COPPER_DARK)
func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:
if lit:
draw_polyline(pts, Color(Style.BRASS, 0.18), 20.0, true)
draw_polyline(pts, Style.BRASS_DARK if lit else Style.COPPER_DARK, 11.0, true)
var inner := Style.BRASS if lit else Style.COPPER
if hovered:
inner = Style.COPPER.lightened(0.35)
draw_polyline(pts, inner, 6.0, true)
draw_set_transform(Vector2(0, -1.5))
draw_polyline(pts, Color(1.0, 0.886, 0.745, 0.4), 1.5, true)
draw_set_transform(Vector2.ZERO)
## A reference pipe: thinner, in dashes.
func _draw_ref(pts: PackedVector2Array, lit: bool) -> void:
if lit:
draw_polyline(pts, Color(Style.BRASS, 0.14), 12.0, true)
var dashes := _dashes(pts, 12.0, 7.0)
for d in dashes:
draw_polyline(d, Style.BRASS_DARK if lit else Style.COPPER_DARK, 6.0, true)
for d in dashes:
draw_polyline(d, Style.BRASS if lit else Style.COPPER, 3.0, true)
## Splits a polyline into dashes `on` long with gaps `off` long.
static func _dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]:
var out: Array[PackedVector2Array] = []
var cur := PackedVector2Array()
var drawing := true
var left := on
for i in range(1, pts.size()):
var a := pts[i - 1]
var b := pts[i]
var seg := a.distance_to(b)
var pos := 0.0
if drawing and cur.is_empty():
cur.append(a)
while seg - pos > left:
pos += left
var p := a.lerp(b, pos / seg)
if drawing:
cur.append(p)
out.append(cur)
cur = PackedVector2Array()
else:
cur = PackedVector2Array([p])
drawing = not drawing
left = on if drawing else off
left -= seg - pos
if drawing:
cur.append(b)
if drawing and cur.size() > 1:
out.append(cur)
return out
func path_length(key: String) -> float:
if not _paths.has(key):
return 0.0
var pts: PackedVector2Array = _paths[key]
var total := 0.0
for i in range(1, pts.size()):
total += pts[i - 1].distance_to(pts[i])
return total
static func point_along(pts: PackedVector2Array, t: float) -> Vector2:
if pts.size() < 2:
return pts[0] if pts.size() == 1 else Vector2.ZERO
var total := 0.0
for i in range(1, pts.size()):
total += pts[i - 1].distance_to(pts[i])
var want := clampf(t, 0.0, 1.0) * total
for i in range(1, pts.size()):
var seg := pts[i - 1].distance_to(pts[i])
if want <= seg and seg > 0.0:
return pts[i - 1].lerp(pts[i], want / seg)
want -= seg
return pts[pts.size() - 1]
## The pipe under a world-space point, or "" if none is within `tolerance`.
## Reference pipes come from entry text, so they're never picked.
func pipe_at(p: Vector2, tolerance: float) -> String:
for key: String in _paths:
if Roller.is_ref_key(key):
continue
var pts: PackedVector2Array = _paths[key]
for i in range(1, pts.size()):
if Geometry2D.get_closest_point_to_segment(p, pts[i - 1], pts[i]).distance_to(p) <= tolerance:
return key
return ""

1
ui/pipe_layer.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b8evnm8lbgvlj

160
ui/pipe_popover.gd Normal file
View file

@ -0,0 +1,160 @@
class_name PipePopover
extends PopupPanel
## Build mode: the options for one pipe, opened by clicking it. How many times
## it rolls, the variable it saves its result as, and Remove.
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
var main: Main
var key: String = ""
var _entry: TableEntry
var _to: String = ""
var _title: RichTextLabel
var _count: LineEdit
var _save: LineEdit
var _save_ok: StyleBoxFlat
var _save_bad: StyleBoxFlat
var _re := RegEx.new()
func setup(p_main: Main) -> void:
main = p_main
_re.compile(SAVE_PATTERN)
theme = Style.card_theme()
var sb := Style.box(Style.CARD, 9, [14, 11, 14, 12])
sb.border_width_top = 3
sb.border_color = Style.COPPER
add_theme_stylebox_override("panel", sb)
popup_hide.connect(func() -> void:
_commit_save()
if main.board:
main.board.pipes.select_key = ""
)
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 9)
add_child(v)
_title = RichText.label("", 15, Style.INK, false)
_title.custom_minimum_size = Vector2(260, 0)
v.add_child(_title)
var field_ok := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.RULE)
var field_focus := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.COPPER)
_save_ok = field_ok
_save_bad = Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.DANGER)
var count_row := HBoxContainer.new()
count_row.add_theme_constant_override("separation", 6)
v.add_child(count_row)
var cl := Style.make_label("Rolls", Style.body(), 14, Style.MUTED)
cl.custom_minimum_size = Vector2(62, 0)
count_row.add_child(cl)
var minus := _small_button("−")
minus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) - 1 if _entry else 1))
count_row.add_child(minus)
_count = LineEdit.new()
_count.custom_minimum_size = Vector2(44, 0)
_count.alignment = HORIZONTAL_ALIGNMENT_CENTER
_count.max_length = 2
_count.add_theme_stylebox_override("normal", field_ok)
_count.add_theme_stylebox_override("focus", field_focus)
_count.text_submitted.connect(func(s: String) -> void: _set_count(s.to_int()))
_count.focus_exited.connect(func() -> void: _set_count(_count.text.to_int()))
count_row.add_child(_count)
var plus := _small_button("+")
plus.pressed.connect(func() -> void: _set_count(_entry.count_for(_to) + 1 if _entry else 1))
count_row.add_child(plus)
count_row.add_child(Style.make_label("times", Style.body(), 14, Style.MUTED))
var save_row := HBoxContainer.new()
save_row.add_theme_constant_override("separation", 6)
v.add_child(save_row)
var sl := Style.make_label("Save as", Style.body(), 14, Style.MUTED)
sl.custom_minimum_size = Vector2(62, 0)
save_row.add_child(sl)
_save = LineEdit.new()
_save.placeholder_text = "name, or @name to keep"
_save.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_save.add_theme_stylebox_override("normal", field_ok)
_save.add_theme_stylebox_override("focus", field_focus)
_save.text_changed.connect(func(s: String) -> void:
var ok := s.strip_edges() == "" or _re.search(s.strip_edges()) != null
_save.add_theme_stylebox_override("normal", _save_ok if ok else _save_bad)
_save.add_theme_stylebox_override("focus", field_focus if ok else _save_bad)
)
_save.text_submitted.connect(func(_s: String) -> void:
_commit_save()
hide()
)
save_row.add_child(_save)
var hint := Style.make_label("{name} lasts one roll; {@name} is kept.", Style.body(), 12, Style.MUTED)
v.add_child(hint)
var remove := Button.new()
remove.text = "Remove pipe"
remove.add_theme_font_size_override("font_size", 14)
var rn := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, Style.DASH)
var rh := Style.bordered(Style.box(Style.WARN_BG, 6, [10, 4, 10, 4]), 1, Style.DANGER_INK)
Style.skin_button(remove, rn, rh, rh, Style.DANGER_INK)
remove.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
remove.pressed.connect(func() -> void:
var k := key
_entry = null
hide()
main.remove_pipe(k)
)
v.add_child(remove)
func _small_button(text: String) -> Button:
var b := Button.new()
b.text = text
b.custom_minimum_size = Vector2(26, 26)
b.add_theme_font_size_override("font_size", 16)
var n := Style.bordered(Style.box(Color(0, 0, 0, 0), 5), 1, Style.RULE)
var h := Style.bordered(Style.box(Style.HOVER_ROW, 5), 1, Style.DASH)
Style.skin_button(b, n, h, h, Style.INK)
return b
## Opens for the pipe `pipe_key` near `at` (window coordinates).
func open(pipe_key: String, at: Vector2) -> void:
var from := pipe_key.get_slice(">", 0)
var t := main.data.get_table(from.get_slice(":", 0))
_to = pipe_key.get_slice(">", 1)
_entry = t.find_entry(from.get_slice(":", 1)) if t else null
if _entry == null:
return
key = pipe_key
var target := main.data.get_table(_to)
_title.text = "%s [color=#%s]→[/color] [b]%s[/b]" % [RichText.preview(_entry.text, main.data), Style.COPPER.to_html(false), RichText.plain(Formatter.strip_tags(target.name)) if target else _to]
_count.text = str(_entry.count_for(_to))
_save.text = _entry.save_for(_to)
_save.add_theme_stylebox_override("normal", _save_ok)
main.board.pipes.select_key = pipe_key
reset_size()
var view := main.get_viewport_rect().size
var sz := get_contents_minimum_size()
var p := at + Vector2(12, 12)
p.x = clampf(p.x, 8.0, view.x - sz.x - 36.0)
p.y = clampf(p.y, 8.0, view.y - sz.y - 36.0)
popup(Rect2i(Vector2i(p), Vector2i.ZERO))
func _set_count(n: int) -> void:
if _entry == null:
return
_entry.set_pipe_count(_to, n)
_count.text = str(_entry.count_for(_to))
main.mark_dirty()
func _commit_save() -> void:
if _entry == null:
return
var s := _save.text.strip_edges()
if s != "" and _re.search(s) == null:
return
if s != _entry.save_for(_to):
_entry.set_pipe_save(_to, s)
main.mark_dirty()

1
ui/pipe_popover.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://daomwkc7dercc

117
ui/port_layer.gd Normal file
View file

@ -0,0 +1,117 @@
class_name PortLayer
extends Control
## Draws pipe ends on top of the cards: an inlet on each card and an outlet on
## each result. In Build mode, dragging from an outlet lays a new pipe.
## Only the ports themselves take mouse input; everything else passes through.
const GRAB_RADIUS := 10.0
var main: Main
var _grab: Array = [] # [{pos, tid, eid}] outlets that can start a pipe
var _linking := false
var _ghost_from := Vector2.ZERO
var _ghost_to := Vector2.ZERO
func _init() -> void:
mouse_filter = MOUSE_FILTER_STOP
mouse_default_cursor_shape = CURSOR_CROSS
# Controls only draw inside their own rect, so cover the whole world.
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
func _process(_delta: float) -> void:
queue_redraw()
func _has_point(p: Vector2) -> bool:
if _linking:
return true
if main == null or main.mode != Main.Mode.BUILD:
return false
for g in _grab:
if p.distance_to(g["pos"]) <= GRAB_RADIUS:
return true
return false
func _draw() -> void:
_grab.clear()
var build := main.mode == Main.Mode.BUILD
var mouse := get_local_mouse_position()
for t in main.data.tables:
var card := main.card_for(t.id)
if card == null or not card.is_inside_tree():
continue
_port(card.inlet_point(), Style.COPPER, Style.COPPER_DARK, 1.0)
for e in t.entries:
if not card.rows.has(e.id):
continue
var a := card.anchor_for(e.id)
if a.is_empty() or not a["visible"]:
continue
var on := not e.pipes.is_empty() or not main.ref_targets_for(e).is_empty()
if not build and not on:
continue
var pos: Vector2 = a["pos"]
var fill := Style.COPPER if on else Style.CARD
var ring := Style.COPPER_DARK
var s := 1.0
if on and main.is_entry_lit(t.id, e.id):
fill = Style.BRASS
ring = Style.BRASS_DARK
if build and pos.distance_to(mouse) <= GRAB_RADIUS and not _linking:
fill = Style.BRASS
s = 1.2
_port(pos, fill, ring, s)
if build:
_grab.append({"pos": pos, "tid": t.id, "eid": e.id})
if card.more_row != null:
var m := card.anchor_for("")
var on_hidden := card.hidden_has_pipes()
if not m.is_empty() and (on_hidden or build):
_port(m["pos"], Style.COPPER if on_hidden else Style.CARD, Style.COPPER_DARK, 1.0)
if _linking:
_draw_ghost(PipeLayer.curve(_ghost_from, _ghost_to))
func _port(pos: Vector2, fill: Color, ring: Color, s: float) -> void:
draw_circle(pos, 8.0 * s, ring)
draw_circle(pos, 5.0 * s, fill)
func _draw_ghost(pts: PackedVector2Array) -> void:
var carry := 0.0
for i in range(1, pts.size()):
var a := pts[i - 1]
var b := pts[i]
var seg := a.distance_to(b)
var d := carry
while d < seg:
draw_circle(a.lerp(b, d / seg), 2.5, Style.BRASS)
d += 11.0
carry = d - seg
func _gui_input(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
if mb.pressed:
for g in _grab:
if mb.position.distance_to(g["pos"]) <= GRAB_RADIUS:
_linking = true
_ghost_from = g["pos"]
_ghost_to = mb.position
main.start_link(g["tid"], g["eid"])
accept_event()
return
elif _linking:
_linking = false
main.finish_link()
accept_event()
return
var mm := ev as InputEventMouseMotion
if mm and _linking:
_ghost_to = mm.position
main.update_link()
accept_event()

1
ui/port_layer.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://2k7jy6gpuaob

269
ui/result_tray.gd Normal file
View file

@ -0,0 +1,269 @@
class_name ResultTray
extends PanelContainer
## The strip along the bottom: the current roll as a chain of result chips
## joined by brass pipe pieces, a Copy menu, and on the right either the
## earlier rolls (default) or the Variables tab.
enum Side { EARLIER, VARIABLES }
const COPY_TEXT := 0
const COPY_BBCODE := 1
const COPY_DETAILS := 2
var main: Main
var side: int = Side.EARLIER
var _title: Label
var _again: Button
var _copy: MenuButton
var _flow: HFlowContainer
var _empty: Label
var _earlier_box: VBoxContainer
var _earlier: VBoxContainer
var _earlier_empty: Label
var _vars: VariablesPanel
var _tab_earlier: Button
var _tab_vars: Button
var _shown_for: Dictionary = {}
var _shown_count := 0
func setup(p_main: Main) -> void:
main = p_main
var sb := Style.box(Style.FELT_DEEP, 0, [16, 14, 16, 16])
sb.border_width_top = 1
sb.border_color = Color(1, 1, 1, 0.08)
add_theme_stylebox_override("panel", sb)
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", 28)
add_child(h)
var now := VBoxContainer.new()
now.add_theme_constant_override("separation", 10)
now.size_flags_horizontal = SIZE_EXPAND_FILL
h.add_child(now)
var head := HBoxContainer.new()
head.add_theme_constant_override("separation", 12)
now.add_child(head)
_title = Style.make_label("RESULT", Style.caps(), 12, Style.ON_FELT_MUTED)
_title.size_flags_vertical = SIZE_SHRINK_CENTER
head.add_child(_title)
_again = Style.bar_button("Roll again")
_again.pressed.connect(func() -> void:
if not main.current.is_empty():
main.start_roll(main.current["root"])
)
head.add_child(_again)
_copy = _make_copy_menu()
head.add_child(_copy)
_flow = HFlowContainer.new()
_flow.add_theme_constant_override("h_separation", 0)
_flow.add_theme_constant_override("v_separation", 8)
# Keep the tray's height steady while a new roll's chips arrive.
_flow.custom_minimum_size = Vector2(0, 58)
now.add_child(_flow)
_empty = Style.make_label("Click a die on any table to roll.", Style.body(), 16, Style.ON_FELT_MUTED)
now.add_child(_empty)
var right := VBoxContainer.new()
right.add_theme_constant_override("separation", 8)
right.custom_minimum_size = Vector2(340, 0)
h.add_child(right)
var tabs := HBoxContainer.new()
tabs.add_theme_constant_override("separation", 14)
right.add_child(tabs)
_tab_earlier = _tab("EARLIER")
_tab_earlier.pressed.connect(func() -> void: set_side(Side.EARLIER))
tabs.add_child(_tab_earlier)
_tab_vars = _tab("VARIABLES")
_tab_vars.tooltip_text = "Saved variables for this collection"
_tab_vars.pressed.connect(func() -> void: set_side(Side.VARIABLES))
tabs.add_child(_tab_vars)
_earlier_box = VBoxContainer.new()
_earlier_box.add_theme_constant_override("separation", 6)
right.add_child(_earlier_box)
_earlier = VBoxContainer.new()
_earlier.add_theme_constant_override("separation", 6)
_earlier_box.add_child(_earlier)
_earlier_empty = Style.make_label("Older rolls show here.", Style.body(), 15, Style.ON_FELT_MUTED)
_earlier_box.add_child(_earlier_empty)
_vars = VariablesPanel.new()
_vars.setup(main)
right.add_child(_vars)
set_side(Side.EARLIER)
func _tab(text: String) -> Button:
var b := Button.new()
b.text = text
b.toggle_mode = true
b.add_theme_font_override("font", Style.caps())
b.add_theme_font_size_override("font_size", 12)
var n := Style.box(Color(0, 0, 0, 0), 0, [0, 0, 0, 3])
var on := Style.box(Color(0, 0, 0, 0), 0, [0, 0, 0, 1])
on.border_width_bottom = 2
on.border_color = Style.BRASS
Style.skin_button(b, n, n, on, Style.ON_FELT_MUTED, Style.ON_FELT, Style.ON_FELT)
b.add_theme_stylebox_override("focus", Style.box(Color(0, 0, 0, 0)))
return b
func set_side(s: int) -> void:
side = s
_tab_earlier.set_pressed_no_signal(s == Side.EARLIER)
_tab_vars.set_pressed_no_signal(s == Side.VARIABLES)
_earlier_box.visible = s == Side.EARLIER
_vars.visible = s == Side.VARIABLES
if s == Side.VARIABLES:
_vars.render()
func _make_copy_menu() -> MenuButton:
var m := MenuButton.new()
m.text = "Copy"
m.tooltip_text = "Copy this result"
m.flat = false
var normal := Style.bordered(Style.box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
var hover := Style.bordered(Style.box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
Style.skin_button(m, normal, hover, hover, Style.ON_FELT)
m.add_theme_font_size_override("font_size", 15)
var pm := m.get_popup()
pm.add_item("Copy as text", COPY_TEXT)
pm.add_item("Copy as BBCode", COPY_BBCODE)
pm.add_item("Copy with details", COPY_DETAILS)
pm.add_theme_stylebox_override("panel", Style.bordered(Style.box(Style.CARD, 8, [6, 6, 6, 6]), 1, Style.RULE))
pm.add_theme_stylebox_override("hover", Style.box(Style.LIT, 5, [8, 4, 8, 4]))
pm.add_theme_color_override("font_color", Style.INK)
pm.add_theme_color_override("font_hover_color", Style.INK)
pm.add_theme_font_override("font", Style.body())
pm.add_theme_font_size_override("font_size", 15)
pm.id_pressed.connect(func(id: int) -> void: main.copy_current(id))
return m
func render() -> void:
var current := main.current
var steps: Array = current.get("steps", [])
var fresh_from := 0
if is_same(current, _shown_for):
fresh_from = _shown_count
_shown_for = current
_shown_count = steps.size()
for c in _flow.get_children():
_flow.remove_child(c)
c.queue_free()
_empty.visible = current.is_empty()
if current.is_empty():
_title.text = "RESULT"
_again.hide()
_copy.hide()
else:
var root_name := Formatter.strip_tags(str(current["root_name"]))
_title.text = ("Result · %s" % root_name).to_upper()
_again.text = "Roll %s again" % root_name
_again.visible = main.data.get_table(current["root"]) != null
var done: bool = current.get("done", false)
_copy.visible = done
for i in steps.size():
var step: Dictionary = steps[i]
if i > 0:
_flow.add_child(_link(step.get("inline", false)))
var chip := _chip(step, done and i == steps.size() - 1)
_flow.add_child(chip)
if i >= fresh_from:
chip.modulate.a = 0.3
create_tween().tween_property(chip, "modulate:a", 1.0, 0.25)
for c in _earlier.get_children():
_earlier.remove_child(c)
c.queue_free()
_earlier_empty.visible = main.history.is_empty()
for rec in main.history:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 8)
var time := Style.make_label(clock(rec["time"]), Style.body(), 14, Style.ON_FELT_MUTED)
time.custom_minimum_size = Vector2(44, 0)
time.size_flags_vertical = SIZE_SHRINK_BEGIN
row.add_child(time)
var texts := PackedStringArray()
for s: Dictionary in rec["steps"]:
if not s.get("inline", false):
texts.append(RichText.decorate(str(s["text"]), true))
var line := RichText.label("[color=#%s]%s:[/color] %s" % [Style.ON_FELT_MUTED.to_html(false),
RichText.plain(Formatter.strip_tags(str(rec["root_name"]))), " → ".join(texts)], 14, Style.ON_FELT, false)
line.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(line, main)
row.add_child(line)
_earlier.add_child(row)
var n := main.persistent_vars.size()
_tab_vars.text = "VARIABLES · %d" % n if n > 0 else "VARIABLES"
if side == Side.VARIABLES:
_vars.render()
func _chip(step: Dictionary, last: bool) -> Control:
var inline: bool = step.get("inline", false)
var p := PanelContainer.new()
var sb := Style.box(Style.LIT if last else Style.CARD, 9, [10, 5, 10, 6] if inline else [12, 7, 12, 8])
sb.shadow_color = Color(0, 0, 0, 0.25)
sb.shadow_size = 1
sb.shadow_offset = Vector2(0, 3)
if last:
Style.bordered(sb, 2, Style.BRASS)
sb.set_expand_margin_all(2)
if inline:
sb.bg_color = sb.bg_color.darkened(0.04)
p.add_theme_stylebox_override("panel", sb)
p.size_flags_vertical = SIZE_SHRINK_CENTER
p.mouse_filter = MOUSE_FILTER_PASS
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1)
p.add_child(v)
var num: String = step["num"]
var caption := Formatter.strip_tags(str(step["table"]))
if num != "":
caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step["die"]))]
if step.get("reshuffled", false):
caption += " · deck reshuffled"
if str(step.get("save_as", "")) != "":
caption += " · saved as {%s}" % step["save_as"]
var has_details := main.details().step_has_details(step)
if has_details:
caption += " " + RichText.INFO_MARK
var cap := Style.make_label(caption, Style.body(), 11 if inline else 12, Style.MUTED)
cap.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(cap)
var shown := RichText.decorate(str(step["text"]))
var body := RichText.display_label(shown, 16 if inline else 20, Style.DANGER_INK if step.get("stop", false) else Style.INK)
if Formatter.strip_tags(shown).length() > 56:
body.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
body.custom_minimum_size = Vector2(420, 0)
RichText.hook_hover(body, main)
v.add_child(body)
if has_details:
p.mouse_entered.connect(func() -> void: main.details().show_step(p, step))
return p
func _link(inline: bool = false) -> Control:
var link := Panel.new()
var sb := Style.box(Style.BRASS)
sb.border_width_top = 2
sb.border_width_bottom = 2
sb.border_color = Style.BRASS_DARK
if inline:
sb = Style.box(Color(Style.BRASS, 0.55))
link.add_theme_stylebox_override("panel", sb)
link.custom_minimum_size = Vector2(16, 4) if inline else Vector2(22, 8)
link.size_flags_vertical = SIZE_SHRINK_CENTER
link.mouse_filter = MOUSE_FILTER_IGNORE
return link
static func clock(unix: float) -> String:
var bias: int = Time.get_time_zone_from_system().get("bias", 0)
var d := Time.get_datetime_dict_from_unix_time(int(unix) + bias * 60)
return "%02d:%02d" % [d["hour"], d["minute"]]

1
ui/result_tray.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://htxsmwhs2m5y

205
ui/rich_text.gd Normal file
View file

@ -0,0 +1,205 @@
class_name RichText
extends RefCounted
## BBCode display helpers: RichTextLabels in the app's fonts, a readable preview
## of entry text with [[references]] and {variables}, and colouring for
## TextExpander's internal markers in rolled results.
## Marker shown after items that have hover details.
const INFO_MARK := "ⓘ"
const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}"
const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*[dD]\\d+(?:\\s*[+-]\\s*\\d+)?))\\s+(\\S.*)$"
static var _var_re: RegEx
static var _count_re: RegEx
## Colours for marker text, on cards (light) and on the felt (dark).
const REF_INK := Color("#1d6656")
const REF_BG := Color("#d6e9e2")
const VAR_INK := Color("#7d5a0c")
const REF_INK_FELT := Color("#9fdcc9")
const VAR_INK_FELT := Color("#f3c450")
const BAD_INK_FELT := Color("#ffb1a3")
## A RichTextLabel that sizes itself to its text like a Label.
## `zoomable` picks the card (MSDF) fonts that stay sharp on the zoomed board.
static func label(text: String, font_size: int, color: Color, zoomable: bool, wrap: bool = true, bold: bool = false) -> RichTextLabel:
var l := RichTextLabel.new()
l.bbcode_enabled = true
l.fit_content = true
l.scroll_active = false
l.meta_underlined = false
l.hint_underlined = false
l.shortcut_keys_enabled = false
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART if wrap else TextServer.AUTOWRAP_OFF
l.mouse_filter = Control.MOUSE_FILTER_PASS
set_fonts(l, font_size, zoomable, bold)
l.add_theme_color_override("default_color", color)
l.text = text
return l
## Sets every font slot of a RichTextLabel. `bold` makes the normal text bold
## (used for a lit row).
static func set_fonts(l: RichTextLabel, font_size: int, zoomable: bool, bold: bool = false) -> void:
l.add_theme_font_override("normal_font", Style.body_bold(zoomable) if bold else Style.body(zoomable))
l.add_theme_font_override("bold_font", Style.body_bold(zoomable))
l.add_theme_font_override("italics_font", Style.body_italic(zoomable))
l.add_theme_font_override("bold_italics_font", Style.body_bold(zoomable))
for slot in ["normal_font_size", "bold_font_size", "italics_font_size", "bold_italics_font_size", "mono_font_size"]:
l.add_theme_font_size_override(slot, font_size)
## Same as label() but in the Rokkitt display face (result chips).
static func display_label(text: String, font_size: int, color: Color, zoomable: bool = false) -> RichTextLabel:
var l := label(text, font_size, color, zoomable, false)
var f := Style.display(zoomable)
l.add_theme_font_override("normal_font", f)
l.add_theme_font_override("bold_font", Style.display(zoomable, 900))
return l
## Connects a label's [url] metas to the details pop-up.
static func hook_hover(l: RichTextLabel, main: Main) -> void:
l.meta_hover_started.connect(func(meta: Variant) -> void:
main.details().show_meta(l, str(meta)))
l.meta_hover_ended.connect(func(_meta: Variant) -> void:
main.details().hide_for(l))
# A click (or a tap, where there's no hover) opens the same pop-up.
l.meta_clicked.connect(func(meta: Variant) -> void:
main.details().show_meta(l, str(meta)))
## Small muted ⓘ appended to text that has hover details.
static func info_mark(on_felt: bool = false) -> String:
var c := Style.ON_FELT_MUTED if on_felt else Color("#9a9483")
return " [font_size=12][color=#%s]%s[/color][/font_size]" % [c.to_html(false), INFO_MARK]
## Escapes text so it shows exactly as typed.
static func plain(text: String) -> String:
return text.replace("[", "[lb]")
## Readable BBCode for an entry's text as written (not rolled): each [[reference]]
## becomes a small teal chip with the table's name, {variables} show in brass,
## and a missing table shows the warning marker. References are wrapped in
## [url=table:id] so hovering them shows the table's details.
static func preview(text: String, board: TowerBoard) -> String:
if not text.contains("[[") and not text.contains("{"):
return text
var out := ""
var i := 0
var n := text.length()
while i < n:
var c := text[i]
if c == "[" and i + 1 < n and text[i + 1] == "[":
var close := text.find("]]", i + 2)
var body := text.substr(i + 2, close - i - 2) if close >= 0 else ""
if close >= 0 and body.strip_edges() != "" and not body.contains("[") and not body.contains("]") and not body.contains("\n"):
out += _ref_chip(body, board)
i = close + 2
continue
out += c
i += 1
continue
if c == "[":
var tag := Formatter.tag_at(text, i)
if not tag.is_empty():
out += tag["raw"]
i += (tag["raw"] as String).length()
continue
elif c == "{":
var m := _vre().search(text, i)
if m != null and m.get_start() == i:
var vname := m.get_string(1)
var shown := "{%s}" % vname
out += "[url=var:%s][color=#%s]%s[/color][/url]" % [vname, VAR_INK.to_html(false), shown]
var from := m.get_string(2).strip_edges()
if from != "":
var id := Roller.resolve(board, from)
if id == "":
out += " " + _bad(TextExpander.missing_marker(from), false)
i = m.get_end()
continue
out += c
i += 1
return Formatter.close_open_tags(out)
static func _ref_chip(body: String, board: TowerBoard) -> String:
var name := body
var save := ""
var arrow := body.rfind("->")
if arrow >= 0:
save = body.substr(arrow + 2).strip_edges()
name = body.substr(0, arrow)
name = name.strip_edges()
var count := ""
var id := Roller.resolve(board, name)
if id == "":
var m := _cre().search(name)
if m != null:
count = (m.get_string(1) + "×") if m.get_string(1) != "" else (m.get_string(2) + "×")
name = m.get_string(3).strip_edges()
id = Roller.resolve(board, name)
if id == "":
return _bad(TextExpander.missing_marker(name), false)
var t := board.get_table(id)
var label_text := count + plain(Formatter.strip_tags(t.name))
if save != "":
label_text += " → " + plain(save)
return "[url=table:%s][bgcolor=#%s][color=#%s] %s [/color][/bgcolor][/url]" % [id, REF_BG.to_html(false), REF_INK.to_html(false), label_text]
## Colours the internal markers of rolled text: table rolls in teal, variables in
## brass, and missing / unset / too-deep markers in red, so they're visible.
static func decorate(bbcode: String, on_felt: bool = false) -> String:
if not bbcode.contains("[url="):
return bbcode
var out := ""
var open: Array[String] = []
for t: Dictionary in Formatter.tokenize(bbcode):
if t["name"] == "url":
if t["kind"] == "open":
var meta := (t["param"] as String).trim_prefix("=").strip_edges().trim_prefix("\"").trim_suffix("\"")
var color := _marker_color(meta, on_felt)
out += t["raw"]
if color != "":
out += "[color=#%s]" % color
open.append(color)
continue
elif not open.is_empty():
if open.pop_back() != "":
out += "[/color]"
out += t["raw"]
return out
static func _marker_color(meta: String, on_felt: bool) -> String:
if meta.begins_with("table:"):
return (REF_INK_FELT if on_felt else REF_INK).to_html(false)
if meta.begins_with("var:"):
return (VAR_INK_FELT if on_felt else VAR_INK).to_html(false)
if meta.begins_with("missing:") or meta.begins_with("unset:") or meta.begins_with("deep:"):
return (BAD_INK_FELT if on_felt else Style.DANGER_INK).to_html(false)
return ""
static func _bad(marker: String, on_felt: bool) -> String:
return decorate(marker, on_felt)
static func _vre() -> RegEx:
if _var_re == null:
_var_re = RegEx.new()
_var_re.compile(_VAR_PATTERN)
return _var_re
static func _cre() -> RegEx:
if _count_re == null:
_count_re = RegEx.new()
_count_re.compile(_COUNT_PATTERN)
return _count_re

1
ui/rich_text.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cftrtp5fjrga2

188
ui/style.gd Normal file
View file

@ -0,0 +1,188 @@
class_name Style
extends RefCounted
## Palette, fonts and stylebox helpers for the felt-board look.
const FELT := Color("#1f4a39")
const FELT_DEEP := Color("#12301f")
const FELT_HOVER := Color("#276048")
const CARD := Color("#efece2")
const INK := Color("#1c2520")
const MUTED := Color("#69726b")
const RULE := Color("#d8d3c3")
const COPPER := Color("#b8703a")
const COPPER_DARK := Color("#4f2b12")
const BRASS := Color("#f3c450")
const BRASS_DARK := Color("#6e5410")
const LIT := Color("#f8e4a2")
const FLICK := Color(0.953, 0.769, 0.314, 0.35)
const HOVER_ROW := Color("#e9e4d6")
const ON_FELT := Color("#e9efe9")
const ON_FELT_MUTED := Color("#a8bdb1")
const DANGER := Color("#e0574a")
const DANGER_INK := Color("#a33a2c")
const WARN_BG := Color("#f4dacb")
const WARN_INK := Color("#8a2f1d")
const DASH := Color("#bdb6a2")
const PULSE := Color("#fff6d2")
const FONT_DIR := "res://assets/fonts/"
static var _fonts: Dictionary = {}
# ---------- Fonts ----------
# Cards live on the zoomable board, so they use MSDF fonts that stay sharp at any scale.
static func _file(file: String, msdf: bool) -> FontFile:
var key := "%s|%s" % [file, msdf]
if not _fonts.has(key):
var f: FontFile = load(FONT_DIR + file)
if msdf:
f = f.duplicate() as FontFile
f.multichannel_signed_distance_field = true
_fonts[key] = f
return _fonts[key]
static func body(msdf: bool = false) -> Font:
return _file("AtkinsonHyperlegible-Regular.ttf", msdf)
static func body_bold(msdf: bool = false) -> Font:
return _file("AtkinsonHyperlegible-Bold.ttf", msdf)
static func body_italic(msdf: bool = false) -> Font:
return _file("AtkinsonHyperlegible-Italic.ttf", msdf)
## Rokkitt, the slab display face. It's a variable font with overlapping
## outlines, which MSDF renders badly, so on cards it is oversampled instead.
static func display(zoomable: bool = false, weight: int = 700) -> Font:
var key := "display|%d|%s" % [weight, zoomable]
if not _fonts.has(key):
var v := FontVariation.new()
var base := _file("Rokkitt-Variable.ttf", false)
if zoomable:
base = base.duplicate() as FontFile
base.oversampling = 2.0
v.base_font = base
v.variation_opentype = {TextServerManager.get_primary_interface().name_to_tag("wght"): weight}
_fonts[key] = v
return _fonts[key]
## Bold body face with a little letter-spacing, for small uppercase labels.
static func caps() -> Font:
if not _fonts.has("caps"):
var v := FontVariation.new()
v.base_font = body_bold()
v.spacing_glyph = 1
_fonts["caps"] = v
return _fonts["caps"]
# ---------- Styleboxes ----------
## margins: [left, top, right, bottom]
static func box(bg: Color, radius: int = 0, margins: Array = [0, 0, 0, 0]) -> StyleBoxFlat:
var s := StyleBoxFlat.new()
s.bg_color = bg
s.set_corner_radius_all(radius)
s.content_margin_left = margins[0]
s.content_margin_top = margins[1]
s.content_margin_right = margins[2]
s.content_margin_bottom = margins[3]
s.anti_aliasing = true
return s
static func bordered(s: StyleBoxFlat, width: int, color: Color) -> StyleBoxFlat:
s.set_border_width_all(width)
s.border_color = color
return s
static func focus_ring(radius: int = 8) -> StyleBoxFlat:
var s := box(Color(0, 0, 0, 0), radius)
s.draw_center = false
bordered(s, 2, BRASS)
s.set_expand_margin_all(2)
return s
static func skin_button(b: Button, normal: StyleBox, hover: StyleBox, pressed: StyleBox,
fg: Color, fg_hover: Color = Color(0, 0, 0, 0), fg_pressed: Color = Color(0, 0, 0, 0)) -> void:
if fg_hover.a == 0.0:
fg_hover = fg
if fg_pressed.a == 0.0:
fg_pressed = fg_hover
b.add_theme_stylebox_override("normal", normal)
b.add_theme_stylebox_override("hover", hover)
b.add_theme_stylebox_override("pressed", pressed)
b.add_theme_stylebox_override("hover_pressed", pressed)
b.add_theme_stylebox_override("disabled", normal)
b.add_theme_stylebox_override("focus", focus_ring())
b.add_theme_color_override("font_color", fg)
b.add_theme_color_override("font_hover_color", fg_hover)
b.add_theme_color_override("font_focus_color", fg)
b.add_theme_color_override("font_pressed_color", fg_pressed)
b.add_theme_color_override("font_hover_pressed_color", fg_pressed)
b.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
static func make_label(text: String, font: Font, font_size: int, color: Color) -> Label:
var l := Label.new()
l.text = text
l.add_theme_font_override("font", font)
l.add_theme_font_size_override("font_size", font_size)
l.add_theme_color_override("font_color", color)
return l
## A top-bar button: translucent on felt, or brass when primary.
static func bar_button(text: String, primary: bool = false) -> Button:
var b := Button.new()
b.text = text
var normal := bordered(box(Color(1, 1, 1, 0.04), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
var hover := bordered(box(Color(1, 1, 1, 0.1), 8, [12, 6, 12, 6]), 1, Color(1, 1, 1, 0.16))
var fg := ON_FELT
if primary:
normal = bordered(box(BRASS, 8, [12, 6, 12, 6]), 1, BRASS)
hover = bordered(box(BRASS.lightened(0.15), 8, [12, 6, 12, 6]), 1, BRASS.lightened(0.15))
fg = INK
b.add_theme_font_override("font", body_bold())
skin_button(b, normal, hover, hover, fg)
b.add_theme_font_size_override("font_size", 15)
return b
# ---------- Themes ----------
static func app_theme() -> Theme:
var th := Theme.new()
th.default_font = body()
th.default_font_size = 16
th.set_color("font_color", "Label", ON_FELT)
th.set_stylebox("panel", "TooltipPanel", box(CARD, 6, [8, 5, 8, 5]))
th.set_color("font_color", "TooltipLabel", INK)
return th
static func card_theme() -> Theme:
var th := Theme.new()
th.default_font = body(true)
th.default_font_size = 16
th.set_color("font_color", "Label", INK)
var normal := bordered(box(Color(1, 1, 1, 0), 5, [6, 3, 6, 3]), 1, Color(1, 1, 1, 0))
var focus := bordered(box(Color.WHITE, 5, [6, 3, 6, 3]), 1, COPPER)
th.set_stylebox("normal", "LineEdit", normal)
th.set_stylebox("focus", "LineEdit", focus)
th.set_stylebox("read_only", "LineEdit", normal)
th.set_color("font_color", "LineEdit", INK)
th.set_color("caret_color", "LineEdit", INK)
th.set_color("selection_color", "LineEdit", Color(BRASS, 0.55))
th.set_color("font_placeholder_color", "LineEdit", MUTED)
# Card fields are sized by their containers, not by a minimum character count.
th.set_constant("minimum_character_width", "LineEdit", 0)
return th

1
ui/style.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bpj6lb2k0d6fo

781
ui/table_card.gd Normal file
View file

@ -0,0 +1,781 @@
class_name TableCard
extends PanelContainer
## One table on the board: a header with the collapse toggle, name and die
## button, then its numbered results. Rebuilt from the RollTable whenever the
## mode, the table's shape, or (when collapsed) the lit result changes.
const WIDTH := 256.0
## Build mode has more controls per row, so cards are a little wider there.
const BUILD_WIDTH := 300.0
const LONG_LIST := 12
const LIST_HEIGHT := 432.0
const INLET_Y := 30.0
enum RowState { NORMAL, FLICK, LIT }
var main: Main
var table: RollTable
## entry id -> row PanelContainer, for the rows currently shown.
var rows: Dictionary = {}
var more_row: PanelContainer
var list_scroll: ScrollContainer
var _row_parts: Dictionary = {}
var _row_styles: Array[StyleBoxFlat] = []
var _list_box: VBoxContainer
var _more_label: Label
var _warn_panel: Control
var _warn_label: Label
var _die_icon: DieIcon
var _rolling := false
var _dragging := false
var _drop_target := false
var _drag_offset := Vector2.ZERO
var _flick_id := ""
var _style_normal: StyleBoxFlat
var _style_rolling: StyleBoxFlat
var _style_dragging: StyleBoxFlat
var _style_drop: StyleBoxFlat
var _deck_row: Control
var _deck_label: Label
## Entry ids whose details editor is open (Build mode).
var _open_details: Dictionary = {}
var _table_details_open := false
func setup(p_main: Main, p_table: RollTable) -> void:
main = p_main
table = p_table
custom_minimum_size = Vector2(WIDTH, 0)
mouse_filter = MOUSE_FILTER_PASS
theme = Style.card_theme()
position = table.position
_style_normal = Style.box(Style.CARD, 10)
_style_normal.shadow_color = Color(0, 0, 0, 0.32)
_style_normal.shadow_size = 16
_style_normal.shadow_offset = Vector2(0, 8)
_style_rolling = _style_normal.duplicate() as StyleBoxFlat
Style.bordered(_style_rolling, 3, Style.BRASS)
_style_rolling.set_expand_margin_all(3)
_style_rolling.shadow_color = Color(Style.BRASS, 0.45)
_style_rolling.shadow_size = 26
_style_rolling.shadow_offset = Vector2.ZERO
_style_drop = _style_rolling.duplicate() as StyleBoxFlat
_style_drop.shadow_color = Color(0, 0, 0, 0.32)
_style_drop.shadow_size = 16
_style_drop.shadow_offset = Vector2(0, 8)
_style_dragging = _style_normal.duplicate() as StyleBoxFlat
_style_dragging.shadow_color = Color(0, 0, 0, 0.4)
_style_dragging.shadow_size = 26
_style_dragging.shadow_offset = Vector2(0, 16)
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
_row_styles.append(Style.box(c, 0, [12, 6, 22, 6]))
minimum_size_changed.connect(func() -> void: _shrink.call_deferred())
rebuild()
func rebuild() -> void:
for c in get_children():
remove_child(c)
c.queue_free()
rows.clear()
_row_parts.clear()
more_row = null
_more_label = null
list_scroll = null
_flick_id = ""
_deck_row = null
_deck_label = null
var build := main.mode == Main.Mode.BUILD
custom_minimum_size = Vector2(card_width(), 0)
_shrink.call_deferred()
var ranged := table.is_ranged()
var col := _vbox(0)
add_child(col)
col.add_child(_make_header(build, ranged))
if build and _table_details_open:
var ted := _details_editor(table.details, "Details for this table (BBCode)", 12.0,
func(s: String) -> void:
table.details = s
main.mark_dirty())
ted.add_theme_constant_override("margin_top", 8)
col.add_child(ted)
var pad := MarginContainer.new()
pad.mouse_filter = MOUSE_FILTER_PASS
pad.add_theme_constant_override("margin_top", 6)
pad.add_theme_constant_override("margin_bottom", 8)
_list_box = _vbox(0)
pad.add_child(_list_box)
if not table.collapsed and table.entries.size() > LONG_LIST:
list_scroll = ScrollContainer.new()
list_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
list_scroll.custom_minimum_size = Vector2(0, LIST_HEIGHT)
list_scroll.mouse_filter = MOUSE_FILTER_PASS
_skin_scrollbar(list_scroll.get_v_scroll_bar())
pad.size_flags_horizontal = SIZE_EXPAND_FILL
list_scroll.add_child(pad)
col.add_child(list_scroll)
else:
col.add_child(pad)
var numw := _num_width(build, ranged)
for i in table.entries.size():
var e := table.entries[i]
var lit := main.is_entry_lit(table.id, e.id)
if table.collapsed and not lit:
continue
_list_box.add_child(_make_row(e, i, build, ranged, numw))
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
if build and _open_details.has(e.id):
_list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0,
func(s: String) -> void:
e.details = s
main.mark_dirty()))
if table.collapsed:
_list_box.add_child(_make_more_row(numw))
_warn_panel = _make_warning()
col.add_child(_warn_panel)
_update_warning()
if build:
col.add_child(_make_footer(ranged))
_apply_style()
if list_scroll != null:
for eid in rows:
if main.is_entry_lit(table.id, eid):
_reveal_when_laid_out.call_deferred(eid)
break
func _reveal_when_laid_out(eid: String) -> void:
await get_tree().process_frame
if is_instance_valid(list_scroll):
reveal(eid)
# ---------- Building blocks ----------
func _vbox(sep: int) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", sep)
v.mouse_filter = MOUSE_FILTER_PASS
return v
func _hbox(sep: int) -> HBoxContainer:
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", sep)
h.mouse_filter = MOUSE_FILTER_PASS
return h
func _num_width(build: bool, ranged: bool) -> float:
var wide := table.die_size() >= 100
if build and ranged:
return 90.0
if ranged:
return 52.0 if wide else 40.0
return 24.0 if wide else 22.0
func _make_header(build: bool, ranged: bool) -> Control:
var header := PanelContainer.new()
var hs := Style.box(Color(0, 0, 0, 0), 0, [12, 10, 10, 9])
hs.border_width_bottom = 1
hs.border_color = Style.RULE
header.add_theme_stylebox_override("panel", hs)
header.mouse_filter = MOUSE_FILTER_PASS
header.mouse_default_cursor_shape = CURSOR_MOVE
header.gui_input.connect(_on_header_input.bind(header))
var row := _hbox(8)
var head_box := _vbox(4)
header.add_child(head_box)
head_box.add_child(row)
var chevron := ChevronButton.new()
chevron.open = not table.collapsed
chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name
chevron.size_flags_vertical = SIZE_SHRINK_CENTER
chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id))
row.add_child(chevron)
header.mouse_entered.connect(func() -> void:
if not _dragging and main.mode == Main.Mode.PLAY:
main.details().show_table(header, table.id, true)
)
if build:
var name_edit := LineEdit.new()
name_edit.text = table.name
name_edit.size_flags_horizontal = SIZE_EXPAND_FILL
name_edit.size_flags_vertical = SIZE_SHRINK_CENTER
name_edit.custom_minimum_size = Vector2(40, 0)
name_edit.add_theme_font_override("font", Style.display(true))
name_edit.add_theme_font_size_override("font_size", 18)
name_edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 6, [7, 3, 7, 3]), 1, Style.RULE))
name_edit.text_changed.connect(func(s: String) -> void:
table.name = s
main.mark_dirty()
)
row.add_child(name_edit)
var gear := Button.new()
gear.text = "⚙"
gear.tooltip_text = "Table settings"
gear.custom_minimum_size = Vector2(26, 26)
gear.size_flags_vertical = SIZE_SHRINK_CENTER
gear.add_theme_font_size_override("font_size", 16)
Style.skin_button(gear, Style.box(Color(0, 0, 0, 0), 6), Style.box(Color("#e6dfcd"), 6), Style.box(Color("#e6dfcd"), 6), Style.MUTED, Style.INK)
gear.pressed.connect(func() -> void: main.request_table_settings(table.id))
row.add_child(gear)
else:
var titles := _vbox(3)
titles.size_flags_horizontal = SIZE_EXPAND_FILL
titles.size_flags_vertical = SIZE_SHRINK_CENTER
titles.mouse_filter = MOUSE_FILTER_IGNORE
var title := Style.make_label(Formatter.strip_tags(table.name), Style.display(true), 20, Style.INK)
title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
if table.details.strip_edges() != "":
# A small ⓘ after the name says hovering shows the table's details.
var name_row := _hbox(4)
name_row.mouse_filter = MOUSE_FILTER_IGNORE
title.size_flags_horizontal = SIZE_EXPAND_FILL
name_row.add_child(title)
var mark := Style.make_label(RichText.INFO_MARK, Style.body(true), 12, Color("#9a9483"))
mark.size_flags_vertical = SIZE_SHRINK_CENTER
name_row.add_child(mark)
titles.add_child(name_row)
else:
titles.add_child(title)
if ranged or table.collapsed:
var count := "%d %s" % [table.entries.size(), "ranges" if ranged else "results"]
var cl := Style.make_label(count, Style.body(true), 12, Style.MUTED)
cl.mouse_filter = MOUSE_FILTER_IGNORE
titles.add_child(cl)
row.add_child(titles)
if table.card_mode:
_deck_row = _make_deck_row()
var die := table.die_size()
var roll := Button.new()
roll.text = "d%d" % die
roll.tooltip_text = "Roll d%d on %s" % [die, table.name]
roll.size_flags_vertical = SIZE_SHRINK_CENTER
roll.add_theme_font_override("font", Style.display(true))
roll.add_theme_font_size_override("font_size", 17)
var rn := Style.box(Style.FELT, 8, [34, 6, 10, 6])
rn.border_width_bottom = 2
rn.border_color = Style.FELT_DEEP
var rh := rn.duplicate() as StyleBoxFlat
rh.bg_color = Style.FELT_HOVER
var rp := rn.duplicate() as StyleBoxFlat
rp.border_width_bottom = 1
rp.content_margin_top = 7
rp.content_margin_bottom = 5
Style.skin_button(roll, rn, rh, rp, Style.BRASS)
_die_icon = DieIcon.new()
_die_icon.spinning = _rolling
roll.add_child(_die_icon)
roll.resized.connect(func() -> void: _die_icon.position = Vector2(8, (roll.size.y - 20.0) / 2.0 - 1.0))
roll.pressed.connect(func() -> void: main.start_roll(table.id))
row.add_child(roll)
if _deck_row != null:
head_box.add_child(_deck_row)
return header
## Card mode: "4 / 6 left" and a small Reshuffle link under the title.
func _make_deck_row() -> Control:
var h := _hbox(6)
var pad := Control.new()
pad.custom_minimum_size = Vector2(26, 0)
pad.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(pad)
_deck_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_deck_label.size_flags_vertical = SIZE_SHRINK_CENTER
_deck_label.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(_deck_label)
var b := Button.new()
b.text = "↻ Reshuffle"
b.tooltip_text = "Put every card back in the deck"
b.add_theme_font_override("font", Style.body(true))
b.add_theme_font_size_override("font_size", 12)
b.size_flags_vertical = SIZE_SHRINK_CENTER
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(b, n, hv, hv, Style.COPPER, Style.INK)
b.pressed.connect(func() -> void: main.reshuffle_table(table.id))
h.add_child(b)
update_deck()
return h
## Refreshes the cards-left count of a card-mode table.
func update_deck() -> void:
if _deck_label == null or not is_instance_valid(_deck_label):
return
var left := main.cards_left(table.id)
_deck_label.text = "%d / %d left" % [left.x, left.y]
_deck_label.add_theme_color_override("font_color", Style.DANGER_INK if left.x == 0 else Style.MUTED)
func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := _hbox(8)
row.add_child(h)
var num: Label = null
if build and ranged:
var r := _hbox(2)
r.custom_minimum_size = Vector2(numw, 0)
r.size_flags_vertical = SIZE_SHRINK_CENTER
r.add_child(_range_edit(e, true))
r.add_child(Style.make_label("–", Style.display(true), 15, Style.MUTED))
r.add_child(_range_edit(e, false))
h.add_child(r)
else:
num = Style.make_label(table.num_label(e, index), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(num)
var text: RichTextLabel = null
if build:
h.add_theme_constant_override("separation", 4)
var edit := LineEdit.new()
edit.text = e.text
edit.size_flags_horizontal = SIZE_EXPAND_FILL
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
edit.add_theme_font_size_override("font_size", 15)
edit.text_changed.connect(func(s: String) -> void:
e.text = s
main.mark_dirty()
)
h.add_child(edit)
if not ranged:
h.add_child(_weight_edit(e))
var info := Button.new()
info.text = "i"
info.toggle_mode = true
info.button_pressed = _open_details.has(e.id)
info.tooltip_text = "Details shown when hovering this result"
info.custom_minimum_size = Vector2(22, 22)
info.size_flags_vertical = SIZE_SHRINK_CENTER
info.add_theme_font_override("font", Style.body_bold(true))
info.add_theme_font_size_override("font_size", 13)
var has := e.details.strip_edges() != ""
var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, Style.COPPER if has else Style.DASH)
var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER)
var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER)
Style.skin_button(info, inn, inh, inp, Style.COPPER if has else Style.MUTED, Style.INK)
info.toggled.connect(func(on: bool) -> void:
if on:
_open_details[e.id] = true
else:
_open_details.erase(e.id)
rebuild()
)
h.add_child(info)
var x := Button.new()
x.text = "×"
x.tooltip_text = "Delete this result"
x.custom_minimum_size = Vector2(22, 22)
x.size_flags_vertical = SIZE_SHRINK_CENTER
x.add_theme_font_size_override("font_size", 18)
Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK)
x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id))
h.add_child(x)
else:
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
text.size_flags_vertical = SIZE_SHRINK_CENTER
RichText.hook_hover(text, main)
h.add_child(text)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged:
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
pct.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(pct)
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e}
return row
## Play-mode text of a row: the last rolled (expanded) text when the row is
## lit, otherwise the entry as written with its references shown readably.
func _row_text(e: TableEntry) -> String:
var rolled := main.lit_text(table.id, e.id)
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
if e.details.strip_edges() != "":
s += RichText.info_mark()
return s
## Weight on a plain table, shown as ×N. Also the number of copies in card mode.
func _weight_edit(e: TableEntry) -> LineEdit:
var edit := LineEdit.new()
edit.text = "×%d" % e.weight
edit.custom_minimum_size = Vector2(34, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 4
edit.tooltip_text = "Weight: how likely this result is, relative to the others (0 = never)"
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 14)
edit.add_theme_color_override("font_color", Style.MUTED)
var commit := func() -> void:
var digits := ""
for ch in edit.text:
if ch >= "0" and ch <= "9":
digits += ch
var w := clampi(digits.to_int(), 0, 999) if digits != "" else e.weight
edit.text = "×%d" % w
if w != e.weight:
e.weight = w
update_deck()
main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
## A multi-line details editor (BBCode), shown under a row or the header.
func _details_editor(initial: String, placeholder: String, left: float, on_change: Callable) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var te := TextEdit.new()
te.text = initial
te.placeholder_text = placeholder
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 66)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 13)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
te.text_changed.connect(func() -> void: on_change.call(te.text))
wrap.add_child(te)
return wrap
func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit:
var edit := LineEdit.new()
edit.text = str(e.range_lo if is_lo else e.range_hi)
edit.custom_minimum_size = Vector2(40, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 3
edit.tooltip_text = "Range start" if is_lo else "Range end"
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 15)
edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.RULE))
edit.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.COPPER))
var commit := func() -> void:
var v := clampi(edit.text.to_int(), table.min_value(), table.die_size())
if is_lo:
e.range_lo = v
else:
e.range_hi = v
if e.range_lo > e.range_hi:
var tmp := e.range_lo
e.range_lo = e.range_hi
e.range_hi = tmp
edit.text = str(e.range_lo if is_lo else e.range_hi)
_update_warning()
main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
func _make_more_row(numw: float) -> Control:
more_row = PanelContainer.new()
var normal := Style.box(Color(0, 0, 0, 0), 0, [12, 6, 22, 6])
var hover := Style.box(Style.HOVER_ROW, 0, [12, 6, 22, 6])
more_row.add_theme_stylebox_override("panel", normal)
more_row.custom_minimum_size = Vector2(0, 36)
more_row.mouse_filter = MOUSE_FILTER_STOP
more_row.mouse_default_cursor_shape = CURSOR_POINTING_HAND
more_row.tooltip_text = "Show every result"
more_row.mouse_entered.connect(func() -> void: more_row.add_theme_stylebox_override("panel", hover))
more_row.mouse_exited.connect(func() -> void: more_row.add_theme_stylebox_override("panel", normal))
more_row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and not mb.pressed:
main.toggle_collapse.call_deferred(table.id)
)
var h := _hbox(8)
more_row.add_child(h)
var dots := Style.make_label("…", Style.display(true), 16, Style.MUTED)
dots.custom_minimum_size = Vector2(numw, 0)
dots.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
h.add_child(dots)
_more_label = Style.make_label(_more_text(), Style.body_italic(true), 14, Style.MUTED)
_more_label.size_flags_horizontal = SIZE_EXPAND_FILL
_more_label.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(_more_label)
return more_row
func _more_text() -> String:
var hidden := table.entries.size() - rows.size()
if rows.size() > 0:
return "%d more · show all" % hidden
return "%d %s · show all" % [table.entries.size(), "ranges" if table.is_ranged() else "results"]
func _make_warning() -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_bottom", 10)
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", Style.box(Style.WARN_BG, 6, [9, 6, 9, 6]))
panel.mouse_filter = MOUSE_FILTER_PASS
_warn_label = Style.make_label("", Style.body(true), 13, Style.WARN_INK)
_warn_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
panel.add_child(_warn_label)
wrap.add_child(panel)
return wrap
func _update_warning() -> void:
var problems := table.range_problems()
_warn_label.text = problems
_warn_panel.visible = problems != ""
func _make_footer(ranged: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_bottom", 10)
var h := _hbox(8)
wrap.add_child(h)
var add := _footer_button("+ Add range" if ranged else "+ Add result", Style.INK)
add.pressed.connect(func() -> void: main.add_entry(table.id))
h.add_child(add)
var det := _footer_button("Details", Style.INK)
det.tooltip_text = "Details shown when hovering the table's name"
if table.details.strip_edges() != "":
det.add_theme_color_override("font_color", Style.COPPER)
det.pressed.connect(func() -> void:
_table_details_open = not _table_details_open
rebuild()
)
h.add_child(det)
var spacer := Control.new()
spacer.size_flags_horizontal = SIZE_EXPAND_FILL
spacer.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(spacer)
var del := _footer_button("Delete", Style.DANGER_INK)
del.tooltip_text = "Delete this table"
del.pressed.connect(func() -> void: main.delete_table(table.id))
h.add_child(del)
return wrap
func _footer_button(text: String, hover_color: Color) -> Button:
var b := Button.new()
b.text = text
b.add_theme_font_size_override("font_size", 14)
var normal := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, Style.DASH)
var hover := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, hover_color if hover_color != Style.INK else Style.MUTED)
Style.skin_button(b, normal, hover, hover, Style.MUTED, hover_color)
return b
func _skin_scrollbar(bar: VScrollBar) -> void:
var track := Style.box(Color(0, 0, 0, 0), 3, [3, 0, 3, 0])
var grab := Style.box(Color(0, 0, 0, 0.22), 3, [3, 0, 3, 0])
var grab_hi := Style.box(Color(0, 0, 0, 0.35), 3, [3, 0, 3, 0])
bar.add_theme_stylebox_override("scroll", track)
bar.add_theme_stylebox_override("scroll_focus", track)
bar.add_theme_stylebox_override("grabber", grab)
bar.add_theme_stylebox_override("grabber_highlight", grab_hi)
bar.add_theme_stylebox_override("grabber_pressed", grab_hi)
# ---------- State ----------
func _set_row_state(eid: String, state: RowState) -> void:
if not rows.has(eid):
return
(rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[state])
var parts: Dictionary = _row_parts[eid]
var num: Label = parts["num"]
if num:
num.add_theme_color_override("font_color", Style.INK if state == RowState.LIT else Style.MUTED)
var text: RichTextLabel = parts["text"]
if text:
RichText.set_fonts(text, 16, true, state == RowState.LIT)
## Re-renders a Play-mode row's text (it shows the rolled text while lit).
func _update_row_text(eid: String) -> void:
var parts: Dictionary = _row_parts.get(eid, {})
var text: RichTextLabel = parts.get("text")
if text:
var want := _row_text(parts["entry"])
if text.text != want:
text.text = want
func _apply_style() -> void:
var s := _style_normal
if _drop_target:
s = _style_drop
elif _rolling:
s = _style_rolling
elif _dragging:
s = _style_dragging
add_theme_stylebox_override("panel", s)
func _shrink() -> void:
size = Vector2(card_width(), 0)
func card_width() -> float:
return BUILD_WIDTH if main.mode == Main.Mode.BUILD else WIDTH
func set_rolling(on: bool) -> void:
_rolling = on
if is_instance_valid(_die_icon):
_die_icon.spinning = on
_apply_style()
func set_drop_target(on: bool) -> void:
_drop_target = on
_apply_style()
func flick_random() -> void:
clear_flick()
if rows.is_empty():
return
var keys := rows.keys()
_flick_id = keys[main.rng.randi_range(0, keys.size() - 1)]
_set_row_state(_flick_id, RowState.FLICK)
func clear_flick() -> void:
if _flick_id != "":
_set_row_state(_flick_id, RowState.LIT if main.is_entry_lit(table.id, _flick_id) else RowState.NORMAL)
_flick_id = ""
func set_more_text(text: String) -> void:
if _more_label:
_more_label.text = text
## Updates highlights after a roll. Collapsed cards rebuild so the rolled result shows.
func refresh_lit() -> void:
update_deck()
if table.collapsed:
var want: Array = []
for e in table.entries:
if main.is_entry_lit(table.id, e.id):
want.append(e.id)
if want != rows.keys():
rebuild()
elif _more_label:
_more_label.text = _more_text()
return
for eid in rows:
_update_row_text(eid)
_set_row_state(eid, RowState.LIT if main.is_entry_lit(table.id, eid) else RowState.NORMAL)
## Scrolls a long list so the given result sits in the middle.
func reveal(eid: String) -> void:
if list_scroll == null or not rows.has(eid):
return
var row: Control = rows[eid]
list_scroll.scroll_vertical = int(row.position.y + 6.0 - list_scroll.size.y / 2.0 + row.size.y / 2.0)
func hidden_has_pipes() -> bool:
for e in table.entries:
if not rows.has(e.id) and (not e.pipes.is_empty() or not main.ref_targets_for(e).is_empty()):
return true
return false
# ---------- Geometry (world coordinates) ----------
func inlet_point() -> Vector2:
return Vector2(position.x, position.y + INLET_Y)
## Where a pipe leaves this card for an entry: its row, or the "more" row when the
## entry is hidden in a collapsed card. Rows scrolled out of a long list clamp to
## its edge. Returns {} if there's nowhere to anchor.
func anchor_for(eid: String) -> Dictionary:
var row: Control = rows.get(eid, more_row)
if row == null or not row.is_inside_tree():
return {}
var to_world := main.board.world.get_global_transform().affine_inverse()
var r := row.get_global_rect()
var y := (to_world * (r.position + Vector2(0, r.size.y / 2.0))).y
var shown := true
if list_scroll != null and rows.has(eid):
var sr := list_scroll.get_global_rect()
var top := (to_world * sr.position).y + 14.0
var bottom := (to_world * sr.end).y - 14.0
shown = y >= top - 4.0 and y <= bottom + 4.0
y = clampf(y, top, bottom)
return {"pos": Vector2(position.x + size.x, y), "visible": shown}
# ---------- Input ----------
func _gui_input(ev: InputEvent) -> void:
# Clicks on the card body shouldn't pan the board; the wheel still passes through.
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
accept_event()
func _on_header_input(ev: InputEvent, header: Control) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
if mb.pressed:
main.details().hide_for()
_dragging = true
_drag_offset = main.board.world_mouse() - position
get_parent().move_child(self, -1)
else:
_dragging = false
main.mark_dirty()
_apply_style()
header.accept_event()
return
var mm := ev as InputEventMouseMotion
if mm and _dragging:
var p := main.board.world_mouse() - _drag_offset
position = Vector2(maxf(10.0, roundf(p.x)), maxf(10.0, roundf(p.y)))
table.position = position
header.accept_event()

1
ui/table_card.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://d3m72ntlmi6t6

347
ui/table_settings_dialog.gd Normal file
View file

@ -0,0 +1,347 @@
class_name TableSettingsDialog
extends ModalCard
## Build-mode editor for one table's name, details, tags, type and card mode.
## The editing rules live in static functions (apply_settings and friends) so
## they can be tested without a window.
signal applied(settings: Dictionary)
const COLORS := [
["Red", Color("#a33a2c")],
["Copper", Color("#b8703a")],
["Green", Color("#2f6b4f")],
["Blue", Color("#2f5d8a")],
["Purple", Color("#6b3f8a")],
]
var table: RollTable
var _name: LineEdit
var _details: TextEdit
var _preview: RichTextLabel
var _tags: LineEdit
var _dice: LineEdit
var _dice_row: Control
var _type_note: Label
var _problem: Label
var _deck_block: Control
var _ranged := false
var _card_mode := false
var _deck_empty := "reshuffle"
func _init(p_table: RollTable = null) -> void:
super._init("Table settings", 560.0)
table = p_table
_ranged = table.is_ranged()
_card_mode = table.card_mode
_deck_empty = table.deck_empty
_build()
func _build() -> void:
_name = LineEdit.new()
_name.text = table.name
_name.placeholder_text = "Table name"
style_line_edit(_name)
_name.text_changed.connect(func(_t: String) -> void: _refresh())
body.add_child(field("Name", _name))
_details = TextEdit.new()
_details.text = table.details
_details.placeholder_text = "What this table is for. BBCode is allowed."
_details.custom_minimum_size.y = 84
_details.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
style_text_edit(_details)
_details.text_changed.connect(_refresh)
var tools := HBoxContainer.new()
tools.add_theme_constant_override("separation", 6)
tools.add_child(_tool_button("B", "Bold", func() -> void: _wrap_selection("[b]", "[/b]")))
tools.add_child(_tool_button("I", "Italic", func() -> void: _wrap_selection("[i]", "[/i]")))
var color := make_button("Color ▾", "plain")
color.pressed.connect(func() -> void: _color_menu(color))
color.add_theme_font_size_override("font_size", 14)
tools.add_child(color)
var dbox := VBoxContainer.new()
dbox.add_theme_constant_override("separation", 6)
dbox.add_child(section("Details"))
dbox.add_child(tools)
dbox.add_child(_details)
_preview = RichTextLabel.new()
_preview.bbcode_enabled = true
_preview.fit_content = true
_preview.scroll_active = false
_preview.custom_minimum_size.y = 24
var pbox := PanelContainer.new()
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
pbox.add_child(_preview)
dbox.add_child(pbox)
body.add_child(dbox)
_tags = LineEdit.new()
_tags.text = ", ".join(table.tags)
_tags.placeholder_text = "loot, treasure, magic"
style_line_edit(_tags)
body.add_child(field("Tags (comma-separated)", _tags))
var type_box := VBoxContainer.new()
type_box.add_theme_constant_override("separation", 6)
type_box.add_child(section("Table type"))
type_box.add_child(segmented(["Plain", "Ranged (dice)"], 1 if _ranged else 0, func(i: int) -> void:
_ranged = i == 1
_refresh()
))
_dice = LineEdit.new()
_dice.text = table.dice
_dice.placeholder_text = "1d100"
_dice.custom_minimum_size.x = 140
style_line_edit(_dice)
_dice.size_flags_horizontal = SIZE_SHRINK_BEGIN
_dice.text_changed.connect(func(_t: String) -> void: _refresh())
var drow := HBoxContainer.new()
drow.add_theme_constant_override("separation", 10)
var dl := Style.make_label("Dice", Style.body(), 15, Style.INK)
dl.size_flags_vertical = SIZE_SHRINK_CENTER
drow.add_child(dl)
drow.add_child(_dice)
var eg := note("e.g. 1d100, 2d6, 1d8+2")
eg.size_flags_vertical = SIZE_SHRINK_CENTER
drow.add_child(eg)
_dice_row = drow
type_box.add_child(drow)
_type_note = note("")
type_box.add_child(_type_note)
_problem = note("", Style.WARN_INK)
type_box.add_child(_problem)
body.add_child(type_box)
var card_box := VBoxContainer.new()
card_box.add_theme_constant_override("separation", 6)
card_box.add_child(section("Card mode"))
card_box.add_child(segmented(["Off", "On"], 1 if _card_mode else 0, func(i: int) -> void:
_card_mode = i == 1
_refresh()
))
card_box.add_child(note("Entries are dealt like cards, without repeats, until the deck runs out."))
var deck := VBoxContainer.new()
deck.add_theme_constant_override("separation", 6)
deck.add_child(section("When the deck runs out"))
deck.add_child(segmented(["Reshuffle", "Stop"], 1 if _deck_empty == "stop" else 0, func(i: int) -> void:
_deck_empty = "stop" if i == 1 else "reshuffle"
_refresh()
))
_deck_block = deck
card_box.add_child(deck)
body.add_child(card_box)
add_button("Close", "plain", close)
add_button("Apply", "primary", _on_apply)
_refresh()
func _tool_button(text: String, tip: String, on_press: Callable) -> Button:
var b := make_button(text, "plain")
b.tooltip_text = tip
b.custom_minimum_size.x = 36
b.add_theme_font_size_override("font_size", 14)
b.pressed.connect(on_press)
return b
func _color_menu(anchor: Control) -> void:
var pm := PopupMenu.new()
style_popup(pm)
for i in COLORS.size():
pm.add_item(COLORS[i][0], i)
pm.id_pressed.connect(func(id: int) -> void:
_wrap_selection("[color=%s]" % (COLORS[id][1] as Color).to_html(false), "[/color]")
)
pm.popup_hide.connect(pm.queue_free)
add_child(pm)
pm.popup(Rect2i(Vector2i(anchor.get_screen_position()) + Vector2i(0, int(anchor.size.y)), Vector2i(0, 0)))
## Wraps the selected text in the tags, or inserts an empty pair at the caret.
func _wrap_selection(open: String, close_tag: String) -> void:
var r := wrap_text(_details.text, _selection_range(), open, close_tag)
_details.text = r["text"]
_set_caret_at_offset(int(r["caret"]))
_details.grab_focus()
_refresh()
func _selection_range() -> Vector2i:
if _details.has_selection():
return Vector2i(_offset_of(_details.get_selection_from_line(), _details.get_selection_from_column()),
_offset_of(_details.get_selection_to_line(), _details.get_selection_to_column()))
var c := _offset_of(_details.get_caret_line(), _details.get_caret_column())
return Vector2i(c, c)
func _offset_of(line: int, col: int) -> int:
var off := 0
for i in line:
off += _details.get_line(i).length() + 1
return off + col
func _set_caret_at_offset(off: int) -> void:
var line := 0
while line < _details.get_line_count() - 1 and off > _details.get_line(line).length():
off -= _details.get_line(line).length() + 1
line += 1
_details.set_caret_line(line)
_details.set_caret_column(clampi(off, 0, _details.get_line(line).length()))
func settings() -> Dictionary:
return {
"name": _name.text, "details": _details.text, "tags": _tags.text,
"ranged": _ranged, "dice": _dice.text.strip_edges(),
"card_mode": _card_mode, "deck_empty": _deck_empty,
}
func _refresh() -> void:
if _preview == null:
return
var det := _details.text
_preview.text = Formatter.close_open_tags(det) if det.strip_edges() != "" else "[color=#69726b]Preview appears here.[/color]"
_dice_row.visible = _ranged
_deck_block.visible = _card_mode
var s := settings()
var dice_ok := not _ranged or Dice.is_valid_text(s["dice"])
_dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK)
var msgs := PackedStringArray()
if _ranged and not table.is_ranged():
msgs.append("Each entry gets a range sized by its weight; adjust them on the card.")
if _ranged and extra_pipe_count(table) > 0:
msgs.append("A range takes one pipe, so extra pipes on an entry will be dropped.")
if not _ranged and table.is_ranged():
msgs.append("Ranges are removed; entries become plain picks.")
_type_note.text = " ".join(msgs)
_type_note.visible = not msgs.is_empty()
var problem := ""
if not dice_ok:
problem = "“%s” is not a valid dice expression." % s["dice"]
else:
var clone := RollTable.from_dict(table.to_dict())
apply_settings(clone, s)
problem = clone.range_problems()
_problem.text = problem
_problem.visible = problem != ""
if is_inside_tree():
_fit()
func _on_apply() -> void:
var s := settings()
var r := apply_settings(table, s)
if not r["ok"]:
_problem.text = r["error"]
_problem.visible = true
return
applied.emit(r)
close()
# ---------- Pure editing logic ----------
## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the
## pair. Returns {text, caret}: the caret sits inside an inserted pair, or
## after the closing tag of a wrapped selection.
static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary:
var a := clampi(mini(sel.x, sel.y), 0, text.length())
var b := clampi(maxi(sel.x, sel.y), 0, text.length())
var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b)
var caret := a + open.length() if a == b else b + open.length() + close_tag.length()
return {"text": out, "caret": caret}
## "a, b ,, a" -> ["a", "b"].
static func parse_tags(text: String) -> Array[String]:
var out: Array[String] = []
for part in text.split(","):
var t := part.strip_edges()
if t != "" and not out.has(t):
out.append(t)
return out
## Number of pipes beyond the first, summed over entries (lost when going ranged).
static func extra_pipe_count(t: RollTable) -> int:
var n := 0
for e in t.entries:
n += maxi(0, e.pipes.size() - 1)
return n
## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode,
## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice
## expression nothing is changed. deck_reset says the card deck no longer fits
## (type, dice or card mode changed), so a saved deck should be cleared.
static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
var ranged: bool = s.get("ranged", false)
var dice := str(s.get("dice", t.dice)).strip_edges()
if ranged and not Dice.is_valid_text(dice):
return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false}
var was_ranged := t.is_ranged()
var old_dice := t.dice
var old_card := t.card_mode
var new_name := str(s.get("name", t.name)).strip_edges()
if new_name != "":
t.name = new_name
t.details = str(s.get("details", t.details))
t.tags = parse_tags(str(s.get("tags", "")))
t.card_mode = bool(s.get("card_mode", t.card_mode))
t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle"
if ranged:
t.dice = dice
if not was_ranged:
assign_ranges(t)
elif was_ranged:
drop_ranges(t)
var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
return {"ok": true, "error": "", "deck_reset": deck_reset}
## Gives entries ranges on the table's dice, sized by weight (at least one
## value each while there is room). Entries of weight 0 get no range. Each
## entry keeps only its first pipe, since a range takes one pipe.
static func assign_ranges(t: RollTable) -> void:
var d := t.dice_obj()
var lo := d.min_value()
var hi := d.max_value()
var live: Array[TableEntry] = []
var total := 0
for e in t.entries:
e.has_range = false
if e.weight > 0:
live.append(e)
total += e.weight
while e.pipes.size() > 1:
e.remove_pipe(e.pipes[e.pipes.size() - 1])
var span := hi - lo + 1
var cum := 0
var prev := lo - 1
for i in live.size():
var e := live[i]
if prev >= hi:
break
cum += e.weight
var end := lo - 1 + roundi(float(span) * cum / total)
end = mini(end, hi - (live.size() - 1 - i))
end = clampi(maxi(end, prev + 1), prev + 1, hi)
if i == live.size() - 1:
end = hi
e.has_range = true
e.range_lo = prev + 1
e.range_hi = end
prev = end
static func drop_ranges(t: RollTable) -> void:
for e in t.entries:
e.has_range = false
e.range_lo = 1
e.range_hi = 1

View file

@ -0,0 +1 @@
uid://cql8vbrr3s6ti

Some files were not shown because too many files have changed in this diff Show more