Compare commits

..

No commits in common. "0367d366478bfe4d2afe06b2c354e9a8a68d2109" and "14a0b6e6a4a37edcdbc535c7130aacb5666494a0" have entirely different histories.

40 changed files with 369 additions and 4446 deletions

View file

@ -36,11 +36,6 @@ godot --path .
headline when a chain reaches them. Results can carry effects (`@hp -= 2`), edited with headline when a chain reaches them. Results can carry effects (`@hp -= 2`), edited with
the **ƒ** button in Build mode. The tray's Variables tab lists every variable, with the **ƒ** button in Build mode. The tray's Variables tab lists every variable, with
**Reset all…**. Try `examples/logic_demo.json` (Board ▾ → Import). **Reset all…**. Try `examples/logic_demo.json` (Board ▾ → Import).
- **Branching:** click a pipe in Build mode to give it an **Only if** condition
(`@str >= 8`), or mark it **Otherwise** so it runs only when none of that result's
conditions are true. All of a result's conditions and pipe counts are checked once, before
any pipe runs, and only the pipes taken light up. A **Router** card (+ Table ▾) lists cases
("if @species = "Aslan"", "if @str >= 10", "Otherwise") and takes the first true one.
- **Collections:** the switcher in the top bar holds separate sets of tables. Build mode's - **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. **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 - **Ranged tables** (like *Wilderness Travel*) roll a d100 where each range's size sets its
@ -63,40 +58,7 @@ godot --path .
Templates live in `user://templates/` and are shared by every collection; the list can Templates live in `user://templates/` and are shared by every collection; the list can
rename, delete, export and import them. rename, delete, export and import them.
- **Moving around:** drag the felt to pan, use the mouse wheel to scroll (Shift for sideways), - **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. Zoom goes out far enough Ctrl+wheel or pinch to zoom, and **Fit** to see every table.
(8%) to fit a board of several hundred cards; that far out, cards show as plain cards with
their title line and group names are written large.
- **Search** (top bar, or **Ctrl+F**) finds cards by name, result text, details, choice
prompts, variable names and group names, ignoring case, accents and BBCode. ↑/↓ pick a
result, Enter or a click jumps to it, Esc closes. Jumping opens the card's group if it's
collapsed (and says so), scrolls a long list to the result, centres the card at a readable
zoom and flashes a ring around it.
- **Map** (beside Fit, or **M**) shows an overview in the corner: groups, cards, lit cards in
brass and the part in view. Click or drag on it to move there. It starts off in Play and
on in Build; the choice is remembered for each mode.
- **Arrange ▾ → Pack collapsed groups** (Build) moves collapsed groups, and the cards and
open groups between them, together to close the gaps collapsed blocks leave, keeping
their order left to right and top to bottom (undo from the toast). Expanding a group
whose frame would now cover its neighbours shifts the blocks to its right further right
and the rows below it further down, just enough to clear it (also with undo).
- **Big boards:** cards inside collapsed groups aren't built until their group opens, and
the board only redraws its pipes and ports when something changes, so an 800-card board
with its groups collapsed opens in well under a second.
**Test board** (Build mode, top bar or **Board ▾**) rolls the board many times to find
problems before you play it. Pick a start card (by default one nothing pipes into, or the last
one you rolled), 100, 500 or 1000 runs, and whether the simulated player answers choices at
random or prefers options matching a regular expression, then **Run** (it shows progress and
can be cancelled; the app stays responsive). The report has a summary line and collapsible
lists: **Problems** (static checks: bad expressions and effects, range gaps and overlaps,
pipes to missing tables, endless cycles, choice cards with no options), **Errors** (effect and
expression errors while rolling, unset variables, runs stopped by the action limit), **Dead
ends** (rolls that stopped, such as "No result for 7"), tables **Never reached** and entries
**Never chosen**. Click any line to jump to that card (the dialog closes; reopen it to see the
same report again), **Copy report** puts it on the clipboard as text. Every run starts with
empty variables and decks of its own, so your saved variables and decks are never touched. The
logic is `core/board_tester.gd` (`BoardTester`); `tools/simulate_board.gd` is its command-line
front end (`--board=<json> --start=<id> --runs=N [--prefer=<regex>] [--check]`).
Collections save automatically to `user://collections/<id>.json`, and card draws, saved Collections save automatically to `user://collections/<id>.json`, and card draws, saved
variables and roll history to `user://state/state.json` (on Linux, under variables and roll history to `user://state/state.json` (on Linux, under
@ -133,18 +95,12 @@ the first questions and leaves the next pop-up open; `--menu=add`, `--open-setti
`--edit-effects=<id>`, `--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the `--edit-effects=<id>`, `--demo-long=<n>` (a chain of n steps) and `--confirm-reset` show the
rest. rest.
Test board: `--test-board` opens the dialog, `--test-board-run=<runs>` also starts a run.
Groups and templates: `--select=<id>,<id>`, `--group-selected[=<name>]`, `--collapse-groups`, Groups and templates: `--select=<id>,<id>`, `--group-selected[=<name>]`, `--collapse-groups`,
`--expand-groups`, `--toggle-group=<id>`, `--group-menu`, `--drag-demo`, `--templates[=<search>]`, `--expand-groups`, `--toggle-group=<id>`, `--group-menu`, `--drag-demo`, `--templates[=<search>]`,
`--insert-form=builtin:2d-check`, `--insert-template=<id> --template-values=skill=pilot|target=8`, `--insert-form=builtin:2d-check`, `--insert-template=<id> --template-values=skill=pilot|target=8`,
`--save-template=<table>`, `--save-group-template=first`, `--view=<x>,<y>[,<zoom>]`, `--fit` and `--save-template=<table>`, `--save-group-template=first`, `--view=<x>,<y>[,<zoom>]`, `--fit` and
`--clear-result`. `--clear-result`.
Navigation: `--search=<text>` (the search panel with results), `--focus=<table id>[:<entry id>]`,
`--minimap` / `--no-minimap`, `--pack` (Build), and `--perf` (prints load time and idle and
panning frame times with vsync off, then quits; `--perf-layers` adds a per-layer breakdown).
This uses the sample board and doesn't save anything. `tools/test_window.sh` runs the game 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 under the window class "TableTower Test" (via a temporary `override.cfg`), which a KWin
window rule keeps in the background without focus. window rule keeps in the background without focus.

View file

@ -1,493 +0,0 @@
class_name BoardTester
extends RefCounted
## Tests a board without a window: static checks (bad expressions and effects,
## range gaps, pipes to missing tables, endless cycles ...) and a simulation
## that rolls a start table many times, answering every choice card at random,
## then reports what happened (see docs/LOGIC.md and the README).
##
## Use from a coroutine, in slices, so a UI stays responsive:
## var t := BoardTester.new(board, "start", {"runs": 500, "seed": 1})
## while not t.is_done():
## await t.run_batch(10)
## var report := t.report()
##
## Every run gets its own empty variables and decks, so the caller's saved
## variables and decks are never read or changed. tools/simulate_board.gd is
## the command-line front end.
var board: TowerBoard
var start := ""
var runs_total := 1
var runs_done := 0
var _rng := RandomNumberGenerator.new()
var _answer_rng := RandomNumberGenerator.new()
var _prefer: RegEx = null
var _max_actions := RollContext.DEFAULT_MAX_ACTIONS
var _base_vars := {}
var _cancelled := false
var _completed := 0
var _halted := {}
var _actions: Array[int] = []
var _prompts_total := 0
var _errors := {} # key -> {table, table_id, entry, entry_id, text, count}
var _dead_ends := {} # key -> {table, table_id, text, count}
var _markers := {} # key -> {table, table_id, entry, entry_id, text, count}
var _table_hits := {} # table id -> count
var _entry_hits := {} # "table:entry" -> count
var _sample_sheet := ""
var _sample_vars := {}
var _sample_halted := ""
var _longest := {"actions": -1, "run": 0, "top": []}
var _track := {} # name -> {min, max, sum, n}
## opts: runs (int), seed (int), prefer (regex String, may be ""), max_actions
## (int), track (Array of variable names), vars (Dictionary every run starts
## from a deep copy of; default empty).
func _init(p_board: TowerBoard, p_start: String, opts: Dictionary = {}) -> void:
board = p_board
start = p_start
runs_total = maxi(1, int(opts.get("runs", 100)))
_rng.seed = int(opts.get("seed", 1))
_answer_rng.seed = _rng.seed * 7919 + 17
var pat := str(opts.get("prefer", ""))
if pat != "":
_prefer = RegEx.create_from_string("(?i)" + pat)
_max_actions = int(opts.get("max_actions", RollContext.DEFAULT_MAX_ACTIONS))
_base_vars = opts.get("vars", {})
for name: String in opts.get("track", []):
_track[name.strip_edges().trim_prefix("@")] = {"min": INF, "max": -INF, "sum": 0.0, "n": 0}
func is_done() -> bool:
return _cancelled or runs_done >= runs_total
func cancel() -> void:
_cancelled = true
func was_cancelled() -> bool:
return _cancelled
## Does up to `k` more runs; returns how many it did.
func run_batch(k: int) -> int:
var did := 0
while did < k and not is_done():
await _one_run(runs_done)
runs_done += 1
did += 1
return did
## All the remaining runs in one go.
func run_all() -> void:
while not is_done():
await run_batch(25)
## Convenience: every run, then the report.
static func simulate(p_board: TowerBoard, p_start: String, opts: Dictionary = {}) -> Dictionary:
var t := BoardTester.new(p_board, p_start, opts)
await t.run_all()
return t.report()
func _one_run(run: int) -> void:
var vars: Dictionary = _base_vars.duplicate(true)
var ctx := Roller.new_context(board, _rng, vars, {})
ctx.max_actions = _max_actions
var counter := [0]
ctx.prompt = func(req: Dictionary) -> Variant:
counter[0] += 1
var texts: Array = [str(req.get("prompt", ""))]
for o: Dictionary in req.get("options", []):
texts.append(str(o.get("text", "")))
for txt: String in texts:
for m in _marker_re().search_all(txt):
var what := Formatter.strip_tags(m.get_string())
var tid := str(req.get("table_id", ""))
var mk := tid + ":prompt|" + what
if not _markers.has(mk):
_markers[mk] = {"table": "%s (%s)" % [Formatter.strip_tags(str(req.get("title", ""))), tid], "table_id": tid,
"entry": "(prompt)", "entry_id": "", "text": what, "count": 0}
_markers[mk]["count"] += 1
return answer(req, _answer_rng, _prefer)
var root: Dictionary = await Roller.roll_async(board, start, ctx)
_prompts_total += counter[0]
_actions.append(ctx.actions)
if ctx.halted == "":
_completed += 1
else:
var why := "Action limit" if ctx.halted.begins_with("Stopped after") else ctx.halted
_halted[why] = int(_halted.get(why, 0)) + 1
for name: String in _track:
var v: Variant = Expr.to_value((vars.get(name, {}) as Dictionary).get("value") if vars.get(name) is Dictionary else null)
if v is int or v is float:
var tr: Dictionary = _track[name]
tr["min"] = minf(tr["min"], v)
tr["max"] = maxf(tr["max"], v)
tr["sum"] += v
tr["n"] += 1
var run_hits := {}
for st: Dictionary in Roller.flatten(root, []):
var tid := str(st.get("table_id", ""))
run_hits[tid] = int(run_hits.get(tid, 0)) + 1
var eid := str(st.get("entry_id", ""))
var tname := Formatter.strip_tags(str(st.get("table", "")))
if st.get("stop", false):
if not st.get("limit", false) and not st.get("cancelled", false):
var dk := tid + "|" + str(st.get("text", ""))
if not _dead_ends.has(dk):
_dead_ends[dk] = {"table": "%s (%s)" % [tname, tid], "table_id": tid,
"text": Formatter.strip_tags(str(st.get("text", ""))), "count": 0}
_dead_ends[dk]["count"] += 1
continue
_table_hits[tid] = int(_table_hits.get(tid, 0)) + 1
if eid != "" and not st.has("pass") and not st.has("after"):
_entry_hits[tid + ":" + eid] = int(_entry_hits.get(tid + ":" + eid, 0)) + 1
elif st.has("pass"):
_entry_hits[tid + ":" + _loop_entry_id(board, tid, 0)] = 1
elif st.has("after"):
_entry_hits[tid + ":" + _loop_entry_id(board, tid, 1)] = 1
for l: Variant in st.get("effects", []):
if l is Dictionary and (l as Dictionary).get("error", false):
var text := str((l as Dictionary).get("text", ""))
var ek := tid + ":" + eid + "|" + text
if not _errors.has(ek):
_errors[ek] = {"table": "%s (%s)" % [tname, tid], "table_id": tid,
"entry": _entry_label(board, tid, eid), "entry_id": eid, "text": text, "count": 0}
_errors[ek]["count"] += 1
for m in _marker_re().search_all(str(st.get("text", ""))):
var what := Formatter.strip_tags(m.get_string())
var mk := tid + ":" + eid + "|" + what
if not _markers.has(mk):
_markers[mk] = {"table": "%s (%s)" % [tname, tid], "table_id": tid,
"entry": _entry_label(board, tid, eid), "entry_id": eid, "text": what, "count": 0}
_markers[mk]["count"] += 1
if ctx.actions > int(_longest["actions"]):
var top: Array = []
for k: String in run_hits:
top.append({"table": k, "count": run_hits[k]})
top = _sorted_by_count(top).slice(0, 8)
_longest = {"actions": ctx.actions, "run": run + 1, "top": top}
if run == runs_total - 1 or (_sample_sheet == "" and ctx.halted == ""):
var sheet := Roller.last_sheet(root)
if not sheet.is_empty():
_sample_sheet = Formatter.strip_tags(str(sheet.get("summary", "")))
_sample_vars = vars.duplicate(true)
_sample_halted = ctx.halted
## The report so far (also fine mid-run, or after cancel()). Keys: runs
## (done so far), runs_planned, cancelled, start, completed, halted {reason:
## count}, actions {max, mean, p95}, longest {actions, run, top}, track,
## prompts_mean, errors [{table, table_id, entry, entry_id, text, count}],
## dead_ends [{table, table_id, text, count}], unset_markers (same shape as
## errors; unset {@var?}, missing [[table]] and failed {= expr} markers),
## unreached [table ids], unchosen {table id: [entry texts]}, unchosen_ids
## {table id: [entry ids]}, table_hits, sample_sheet, sample_vars,
## sample_halted.
func report() -> Dictionary:
var runs := maxi(1, runs_done)
var unreached: Array[String] = []
var unchosen := {}
var unchosen_ids := {}
if runs_done > 0:
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE:
continue
if not _table_hits.has(t.id):
unreached.append(t.id)
continue
var missing: Array[String] = []
var ids: Array[String] = []
for e in t.entries:
if t.kind == RollTable.KIND_ROLL and not t.can_come_up(e):
continue
if not _entry_hits.has(t.id + ":" + e.id):
missing.append(Formatter.strip_tags(e.text).substr(0, 60))
ids.append(e.id)
if not missing.is_empty():
unchosen[t.id] = missing
unchosen_ids[t.id] = ids
var sorted_actions := _actions.duplicate()
sorted_actions.sort()
var total := 0
for a in _actions:
total += a
var p95 := 0
var amax := 0
if not sorted_actions.is_empty():
p95 = sorted_actions[clampi(ceili(0.95 * sorted_actions.size()) - 1, 0, sorted_actions.size() - 1)]
amax = sorted_actions.back()
return {
"runs": runs_done,
"runs_planned": runs_total,
"cancelled": _cancelled,
"start": start,
"completed": _completed,
"halted": _halted.duplicate(),
"actions": {"max": amax, "mean": float(total) / runs, "p95": p95},
"longest": _longest.duplicate(true),
"track": _track.duplicate(true),
"prompts_mean": float(_prompts_total) / runs,
"errors": _sorted_by_count(_errors.values()),
"dead_ends": _sorted_by_count(_dead_ends.values()),
"unset_markers": _sorted_by_count(_markers.values()),
"unreached": unreached,
"unchosen": unchosen,
"unchosen_ids": unchosen_ids,
"table_hits": _table_hits.duplicate(),
"sample_sheet": _sample_sheet,
"sample_vars": _sample_vars,
"sample_halted": _sample_halted,
}
# ---------- Static checks ----------
## Problems found without rolling anything. Array of {kind, table_id,
## entry_id ("" for the card), table (display name), text}, in board order.
## kinds: expression, effect, range, cycle, missing_pipe, empty_choice, pipes.
static func static_checks(b: TowerBoard) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var add := func(kind: String, t: RollTable, eid: String, text: String) -> void:
out.append({"kind": kind, "table_id": t.id, "entry_id": eid, "table": Formatter.strip_tags(t.name), "text": text})
for t in b.tables:
var expr := func(what: String, src: String, eid: String = "") -> void:
if src.strip_edges() == "":
return
var err := Expr.check(src)
if err != "":
add.call("expression", t, eid, "%s \"%s\": %s" % [what, src, err])
if t.is_expr_dice():
expr.call("Dice", t.dice)
if t.is_ranged():
var rp := t.range_problems()
if rp != "":
add.call("range", t, "", rp)
match t.kind:
RollTable.KIND_LOOP:
expr.call("Loop rule", t.loop_expr)
RollTable.KIND_CHOICE:
if t.choice == "pick" and t.entries.is_empty():
add.call("empty_choice", t, "", "Choice card has no options.")
if t.choice == "number":
expr.call("Minimum", t.min_expr)
expr.call("Maximum", t.max_expr)
_check_braces(t.prompt, func(src: String) -> void: expr.call("Prompt", src))
RollTable.KIND_VARIABLE:
var init := t.initial.strip_edges()
if t.var_type == "number" and init != "" and not init.is_valid_float():
expr.call("Initial value", init)
for e in t.entries:
_check_braces(e.text, func(src: String) -> void: expr.call("Text", src, e.id))
for p in Effects.validate(e.effects):
add.call("effect", t, e.id, "Effect \"%s\": %s" % [p["src"], p["error"]])
for target in e.pipes:
if b.get_table(target) == null:
add.call("missing_pipe", t, e.id, "Pipe to a table that doesn't exist (%s)." % target)
var ce := e.count_expr(target)
if ce != "":
expr.call("Pipe count", ce, e.id)
for id in Roller.endless_cycles(b):
var t := b.get_table(id)
add.call("cycle", t, "", "Can never finish: every result leads back into an endless cycle.")
var roller: GDScript = Roller
var has_lint := false
for m in roller.get_script_method_list():
if m["name"] == "lint_pipes":
has_lint = true
if has_lint:
var lint: Variant = roller.call("lint_pipes", b)
if lint is Array:
for item: Variant in lint:
var t: RollTable = null
var eid := ""
var text := str(item)
if item is Dictionary:
var d: Dictionary = item
t = b.get_table(str(d.get("table_id", d.get("table", ""))))
eid = str(d.get("entry_id", d.get("entry", "")))
text = str(d.get("text", d.get("message", d.get("problem", text))))
if t == null:
t = RollTable.new("", "")
add.call("pipes", t, eid, text)
return out
## Calls `f(src)` for each `{= expr}` in the text.
static func _check_braces(text: String, f: Callable) -> void:
var re := RegEx.create_from_string("\\{=([^}]*)\\}")
for m in re.search_all(text):
f.call(m.get_string(1))
## Tables worth starting a test from: not variable cards, with nothing piping
## into them and nothing referencing them by [[name]]. If `last_rolled` is a
## table it comes first (even if it isn't a root). Ids in board order.
static func start_candidates(b: TowerBoard, last_rolled: String = "") -> Array[String]:
var used := {}
for t in b.tables:
for e in t.entries:
for p in e.pipes:
used[p] = true
for r in Roller.ref_targets(b, e.text):
used[r] = true
for r in Roller.ref_targets(b, t.prompt):
used[r] = true
var out: Array[String] = []
for t in b.tables:
if t.kind != RollTable.KIND_VARIABLE and not used.has(t.id):
out.append(t.id)
var lr := b.get_table(last_rolled)
if lr != null and lr.kind != RollTable.KIND_VARIABLE:
out.erase(lr.id)
out.push_front(lr.id)
return out
# ---------- Answers and report text ----------
## The simulated player's reply to a prompt request (docs/LOGIC.md section 8):
## a random option or Random for a pick (or an option matching `prefer`), a
## random number in range, a short random word for text.
static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant:
match str(req.get("kind", "pick")):
"number":
return rng.randi_range(int(req.get("min", 0)), int(req.get("max", 0)))
"text":
var letters := "abcdefghijklmnopqrstuvwxyz"
var s := ""
for k in rng.randi_range(3, 8):
s += letters[rng.randi_range(0, letters.length() - 1)]
return s.capitalize()
var options: Array = req.get("options", [])
if prefer != null:
for o: Dictionary in options:
if prefer.search(Formatter.strip_tags(str(o.get("text", "")))) != null:
return int(o["index"])
if options.is_empty():
return -1
# Random (-1) is offered beside every option.
var k := rng.randi_range(-1, options.size() - 1)
return -1 if k < 0 else int(options[k]["index"])
## True when no run hit an error, a dead end or the action limit.
static func is_clean(r: Dictionary) -> bool:
return (r["errors"] as Array).is_empty() and (r["dead_ends"] as Array).is_empty() \
and not (r["halted"] as Dictionary).has("Action limit")
## The static problems as text lines (for the CLI's --check and Copy report).
static func format_problems(problems: Array, list: int = 40) -> PackedStringArray:
var out := PackedStringArray()
out.append("Static problems: %d" % problems.size())
for k in mini(list, problems.size()):
var p: Dictionary = problems[k]
var where: String = "%s (%s)" % [p["table"], p["table_id"]]
if str(p["entry_id"]) != "":
where += ", entry " + str(p["entry_id"])
out.append(" %s: %s" % [where, p["text"]])
if problems.size() > list:
out.append(" ... and %d more" % (problems.size() - list))
return out
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
var out := PackedStringArray()
var a: Dictionary = r["actions"]
out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]])
var hl := PackedStringArray()
for k: String in r["halted"]:
hl.append("%s %d" % [k, r["halted"][k]])
out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none"))
out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]])
var lg: Dictionary = r.get("longest", {})
if not (lg.get("top", []) as Array).is_empty():
var parts := PackedStringArray()
for x: Dictionary in lg["top"]:
parts.append("%s %d" % [x["table"], x["count"]])
out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)])
var tr: Dictionary = r.get("track", {})
for name: String in tr:
var t: Dictionary = tr[name]
if int(t["n"]) == 0:
out.append("@%s: never a number" % name)
else:
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]])
_section(out, "Effect / expression errors", r["errors"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
_section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String:
return "%dx %s: %s" % [e["count"], e["table"], e["text"]])
_section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
var un: Array = r["unreached"]
out.append("Tables never reached: %d" % un.size())
for k in mini(list, un.size()):
out.append(" " + str(un[k]))
if un.size() > list:
out.append(" ... and %d more" % (un.size() - list))
var uc: Dictionary = r["unchosen"]
var n_entries := 0
for k: String in uc:
n_entries += (uc[k] as Array).size()
out.append("Entries never chosen: %d in %d reached tables" % [n_entries, uc.size()])
var shown := 0
for k: String in uc:
if shown >= list:
out.append(" ... and %d more tables" % (uc.size() - shown))
break
var items: Array = uc[k]
var names := PackedStringArray()
for x in mini(4, items.size()):
names.append("\"%s\"" % items[x])
out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
shown += 1
if show_sheet:
out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else ""))
out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)")
return "\n".join(out)
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
out.append("%s: %d" % [title, items.size()])
for k in mini(list, items.size()):
out.append(" " + str(fmt.call(items[k])))
if items.size() > list:
out.append(" ... and %d more" % (items.size() - list))
static func _sorted_by_count(list: Array) -> Array:
var out := list.duplicate()
out.sort_custom(func(x: Dictionary, y: Dictionary) -> bool: return int(x["count"]) > int(y["count"]))
return out
static func _entry_label(b: TowerBoard, tid: String, eid: String) -> String:
var t := b.get_table(tid)
if t == null:
return eid
var e := t.find_entry(eid)
return eid if e == null else Formatter.strip_tags(e.text).substr(0, 50)
static func _loop_entry_id(b: TowerBoard, tid: String, index: int) -> String:
var t := b.get_table(tid)
if t == null or t.entries.size() <= index:
return ""
return t.entries[index].id
static var _marker: RegEx = null
static func _marker_re() -> RegEx:
if _marker == null:
_marker = RegEx.create_from_string("\\[url=(?:unset|missing|error):[^\\]]*\\][^\\[]*\\[/url\\]")
return _marker

View file

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

View file

@ -7,8 +7,7 @@ extends RefCounted
## expression) where the probability mass of each range sets its chance. ## expression) where the probability mass of each range sets its chance.
## ##
## Every table has a `kind` (docs/LOGIC.md §1): "roll" (the default), "choice", ## Every table has a `kind` (docs/LOGIC.md §1): "roll" (the default), "choice",
## "loop", "variable", "sheet" or "router", with the per-kind fields below ## "loop", "variable" or "sheet", with the per-kind fields below. Use create()
## (a router's cases are its entries, each with an entry-level `when`). Use create()
## for a well-formed card of each kind. ## for a well-formed card of each kind.
## ##
## Ranged tables also accept a full expression in `dice` ("2d6 + dm(@end)", ## Ranged tables also accept a full expression in `dice` ("2d6 + dm(@end)",
@ -23,10 +22,7 @@ const KIND_CHOICE := "choice"
const KIND_LOOP := "loop" const KIND_LOOP := "loop"
const KIND_VARIABLE := "variable" const KIND_VARIABLE := "variable"
const KIND_SHEET := "sheet" const KIND_SHEET := "sheet"
const KIND_ROUTER := "router" const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET]
const KINDS: Array[String] = [KIND_ROLL, KIND_CHOICE, KIND_LOOP, KIND_VARIABLE, KIND_SHEET, KIND_ROUTER]
## A new router's first case condition (an even chance, so both cases can come up).
const ROUTER_DEFAULT_WHEN := "1d6 >= 4"
const CHOICES: Array[String] = ["pick", "number", "text"] const CHOICES: Array[String] = ["pick", "number", "text"]
const LOOPS: Array[String] = ["times", "while", "until"] const LOOPS: Array[String] = ["times", "while", "until"]
const VAR_TYPES: Array[String] = ["number", "text", "list"] const VAR_TYPES: Array[String] = ["number", "text", "list"]
@ -82,8 +78,7 @@ func _init(p_id: String = "", p_name: String = "") -> void:
## the variable type ("number", "text", "list"). ## the variable type ("number", "text", "list").
## roll: four "Result N" entries · choice pick: three options · ## roll: four "Result N" entries · choice pick: three options ·
## choice number/text: one "Answer" entry · loop: "Each time" and ## choice number/text: one "Answer" entry · loop: "Each time" and
## "Afterwards" · variable: no entries · sheet: one template entry · ## "Afterwards" · variable: no entries · sheet: one template entry.
## router: an "if …" case (when ROUTER_DEFAULT_WHEN) and an "Otherwise" case.
static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable: static func create(p_kind: String, p_id: String, p_name: String, sub: String = "") -> RollTable:
var t := RollTable.new(p_id, p_name) var t := RollTable.new(p_id, p_name)
t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL t.kind = p_kind if KINDS.has(p_kind) else KIND_ROLL
@ -115,23 +110,9 @@ static func create(p_kind: String, p_id: String, p_name: String, sub: String = "
t.initial = "0" if t.var_type == "number" else "" t.initial = "0" if t.var_type == "number" else ""
KIND_SHEET: KIND_SHEET:
t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name)) t.entries.append(TableEntry.new("e1", "[b]%s[/b]" % p_name))
KIND_ROUTER:
var first := TableEntry.new("e1", "if …")
first.when = ROUTER_DEFAULT_WHEN
t.entries.append(first)
t.entries.append(TableEntry.new("e2", "Otherwise"))
return t return t
## Router cards: index of the first case that is an Otherwise case (empty
## `when`), or -1.
func otherwise_index() -> int:
for i in entries.size():
if entries[i].when.strip_edges() == "":
return i
return -1
func is_kind(k: String) -> bool: func is_kind(k: String) -> bool:
return kind == k return kind == k

View file

@ -12,8 +12,7 @@ extends RefCounted
## and "stop": String when the chain couldn't continue (its summary then ## and "stop": String when the chain couldn't continue (its summary then
## explains why). ## explains why).
## Logic-card keys (docs/LOGIC.md), present only when they apply: ## Logic-card keys (docs/LOGIC.md), present only when they apply:
## kind: "choice" | "loop" | "sheet" | "router" (plain roll nodes have no kind) ## kind: "choice" | "loop" | "sheet" (plain roll nodes have no kind)
## case: int, on a router node: the index of the case that matched
## effects: Array of {"text": String, "error": true?}, the effect log ## effects: Array of {"text": String, "error": true?}, the effect log
## answer: the player's answer on a number/text choice (int or String) ## answer: the player's answer on a number/text choice (int or String)
## picked: true when the player picked a pick option; random: true for Random ## picked: true when the player picked a pick option; random: true for Random
@ -36,7 +35,6 @@ const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH
## Most actions one top-level roll may take (matches RollContext). ## Most actions one top-level roll may take (matches RollContext).
const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS const MAX_ACTIONS := RollContext.DEFAULT_MAX_ACTIONS
const CANCELLED := "Cancelled" const CANCELLED := "Cancelled"
const NO_CASE := "No case matched"
enum { OP_ROLL, OP_PIPE, OP_LOOP } enum { OP_ROLL, OP_PIPE, OP_LOOP }
@ -206,8 +204,6 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
await _do_choice(t, f, ctx, stack) await _do_choice(t, f, ctx, stack)
RollTable.KIND_LOOP: RollTable.KIND_LOOP:
_start_loop(t, f, ctx, stack) _start_loop(t, f, ctx, stack)
RollTable.KIND_ROUTER:
await _do_router(t, f, ctx, stack)
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "",
"kind": RollTable.KIND_SHEET} "kind": RollTable.KIND_SHEET}
@ -265,16 +261,12 @@ static func _pick_node(t: RollTable, ctx: RollContext) -> Dictionary:
## The chosen entry happens: its effects run, its text expands (unless ## The chosen entry happens: its effects run, its text expands (unless
## `expand` is false, for answers) and its pipes are queued. `live` renders the ## `expand` is false, for answers) and its pipes are queued. `live` renders the
## text without rolling references (sheet cards). ## text without rolling references (sheet cards).
##
## Before any pipe runs, every pipe's condition and count is worked out once,
## as a snapshot (see pipe_plan()), so what an earlier pipe's subtree does to
## the variables can't change whether or how often a later pipe runs.
static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void: static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Array, expand: bool = true, live: bool = false) -> void:
var t: RollTable = node["table"] var t: RollTable = node["table"]
var e: TableEntry = node["entry"] var e: TableEntry = node["entry"]
var depth := int(f.get("depth", 0)) var depth := int(f.get("depth", 0))
if e.effects.strip_edges() != "": if e.effects.strip_edges() != "":
_log(node, Effects.run(e.effects, ctx, t.id)) node["effects"] = Effects.run(e.effects, ctx, t.id)
if expand: if expand:
ctx.depth = depth + 1 ctx.depth = depth + 1
var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live) var ex: Dictionary = await TextExpander.expand_async(e.text, ctx, live)
@ -290,66 +282,20 @@ static func _enter(node: Dictionary, f: Dictionary, ctx: RollContext, stack: Arr
if save != "": if save != "":
var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"])) var v: Variant = node["answer"] if node.has("answer") else Formatter.to_export_bbcode(str(node["summary"]))
ctx.save(save, v, t.id) ctx.save(save, v, t.id)
# A picked option is saved under the choice's save_as before the pipe for k in range(e.pipes.size() - 1, -1, -1):
# snapshot, so its own pipe conditions can read it. var p := e.pipes[k]
if t.kind == RollTable.KIND_CHOICE and t.save_as != "" and not node.has("answer"): stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": -1, "save": e.save_for(p), "depth": depth})
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
if e.pipes.is_empty():
return
var log: Array = []
var plan := pipe_plan(e, ctx, log)
_log(node, log)
for k in range(plan.size() - 1, -1, -1):
var item: Dictionary = plan[k]
if not item["run"]:
continue
var p: String = item["to"]
stack.append({"op": OP_PIPE, "node": node, "entry": e, "to": p, "left": int(item["count"]), "save": e.save_for(p), "depth": depth})
## Appends effect-log lines to a node's "effects".
static func _log(node: Dictionary, lines: Array) -> void:
if lines.is_empty():
return
if not node.has("effects"):
node["effects"] = []
(node["effects"] as Array).append_array(lines)
## The snapshot of an entry's pipes, taken once after the entry's effects ran
## and its text expanded: one item per pipe, in pipe order,
## {"to": table id, "run": bool, "count": int}.
## - A pipe with a condition ("when") runs only if it's true. An error
## counts as false and adds an error line to `log`.
## - An "otherwise" pipe runs only if none of the entry's conditions was true.
## - Any other pipe always runs.
## Counts are worked out only for pipes that run (0 for the others); an
## expression count's error gives 0 and an error line.
static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = []) -> Array:
var plan: Array = []
var any_true := false
for p in e.pipes:
var w := e.when_for(p)
var run := true
if w != "":
var r := Expr.evaluate(w, ctx)
if r["error"] != "":
log.append({"text": "Pipe condition %s: %s" % [w, r["error"]], "error": true})
run = false
else:
run = Expr.truthy(r["value"])
any_true = any_true or run
plan.append({"to": p, "run": run, "count": 0, "otherwise": w == "" and e.is_otherwise(p)})
for item: Dictionary in plan:
if item["otherwise"]:
item["run"] = not any_true
item.erase("otherwise")
if item["run"]:
item["count"] = e.count_value(str(item["to"]), ctx, log)
return plan
static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void: static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: Array) -> void:
if int(f["left"]) < 0:
var log: Array = []
f["left"] = (f["entry"] as TableEntry).count_value(str(f["to"]), ctx, log)
if not log.is_empty():
var node: Dictionary = f["node"]
if not node.has("effects"):
node["effects"] = []
(node["effects"] as Array).append_array(log)
if int(f["left"]) <= 0: if int(f["left"]) <= 0:
return return
var t := board.get_table(str(f["to"])) var t := board.get_table(str(f["to"]))
@ -360,39 +306,6 @@ static func _do_pipe(board: TowerBoard, f: Dictionary, ctx: RollContext, stack:
stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]}) stack.append({"op": OP_ROLL, "id": f["to"], "parent": f["node"], "save": f["save"], "depth": f["depth"]})
# ---------- Routers ----------
## The index of the first router case whose condition is true (an empty
## condition, the Otherwise case, always matches), or -1. Errors count as
## false and add a line to `log`.
static func route(t: RollTable, ctx: RollContext, log: Array = []) -> int:
for k in t.entries.size():
var w := t.entries[k].when.strip_edges()
if w == "":
return k
var r := Expr.evaluate(w, ctx)
if r["error"] != "":
log.append({"text": "Case %s: %s" % [w, r["error"]], "error": true})
elif Expr.truthy(r["value"]):
return k
return -1
static func _do_router(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var log: Array = []
var k := route(t, ctx, log)
if k < 0:
var stop := _stop(t, NO_CASE, {"kind": RollTable.KIND_ROUTER})
_log(stop, log)
_attach(f, stop, ctx)
return
var node := {"table": t, "index": k, "entry": t.entries[k], "children": [], "summary": "",
"kind": RollTable.KIND_ROUTER, "case": k}
_log(node, log)
_attach(f, node, ctx)
await _enter(node, f, ctx, stack)
# ---------- Loops ---------- # ---------- Loops ----------
static func _repeated(n: int) -> String: static func _repeated(n: int) -> String:
@ -543,6 +456,8 @@ static func _do_choice(t: RollTable, f: Dictionary, ctx: RollContext, stack: Arr
if node.has("stop"): if node.has("stop"):
return return
await _enter(node, f, ctx, stack) await _enter(node, f, ctx, stack)
if t.save_as != "" and ctx.halted == "":
ctx.save(t.save_as, Formatter.strip_tags(str(node["summary"])).strip_edges(), t.id)
static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void: static func _answered(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array, value: Variant, summary: String) -> void:
@ -571,7 +486,7 @@ static func _pick_weighted(t: RollTable, rng: RandomNumberGenerator) -> int:
## Ids of tables that can never finish rolling: every result they can give ## 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 ## leads, through pipes, back into such a table. A table that loops on only
## some of its entries is fine, and so is a pipe whose count is an expression ## some of its entries is fine, and so is a pipe whose count is an expression
## (it may come to 0) or a conditional pipe (it may not run). ## (it may come to 0).
static func endless_cycles(board: TowerBoard) -> Array[String]: static func endless_cycles(board: TowerBoard) -> Array[String]:
var done := {} var done := {}
var changed := true var changed := true
@ -592,7 +507,7 @@ static func endless_cycles(board: TowerBoard) -> Array[String]:
static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool: static func _entry_finishes(e: TableEntry, board: TowerBoard, done: Dictionary) -> bool:
for p in e.pipes: for p in e.pipes:
if e.count_expr(p) != "" or e.is_conditional(p): if e.count_expr(p) != "":
continue continue
if board.get_table(p) != null and not done.has(p): if board.get_table(p) != null and not done.has(p):
return false return false
@ -626,8 +541,7 @@ static func _can_finish(t: RollTable, board: TowerBoard, done: Dictionary) -> bo
## One line of the result tray for a single node. Plain data only, because it ## 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. ## is saved in the roll history. "text" is BBCode with internal markers.
## Logic-card keys (only when they apply): kind, effects (Array of {text, ## Logic-card keys (only when they apply): kind, effects (Array of {text,
## error?}), answer, passes, pass, after, picked, random, limit, cancelled, ## error?}), answer, passes, pass, after, picked, random, limit, cancelled.
## case (router nodes: the matched case's index).
static func step_of(n: Dictionary, depth: int = 0) -> Dictionary: static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
var t: RollTable = n["table"] var t: RollTable = n["table"]
var step := { var step := {
@ -653,7 +567,7 @@ static func step_of(n: Dictionary, depth: int = 0) -> Dictionary:
step["kind"] = n["kind"] step["kind"] = n["kind"]
if n.has("effects"): if n.has("effects"):
step["effects"] = (n["effects"] as Array).duplicate(true) step["effects"] = (n["effects"] as Array).duplicate(true)
for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled", "case"]: for k in ["answer", "passes", "pass", "after", "picked", "random", "limit", "cancelled"]:
if n.has(k): if n.has(k):
step[k] = n[k] step[k] = n[k]
return step return step
@ -791,66 +705,3 @@ static func render_sheet(board: TowerBoard, persistent: Dictionary, t: RollTable
if t.entries.is_empty(): if t.entries.is_empty():
return "" return ""
return TextExpander.render(t.entries[0].text, live_context(board, persistent)) return TextExpander.render(t.entries[0].text, live_context(board, persistent))
# ---------- Lint ----------
## Problems with conditional pipes and router cards, for a board check. Pure:
## nothing is rolled. Each item: {table_id, entry_id ("" for the whole card),
## message}.
## - a pipe condition, or a router case condition, that doesn't parse
## - an entry whose "otherwise" pipe comes before one of its conditional
## pipes (a hint: it still works, since the snapshot is taken first)
## - an "otherwise" pipe on an entry with no conditional pipe (always runs)
## - a router with no cases, or whose Otherwise case isn't the last one
static func lint_pipes(board: TowerBoard) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for t in board.tables:
out.append_array(lint_router(t))
for i in t.entries.size():
var e := t.entries[i]
var first_other := ""
var has_when := false
var warned := false
for p in e.pipes:
var pw := e.when_for(p)
if pw != "":
has_when = true
if Expr.check(pw) != "":
out.append({"table_id": t.id, "entry_id": e.id,
"message": "Pipe condition %s: %s" % [pw, Expr.check(pw)]})
if first_other != "" and not warned:
warned = true
out.append({"table_id": t.id, "entry_id": e.id,
"message": "The otherwise pipe to %s comes before a conditional pipe; put it last so it reads in order" % _table_name(board, first_other)})
elif e.is_otherwise(p) and first_other == "":
first_other = p
if first_other != "" and not has_when:
out.append({"table_id": t.id, "entry_id": e.id,
"message": "The otherwise pipe to %s always runs: no pipe on this entry has a condition" % _table_name(board, first_other)})
return out
## The router part of lint_pipes() for one card (empty for other kinds): no
## cases, an Otherwise case that isn't last, case conditions that don't parse.
static func lint_router(t: RollTable) -> Array[Dictionary]:
var out: Array[Dictionary] = []
if t.kind != RollTable.KIND_ROUTER:
return out
if t.entries.is_empty():
out.append({"table_id": t.id, "entry_id": "", "message": "This router has no cases"})
for i in t.entries.size():
var e := t.entries[i]
var w := e.when.strip_edges()
if w == "":
if i < t.entries.size() - 1:
out.append({"table_id": t.id, "entry_id": e.id,
"message": "The Otherwise case isn't last, so the cases after it can never be chosen"})
elif Expr.check(w) != "":
out.append({"table_id": t.id, "entry_id": e.id, "message": "Case %s: %s" % [w, Expr.check(w)]})
return out
static func _table_name(board: TowerBoard, id: String) -> String:
var t := board.get_table(id)
return Formatter.strip_tags(t.name) if t else id

View file

@ -24,15 +24,6 @@ var pipes: Array[String] = []
var pipe_count: Dictionary = {} var pipe_count: Dictionary = {}
## target table id -> variable name to save the result under (missing = none). ## target table id -> variable name to save the result under (missing = none).
var pipe_save: Dictionary = {} var pipe_save: Dictionary = {}
## target table id -> condition expression: the pipe runs only when it's true
## (docs/LOGIC.md, Conditional pipes). Missing = always.
var pipe_when: Dictionary = {}
## target table id -> true: the pipe runs only when none of this entry's
## conditional pipes did. Ignored while the pipe has a condition.
var pipe_otherwise: Dictionary = {}
## Router cards: this case's condition. "" is the Otherwise case (always
## matches). Ignored on other kinds.
var when: String = ""
var has_range: bool = false var has_range: bool = false
var range_lo: int = 1 var range_lo: int = 1
var range_hi: int = 1 var range_hi: int = 1
@ -107,46 +98,6 @@ func set_pipe_count(target: String, n: Variant) -> void:
pipe_count[target] = k pipe_count[target] = k
## The pipe's condition, or "".
func when_for(target: String) -> String:
return str(pipe_when.get(target, ""))
## True when the pipe is an "otherwise" pipe (and has no condition).
func is_otherwise(target: String) -> bool:
return bool(pipe_otherwise.get(target, false)) and when_for(target) == ""
## True when the pipe has a condition or is an otherwise pipe.
func is_conditional(target: String) -> bool:
return when_for(target) != "" or is_otherwise(target)
## Sets the pipe's condition ("" for none). A condition clears "otherwise".
func set_pipe_when(target: String, expr: String) -> void:
expr = expr.strip_edges()
if expr == "":
pipe_when.erase(target)
else:
pipe_when[target] = expr
pipe_otherwise.erase(target)
func set_pipe_otherwise(target: String, on: bool) -> void:
if on and when_for(target) == "":
pipe_otherwise[target] = true
else:
pipe_otherwise.erase(target)
## True when any of this entry's pipes has a condition or is an otherwise pipe.
func has_conditional_pipes() -> bool:
for p in pipes:
if is_conditional(p):
return true
return false
func set_pipe_save(target: String, name: String) -> void: func set_pipe_save(target: String, name: String) -> void:
name = name.strip_edges() name = name.strip_edges()
if name == "": if name == "":
@ -168,8 +119,6 @@ func remove_pipe(target: String) -> void:
pipes.erase(target) pipes.erase(target)
pipe_count.erase(target) pipe_count.erase(target)
pipe_save.erase(target) pipe_save.erase(target)
pipe_when.erase(target)
pipe_otherwise.erase(target)
func to_dict() -> Dictionary: func to_dict() -> Dictionary:
@ -180,17 +129,13 @@ func to_dict() -> Dictionary:
d["weight"] = weight d["weight"] = weight
if effects != "": if effects != "":
d["effects"] = effects d["effects"] = effects
if when.strip_edges() != "":
d["when"] = when.strip_edges()
if not pipes.is_empty(): if not pipes.is_empty():
var list: Array = [] var list: Array = []
for p in pipes: for p in pipes:
var expr := count_expr(p) var expr := count_expr(p)
var n := count_for(p) var n := count_for(p)
var s := save_for(p) var s := save_for(p)
var w := when_for(p) if expr == "" and n == 1 and s == "":
var other := is_otherwise(p)
if expr == "" and n == 1 and s == "" and w == "" and not other:
list.append(p) list.append(p)
else: else:
var po := {"table": p} var po := {"table": p}
@ -200,10 +145,6 @@ func to_dict() -> Dictionary:
po["count"] = n po["count"] = n
if s != "": if s != "":
po["save_as"] = s po["save_as"] = s
if w != "":
po["when"] = w
elif other:
po["otherwise"] = true
list.append(po) list.append(po)
d["pipes"] = list d["pipes"] = list
if has_range: if has_range:
@ -216,15 +157,12 @@ static func from_dict(d: Dictionary) -> TableEntry:
e.details = str(d.get("details", "")) e.details = str(d.get("details", ""))
e.weight = maxi(0, int(d.get("weight", 1))) e.weight = maxi(0, int(d.get("weight", 1)))
e.effects = str(d.get("effects", "")) e.effects = str(d.get("effects", ""))
e.when = str(d.get("when", "")).strip_edges() if d.get("when") != null else ""
for p: Variant in d.get("pipes", []): for p: Variant in d.get("pipes", []):
if p is Dictionary: if p is Dictionary:
var target := str(p.get("table", "")) var target := str(p.get("table", ""))
if target != "": if target != "":
var c: Variant = p.get("count", 1) var c: Variant = p.get("count", 1)
e.add_pipe(target, c if c is String else int(c), str(p.get("save_as", ""))) e.add_pipe(target, c if c is String else int(c), str(p.get("save_as", "")))
e.set_pipe_when(target, str(p.get("when", "")) if p.get("when") != null else "")
e.set_pipe_otherwise(target, bool(p.get("otherwise", false)))
elif str(p) != "": elif str(p) != "":
e.add_pipe(str(p)) e.add_pipe(str(p))
var r: Variant = d.get("range") var r: Variant = d.get("range")

View file

@ -17,12 +17,10 @@ Every table has a `kind`. Existing tables are `roll`.
| `loop` | Runs its **Each time** entry repeatedly, then its **Afterwards** entry once (§3) | The loop rule and two rows | | `loop` | Runs its **Each time** entry repeatedly, then its **Afterwards** entry once (§3) | The loop rule and two rows |
| `variable` | Never rolled. Declares a variable with a type, a starting value and a description (§5) | The variable's live value | | `variable` | Never rolled. Declares a variable with a type, a starting value and a description (§5) | The variable's live value |
| `sheet` | Prints its template with current values (§6) | The template, rendered live | | `sheet` | Prints its template with current values (§6) | The template, rendered live |
| `router` | Chooses the first of its cases whose condition is true (§3b) | A fork icon, one row per case with its condition |
Every kind except `variable` can be the start of a roll and can be the target of a pipe. Every kind except `variable` can be the start of a roll and can be the target of a pipe.
Every entry, of any kind, can carry **effects** (§5.2) and pipes. Pipes keep their count and Every entry, of any kind, can carry **effects** (§5.2) and pipes. Pipes keep their count and
"save as" options, and a pipe count may now be an expression (`@terms`, `1d3`). A pipe may "save as" options, and a pipe count may now be an expression (`@terms`, `1d3`).
also have a condition, or be an "otherwise" pipe (§3a).
## 2. Choice cards ## 2. Choice cards
@ -58,67 +56,9 @@ The chain variable `i` holds the pass number (1, 2, …) during Each time. A loo
reads "Repeated N times". Pipes may also form cycles (a table piping back to an earlier one). reads "Repeated N times". Pipes may also form cycles (a table piping back to an earlier one).
Both are bounded only by the action limit. Both are bounded only by the action limit.
## 3a. Conditional pipes
A pipe may carry `"when": "<expression>"` (shown as **Only if** in the pipe's pop-up) and/or
`"otherwise": true`. A pipe with a `when` ignores `otherwise`.
When an entry is chosen (rolled, picked, answered, a loop pass, a router case):
1. Its effects run, its text expands, and any "save as" (the pipe's that led here, or a pick
choice's `save_as`) is stored.
2. **The snapshot.** Every `when` condition and every count of the entry's pipes is worked
out once, now, before any pipe runs.
3. The pipes run in list order:
- a pipe with `when` runs only if its condition was true;
- an `otherwise` pipe runs only if none of the entry's `when` pipes was true;
- any other pipe always runs.
So an earlier pipe's subtree can change variables without changing whether, or how many
times, a later pipe on the same entry runs. Pipes are not "else if": two true conditions both
run (use a router, §3b, for first-match). Counts are only worked out for pipes that run; a
skipped pipe's count dice are never rolled.
A condition that fails to evaluate counts as false and adds a red line to the node's effect
log ("Pipe condition …: …"), the way a bad pipe count does. Only the pipes actually taken
light up after a roll. On the board, a conditional pipe has a small diamond at its source
end (hollow for otherwise) and a label such as `if @str >= 8 ×2 → foe` or `otherwise`.
**Change from earlier versions.** Pipe counts used to be evaluated lazily: the second pipe's
count was read only after the first pipe's whole subtree had run, so a branch that changed a
variable could make a later pipe fire too ("both branches fired"). Counts now come from the
snapshot. Also, a pick choice's `save_as` is now stored before the snapshot (it used to be
stored after the option's pipes were queued, which made no difference while counts were
lazy). No existing test changed.
## 3b. Router cards
A router (`kind: "router"`, "Router" in the **+ Table ▾** menu, "if / else if / otherwise")
has no dice. Its entries are **cases**, each with an entry-level `when` expression.
- When the chain reaches it, the cases are checked top to bottom and the **first** true case
is chosen. A case with an empty `when` (shown as **Otherwise**) always matches, so it
should be the last one.
- The chosen case happens exactly like a rolled entry: its effects run, its text expands and
its pipes follow (with the snapshot rule of §3a).
- If no case matches, the node stops with a visible "No case matched". A case condition that
errors counts as false and adds a red line ("Case …: …") to the node.
- It counts as one action. The node and step have `kind: "router"` and `case` (the chosen
case's index). Routers have no ranges, weights or card mode.
- A new router has two cases: "if …" (with the condition `1d6 >= 4`, to be edited) and
"Otherwise". **+ Add case** on the card adds an `if false` case before Otherwise; cases can
be reordered and removed on the card, and their conditions edited there or in the
settings dialog.
`Roller.lint_pipes(board)` lists problems for a board check: `when` or case conditions that
don't parse, an otherwise pipe listed before a `when` pipe on the same entry (a hint: it still
works), an otherwise pipe on an entry with no `when` pipe (it always runs), and routers with
no cases or whose Otherwise case isn't last. Each item is `{table_id, entry_id, message}`.
## 4. Expressions ## 4. Expressions
Expressions appear in loop rules, pipe counts, pipe conditions, router cases, `min`/`max`, Expressions appear in loop rules, pipe counts, `min`/`max`, dice fields and effects. They are
dice fields and effects. They are
evaluated with Godot's `Expression`, after a small rewrite. evaluated with Godot's `Expression`, after a small rewrite.
- **Numbers and text:** `12`, `-3`, `"Aslan"` - **Numbers and text:** `12`, `-3`, `"Aslan"`
@ -192,7 +132,7 @@ step's result.
## 7. Limits ## 7. Limits
- **Actions:** one top-level roll may take at most **10,000 actions**. One action is a table - **Actions:** one top-level roll may take at most **10,000 actions**. One action is a table
being rolled or answered, a router choosing a case, or one loop pass. Past that, the roll stops with "Stopped after being rolled or answered, or one loop pass. Past that, the roll stops with "Stopped after
10,000 actions", and everything up to that point is kept. 10,000 actions", and everything up to that point is kept.
- **Inline references:** `[[refs]]` inside text still nest at most 32 deep. - **Inline references:** `[[refs]]` inside text still nest at most 32 deep.
- **Implementation:** pipes and loops must not use GDScript recursion proportional to chain - **Implementation:** pipes and loops must not use GDScript recursion proportional to chain
@ -222,7 +162,5 @@ Table keys:
Entry keys: Entry keys:
- `effects` (String) - `effects` (String)
- `when` (String, router cases; empty or missing is Otherwise)
Pipe objects may have `"count": "<expression>"`, `"when": "<expression>"` and Pipe objects may have `"count": "<expression>"`.
`"otherwise": true` (left out when the pipe has a `when`).

View file

@ -98,7 +98,7 @@
"details": "One room check per room the player chose, then the way out.", "details": "One room check per room the player chose, then the way out.",
"entries": [ "entries": [
{ "id": "e1", "text": "Room {i}", "pipes": ["room_check"] }, { "id": "e1", "text": "Room {i}", "pipes": ["room_check"] },
{ "id": "e2", "text": "Head back up", "pipes": ["climb"] } { "id": "e2", "text": "Head back up", "pipes": ["way_out"] }
] ]
}, },
{ {
@ -114,25 +114,12 @@
{ "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] } { "id": "e3", "text": "A glinting cache", "effects": "@gold += 2d6\n@loot += \"gem\"", "range": [10, 12] }
] ]
}, },
{
"id": "climb",
"name": "On the way up",
"kind": "router",
"x": 680,
"y": 330,
"details": "Checks the delver's state once, top to bottom: the first case that's true is the one that happens.",
"entries": [
{ "id": "e1", "text": "Carried up by a passing patrol", "when": "@hp <= 0", "effects": "@hp = 1", "pipes": ["report"] },
{ "id": "e2", "text": "Pockets heavy with gold", "when": "@gold >= 12", "details": "The guard at the top has noticed.", "pipes": ["way_out"] },
{ "id": "e3", "text": "Up the stairs", "pipes": ["way_out"] }
]
},
{ {
"id": "way_out", "id": "way_out",
"name": "Way out", "name": "Way out",
"kind": "choice", "kind": "choice",
"prompt": "{@name} has {@gold} gold and {@hp} HP left. How do they leave?", "prompt": "{@name} has {@gold} gold and {@hp} HP left. How do they leave?",
"x": 1000, "x": 680,
"y": 330, "y": 330,
"entries": [ "entries": [
{ "id": "e1", "text": "Sneak past the guard", "details": "Quiet and slow. Luck grows.", "effects": "@luck += 1", "pipes": ["report"] }, { "id": "e1", "text": "Sneak past the guard", "details": "Quiet and slow. Luck grows.", "effects": "@luck += 1", "pipes": ["report"] },
@ -144,7 +131,7 @@
"id": "report", "id": "report",
"name": "Delve report", "name": "Delve report",
"kind": "sheet", "kind": "sheet",
"x": 1320, "x": 1000,
"y": 330, "y": 330,
"entries": [ "entries": [
{ {

View file

@ -10,10 +10,9 @@ extends RefCounted
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode], ## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max], ## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial], entries ## [loop], [loop_expr], [var_name], [var_type], [initial], entries
## entry: id, text, [details], [weight], [range], [effects], [when], [pipes] ## entry: id, text, [details], [weight], [range], [effects], [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>", ## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name, "when": "<expression>", "otherwise": true} ## "save_as": name}
## ("otherwise" is dropped when the pipe has a "when")
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when ## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
## they have their default value. ## they have their default value.
@ -155,8 +154,6 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
ed["details"] = clean.call(str(ed["details"])) ed["details"] = clean.call(str(ed["details"]))
if ed.has("effects"): if ed.has("effects"):
ed["effects"] = clean.call(str(ed["effects"])) ed["effects"] = clean.call(str(ed["effects"]))
if ed.has("when"):
ed["when"] = clean.call(str(ed["when"]))
if ed.has("range"): if ed.has("range"):
var r: Array = ed["range"] var r: Array = ed["range"]
if int(r[0]) > int(r[1]): if int(r[0]) > int(r[1]):
@ -178,8 +175,6 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
np["table"] = target np["table"] = target
if np.has("save_as"): if np.has("save_as"):
np["save_as"] = clean.call(str(np["save_as"])) np["save_as"] = clean.call(str(np["save_as"]))
if np.has("when"):
np["when"] = clean.call(str(np["when"]))
pipes.append(np) pipes.append(np)
else: else:
pipes.append(target) pipes.append(target)
@ -342,9 +337,6 @@ static func _canon_entry(ev: Variant) -> Dictionary:
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else "" var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
if effects.strip_edges() != "": if effects.strip_edges() != "":
e["effects"] = effects e["effects"] = effects
var when := str(ed.get("when", "")).strip_edges() if ed.get("when") != null else ""
if when != "":
e["when"] = when
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", [])) var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = [] var pipes: Array = []
if src_pipes is Array: if src_pipes is Array:
@ -361,11 +353,6 @@ static func _canon_entry(ev: Variant) -> Dictionary:
np["count"] = int(cnt if cnt != null else 1) np["count"] = int(cnt if cnt != null else 1)
if str(p.get("save_as", "")) != "": if str(p.get("save_as", "")) != "":
np["save_as"] = str(p["save_as"]) np["save_as"] = str(p["save_as"])
var pw := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
if pw != "":
np["when"] = pw
elif p.get("otherwise", false) is bool and bool(p.get("otherwise", false)):
np["otherwise"] = true
pipes.append(np) pipes.append(np)
if not pipes.is_empty(): if not pipes.is_empty():
e["pipes"] = pipes e["pipes"] = pipes
@ -406,30 +393,22 @@ static func unique_id(base: String, used: Dictionary) -> String:
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as", ## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
## "count_expr", "when", "otherwise"}. An expression count ("@terms") reads as ## "count_expr"}. An expression count ("@terms") reads as count 1, with the
## count 1, with the expression in "count_expr" ("" otherwise). "when" is the ## expression in "count_expr" ("" otherwise).
## pipe's condition ("" for none); "otherwise" is true only without one.
static func pipe_info(p: Variant) -> Dictionary: static func pipe_info(p: Variant) -> Dictionary:
if p is Dictionary: if p is Dictionary:
var c: Variant = p.get("count", 1) var c: Variant = p.get("count", 1)
var expr := "" var expr := ""
if c is String and _num(c, null) == null and (c as String).strip_edges() != "": if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
expr = (c as String).strip_edges() expr = (c as String).strip_edges()
var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else "" return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr}
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr, return {"table": str(p), "count": 1, "save_as": "", "count_expr": ""}
"when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false))}
return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false}
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon" ## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
## ("×@terms" for an expression count), led by "if <condition>" or ## ("×@terms" for an expression count).
## "otherwise" on a conditional pipe ("if @str >= 8 ×2").
static func pipe_label(info: Dictionary) -> String: static func pipe_label(info: Dictionary) -> String:
var parts: Array[String] = [] var parts: Array[String] = []
if str(info.get("when", "")) != "":
parts.append("if " + str(info["when"]))
elif bool(info.get("otherwise", false)):
parts.append("otherwise")
if str(info.get("count_expr", "")) != "": if str(info.get("count_expr", "")) != "":
parts.append("×" + str(info["count_expr"])) parts.append("×" + str(info["count_expr"]))
elif int(info["count"]) != 1: elif int(info["count"]) != 1:

View file

@ -1,213 +0,0 @@
extends SceneTree
## BoardTester: static checks, simulated runs, isolation from the caller's
## variables and decks, batches, start-table detection, and the Test board
## dialog driven through its methods.
## Run: godot --headless --path . -s res://tests/test_board_tester.gd
var _failures := 0
## Stands in for Main: just enough for the dialog.
class FakeMain extends Control:
var data: TowerBoard
var history: Array = []
var focused: Array = []
func focus_table(table_id: String, entry_id: String = "") -> void:
focused.append([table_id, entry_id])
func _init() -> void:
var b := _board()
# ----- Static checks -----
var probs := BoardTester.static_checks(b)
_check(_has(probs, "effect", "start", "e1"), "a bad effect is found with its table and entry: %s" % str(probs))
_check(_has(probs, "expression", "badexpr", ""), "a bad dice expression is found")
_check(_has(probs, "expression", "pick", "") and _text_has(probs, "Prompt"), "a bad {= } in a prompt is found")
_check(_has(probs, "expression", "loop", "") and _text_has(probs, "Loop rule"), "a bad loop rule is found")
_check(_has(probs, "expression", "start", "e1") and _text_has(probs, "Pipe count"), "a bad pipe count is found")
_check(_has(probs, "range", "gap", "") and _text_has(probs, "No result for 3"), "a range gap is found")
_check(_has(probs, "missing_pipe", "start", "e1"), "a pipe to a missing table is found")
_check(_has(probs, "empty_choice", "empty", ""), "a choice card with no options is found")
_check(_has(probs, "cycle", "ping", ""), "an endless cycle is found")
_check(not _has(probs, "range", "okrange", "") and not _has(probs, "effect", "mine", ""), "good cards give no problems")
# ----- Simulation -----
var caller_vars := {"gold": {"value": 99, "source": "x"}}
var r: Dictionary = await BoardTester.simulate(b, "start", {"runs": 80, "seed": 2, "prefer": "^Gap$"})
_eq(r["runs"], 80, "80 runs done")
_check((r["dead_ends"] as Array).size() >= 1 and str(r["dead_ends"][0]["text"]).contains("No result for 3") and r["dead_ends"][0]["table_id"] == "gap",
"the dead end names its table: %s" % str(r["dead_ends"]))
_check((r["unreached"] as Array).has("island") and not (r["unreached"] as Array).has("start"), "the island is never reached: %s" % str(r["unreached"]))
_check((r["errors"] as Array).size() >= 1 and r["errors"][0]["table_id"] == "start" and r["errors"][0]["entry_id"] == "e1" and str(r["errors"][0]["text"]).contains("nope"),
"the runtime error has table and entry ids: %s" % str(r["errors"]))
_check(r["actions"]["max"] >= r["actions"]["p95"] and r["prompts_mean"] > 0.0, "action and prompt stats exist")
_check(not BoardTester.is_clean(r), "not clean")
# A starting vars dictionary is copied for every run, never changed.
var r2: Dictionary = await BoardTester.simulate(b, "start", {"runs": 5, "seed": 3, "vars": caller_vars})
_eq(caller_vars["gold"]["value"], 99, "the caller's variables are untouched")
_eq(caller_vars.size(), 1, "no variables were added to the caller's dictionary")
_eq(r2["runs"], 5, "runs with a starting vars copy")
# ----- Batches -----
var t := BoardTester.new(b, "start", {"runs": 25, "seed": 4})
var did := 0
var calls := 0
while not t.is_done():
did += await t.run_batch(7)
calls += 1
_eq(did, 25, "batches add up to the planned runs")
_eq(calls, 4, "25 runs in slices of 7 is 4 calls")
_eq(t.report()["runs"], 25, "report counts all runs")
var whole: Dictionary = await BoardTester.simulate(b, "start", {"runs": 25, "seed": 4})
_eq(whole["completed"], t.report()["completed"], "sliced and whole runs agree (same seed)")
_eq(whole["actions"], t.report()["actions"], "same action stats")
var t2 := BoardTester.new(b, "start", {"runs": 100, "seed": 5})
await t2.run_batch(10)
t2.cancel()
_check(t2.is_done() and t2.report()["runs"] == 10 and t2.report()["cancelled"], "cancel stops after the finished slice")
_eq(await t2.run_batch(5), 0, "no runs after cancel")
# ----- Start tables -----
var starts := BoardTester.start_candidates(b)
_check(starts.has("start") and starts.has("island") and starts.has("badexpr") and not starts.has("gap") and not starts.has("pick") and not starts.has("v_gold"),
"start candidates are roots without variable cards: %s" % str(starts))
_check(not starts.has("mine"), "a table referenced as [[Mine]] is not a root: %s" % str(starts))
_check(BoardTester.start_candidates(b, "gap")[0] == "gap", "the last rolled table comes first")
_check(not BoardTester.start_candidates(b, "v_gold").has("v_gold"), "a variable card is never offered")
# ----- Dialog -----
var fm := FakeMain.new()
fm.data = b
root.add_child(fm)
var d := TestBoardDialog.new(fm)
fm.add_child(d)
await process_frame
_eq(d.selected_start(), "start", "the dialog defaults to the first root")
d.runs = 100
d.run_test()
var frames := 0
while d.running and frames < 400:
await process_frame
frames += 1
_check(not d.running, "the run finishes")
_check(d.sections.has("Problems") and d.sections["Problems"]["count"] >= 6, "problems section filled")
_check(d.sections["Errors"]["count"] >= 1, "errors section filled")
_check(d.sections["Dead ends"]["count"] >= 1, "dead ends section filled")
_check(d.sections["Never reached"]["count"] >= 1, "never reached section filled")
_check(d.sections.has("Never chosen"), "never chosen section exists")
_check(d.summary.text.begins_with("100 runs · ") and d.summary.text.contains("never reached"), "summary line: %s" % d.summary.text)
_check(d.report_text().contains("Static problems:") and d.report_text().contains("Dead ends"), "report text can be copied")
var first_summary := d.summary.text
d.click_item("gap", "")
_eq(fm.focused, [["gap", ""]], "clicking an item calls focus_table")
await process_frame
await process_frame
# Reopening shows the last report.
var d2 := TestBoardDialog.new(fm)
fm.add_child(d2)
await process_frame
_check(d2.sections.has("Problems") and d2.summary.text == first_summary, "the last report is shown again on reopen")
# Cancel mid-run.
d2.runs = 1000
d2.run_test()
await process_frame
d2.cancel_run()
frames = 0
while d2.running and frames < 400:
await process_frame
frames += 1
_check(not d2.running and d2.summary.text.begins_with("Cancelled after"), "cancelled run reports it: %s" % d2.summary.text)
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
func _board() -> TowerBoard:
var b := TowerBoard.new()
b.id = "bt"
b.name = "Tester"
var start := RollTable.new("start", "Start")
var e := TableEntry.new("e1", "Begin")
e.effects = "@gold += nope("
e.add_pipe("pick")
e.add_pipe("nowhere")
e.add_pipe("loop", "2 +")
start.entries.append(e)
var pick := RollTable.create(RollTable.KIND_CHOICE, "pick", "Pick", "pick")
pick.prompt = "Which? {= 1 + }"
pick.entries[0].text = "Gap"
pick.entries[0].add_pipe("gap")
pick.entries[1].text = "Fine"
pick.entries[1].add_pipe("ok")
pick.entries[2].text = "Dig in [[Mine]]"
var gap := RollTable.new("gap", "Gap")
gap.dice = "1d6"
for spec in [[1, 2, "Low"], [4, 6, "High"]]:
var ge := TableEntry.new("g%d" % spec[0], spec[2])
ge.has_range = true
ge.range_lo = spec[0]
ge.range_hi = spec[1]
gap.entries.append(ge)
var ok := RollTable.new("ok", "Fine")
ok.entries.append(TableEntry.new("e1", "All good"))
var mine := RollTable.new("mine", "Mine")
mine.entries.append(TableEntry.new("e1", "Dig"))
var island := RollTable.new("island", "Island")
island.entries.append(TableEntry.new("e1", "Alone"))
var bad := RollTable.new("badexpr", "Bad dice")
bad.dice = "2d6 +"
var be := TableEntry.new("b1", "X")
be.has_range = true
be.range_lo = 2
be.range_hi = 12
bad.entries.append(be)
var loop := RollTable.create(RollTable.KIND_LOOP, "loop", "Loop", "times")
loop.loop_expr = "3 *"
var empty := RollTable.create(RollTable.KIND_CHOICE, "empty", "Empty", "pick")
empty.entries.clear()
var ping := RollTable.new("ping", "Ping")
var pe := TableEntry.new("e1", "to pong")
pe.add_pipe("pong")
ping.entries.append(pe)
var pong := RollTable.new("pong", "Pong")
var po := TableEntry.new("e1", "to ping")
po.add_pipe("ping")
pong.entries.append(po)
var good := RollTable.new("okrange", "Fine range")
good.dice = "1d6"
var gr := TableEntry.new("r1", "All")
gr.has_range = true
gr.range_lo = 1
gr.range_hi = 6
good.entries.append(gr)
var gold := RollTable.create(RollTable.KIND_VARIABLE, "v_gold", "Gold", "number")
gold.var_name = "gold"
for tb in [start, pick, gap, ok, mine, island, bad, loop, empty, ping, pong, good, gold]:
b.tables.append(tb)
return b
func _has(probs: Array, kind: String, tid: String, eid: String) -> bool:
for p: Dictionary in probs:
if p["kind"] == kind and p["table_id"] == tid and (eid == "" or p["entry_id"] == eid):
return true
return false
func _text_has(probs: Array, s: String) -> bool:
for p: Dictionary in probs:
if str(p["text"]).contains(s):
return true
return false
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(str(got) == str(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

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

View file

@ -173,8 +173,7 @@ func _test_collapse() -> void:
await process_frame await process_frame
var node := main.group_node(g.id) var node := main.group_node(g.id)
_check(g.collapsed and node.get_parent() == main.board.cards, "a collapsed group shows as a card") _check(g.collapsed and node.get_parent() == main.board.cards, "a collapsed group shows as a card")
_check(not _shown("a") and not _shown("b"), "its members are hidden") _check(not main.card_for("a").visible and not main.card_for("b").visible, "its members are hidden")
_check(main.card_for("a") == null and main.card_for("b") == null, "and have no cards until the group expands")
_check(main.card_for("start").visible and main.card_for("out").visible, "other cards stay") _check(main.card_for("start").visible and main.card_for("out").visible, "other cards stay")
var paths: Dictionary = main.board.pipes._paths var paths: Dictionary = main.board.pipes._paths
var into: PackedVector2Array = paths.get("start:e1>a", PackedVector2Array()) var into: PackedVector2Array = paths.get("start:e1>a", PackedVector2Array())
@ -296,14 +295,16 @@ func _test_collapse_all_and_fit() -> void:
var g := _group() var g := _group()
main.set_all_collapsed(true) main.set_all_collapsed(true)
await process_frame await process_frame
_check(g.collapsed and not _shown("a"), "Collapse all collapses groups too") _check(g.collapsed and not main.card_for("a").visible, "Collapse all collapses groups too")
_check(main._collapse_all.text == "Expand all", "the button then offers Expand all") _check(main._collapse_all.text == "Expand all", "the button then offers Expand all")
# Fit ignores hidden members: move one far away; the bounds don't reach it. # Fit ignores hidden members: move one far away; the bounds don't reach it.
main.data.get_table("a").position = Vector2(30000, 30000) main.data.get_table("a").position = Vector2(30000, 30000)
main.card_for("a").position = Vector2(30000, 30000)
var bounds := main.board.content_bounds() var bounds := main.board.content_bounds()
_check(bounds.end.x < 5000.0 and bounds.has_point(main.group_node(g.id).position + Vector2(5, 5)), _check(bounds.end.x < 5000.0 and bounds.has_point(main.group_node(g.id).position + Vector2(5, 5)),
"Fit counts the group card and leaves out its hidden cards: %s" % str(bounds)) "Fit counts the group card and leaves out its hidden cards: %s" % str(bounds))
main.data.get_table("a").position = Vector2(420, 60) main.data.get_table("a").position = Vector2(420, 60)
main.card_for("a").position = Vector2(420, 60)
main.set_all_collapsed(false) main.set_all_collapsed(false)
await process_frame await process_frame
_check(not g.collapsed and main.card_for("a").visible, "Expand all expands groups") _check(not g.collapsed and main.card_for("a").visible, "Expand all expands groups")
@ -338,12 +339,6 @@ func _test_ungroup_and_delete() -> void:
_check(main.data.groups.size() == 1 and main.data.get_table("a") != null and main.card_for("b") != null, "undo brings the group and its cards back") _check(main.data.groups.size() == 1 and main.data.get_table("a") != null and main.card_for("b") != null, "undo brings the group and its cards back")
## True when a table has a card on show (hidden members have no card at all).
func _shown(tid: String) -> bool:
var c := main.card_for(tid)
return c != null and c.visible
func _check(ok: bool, what: String) -> void: func _check(ok: bool, what: String) -> void:
if not ok: if not ok:
_failures += 1 _failures += 1

View file

@ -1,341 +0,0 @@
extends SceneTree
## Navigation on big boards: search (BoardSearch and the panel), focus_table,
## the minimap, Pack collapsed groups (and making room when a packed group
## expands), and lazily built cards for collapsed groups.
## Run: godot --headless --path . -s res://tests/test_navigation.gd -- --sample
var _failures := 0
var main: Main
func _init() -> void:
if not OS.get_cmdline_user_args().has("--sample"):
print("Run with -- --sample so the test can't touch saved data.")
quit(2)
return
_test_fold_and_layout()
main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
print("Saving is enabled; refusing to run.")
quit(2)
return
# The headless window is tiny; give the app a real screen's worth of room.
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
await _load(_board_dict())
await _test_lazy_cards()
_test_search()
await _test_search_panel()
await _test_focus()
await _test_minimap()
await _load(_board_dict())
await _test_pack()
await _test_zoom_range()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## start -> agent (in Careers, 30 results); careers and skills groups
## collapsed, far apart; a variable card and a choice card loose.
func _board_dict() -> Dictionary:
var long_entries: Array = []
for i in 30:
long_entries.append({"id": "e%d" % i, "text": "Posting %d" % i})
long_entries[25]["text"] = "Ráre [b]gem[/b] posting"
return {"format_version": 2, "id": "nav-test", "name": "Nav test", "tables": [
{"id": "start", "name": "Start", "x": 40, "y": 60, "entries": [
{"id": "e1", "text": "Go to work", "pipes": ["agent"]},
{"id": "e2", "text": "Learn", "pipes": ["skill"]}]},
{"id": "agent", "name": "Agent", "x": 3000, "y": 60, "entries": long_entries},
{"id": "army", "name": "Army", "x": 3400, "y": 60, "details": "Soldiers and gems", "entries": [
{"id": "e1", "text": "Infantry"}]},
{"id": "skill", "name": "Gem", "x": 8000, "y": 60, "entries": [{"id": "e1", "text": "Gemology", "pipes": ["gems"]}]},
{"id": "gems", "name": "Gemstones", "x": 8400, "y": 60, "entries": [{"id": "e1", "text": "Ruby"}]},
{"id": "end", "name": "Endurance", "kind": "variable", "var_name": "endurance", "x": 40, "y": 3000, "entries": []},
{"id": "pick", "name": "Pick", "kind": "choice", "prompt": "Which career calls you?", "x": 6000, "y": 3000, "entries": [
{"id": "e1", "text": "Agent", "pipes": ["agent"]}, {"id": "e2", "text": "Army"}]},
], "groups": [
{"id": "careers", "name": "Careers", "x": 2978, "y": -8, "w": 760, "h": 600, "members": ["agent", "army"], "collapsed": true},
{"id": "skills", "name": "Skills", "x": 7978, "y": -8, "w": 760, "h": 300, "members": ["skill", "gems"], "collapsed": true},
]}
func _load(d: Dictionary) -> void:
main.data.load_dict(d)
main.lit_entries.clear()
main.lit_pipes.clear()
main.lit_texts.clear()
main._rebuild_cards()
for i in 4:
await process_frame
func _test_fold_and_layout() -> void:
_check(BoardSearch.fold("Ráre ÉCOLE") == "rare ecole", "fold lowers case and drops accents: %s" % BoardSearch.fold("Ráre ÉCOLE"))
_check(BoardSearch.fold("Ráre").length() == 4, "fold keeps positions")
# Pack: three blocks in a row with big gaps, one below.
var rects := [Rect2(0, 0, 100, 100), Rect2(1000, 0, 100, 50), Rect2(3000, 20, 100, 100), Rect2(2000, 900, 100, 100)]
var off := BoardLayout.pack(rects, 60.0, 60.0)
var moved: Array = []
for i in rects.size():
moved.append(Rect2((rects[i] as Rect2).position + off[i], (rects[i] as Rect2).size))
_check(moved[1].position.x == 160.0 and moved[2].position.x == 320.0, "pack closes the gaps along a row: %s" % str(moved))
_check(moved[2].position.y == 20.0, "keeping each block's height in its row")
_check(moved[3].position == Vector2(0, 180), "the next row moves up and to the left edge: %s" % str(moved[3]))
_check(not _overlaps(moved), "nothing overlaps after packing")
# Make room: a block grows from 100x100 to 600x400 in place.
var room := [Rect2(160, 0, 100, 100), Rect2(0, 160, 100, 100), Rect2(2000, 0, 100, 100)]
var ro := BoardLayout.make_room(room, Rect2(0, 0, 100, 100), Rect2(0, 0, 600, 400), 60.0)
_check(ro[0] == Vector2(500, 0), "the block to the right moves right just enough: %s" % str(ro[0]))
_check(ro[1] == Vector2(0, 300), "the block below moves down just enough: %s" % str(ro[1]))
_check(ro[2] == Vector2(500, 0), "the rest of the row moves with it, keeping order")
func _test_lazy_cards() -> void:
_check(main.card_for("agent") == null and main.card_for("army") == null, "members of a collapsed group have no card")
_check(main.card_for("start") != null and main.card_for("pick") != null, "cards on show are built")
_check(main.cards.size() == 3, "only the three loose cards are built: %d" % main.cards.size())
await process_frame
var paths: Dictionary = main.board.pipes._paths
var gn := main.group_node("careers")
var into: PackedVector2Array = paths.get("start:e1>agent", PackedVector2Array())
_check(not into.is_empty() and into[into.size() - 1].distance_to(gn.inlet_point()) < 0.5, "a pipe into a hidden member still routes to its group")
var out: PackedVector2Array = paths.get("skill:e1>gems", PackedVector2Array())
_check(out.is_empty(), "pipes inside one collapsed group aren't drawn")
main.toggle_group("careers")
await process_frame
_check(main.card_for("agent") != null and main.card_for("army") != null, "expanding the group builds its cards")
main.toggle_group("careers")
await process_frame
_check(main.card_for("agent") == null, "collapsing it again frees them")
# Fast roll through the hidden card still works and lights the group.
main.prompt_hook = func(_req: Dictionary) -> Variant: return 0
main.start_roll("start", true)
for i in 10:
await process_frame
_check(main.current.get("done", false), "a roll through hidden members finishes")
var rev := main.board.geometry_rev
for i in 5:
await process_frame
_check(main.board.geometry_rev == rev, "nothing redraws while the board is idle")
main.board.world.position += Vector2(30, 10)
await process_frame
_check(main.board.geometry_rev == rev, "panning doesn't redraw the pipe, port or card layers")
func _test_search() -> void:
var s := BoardSearch.new(main.data)
var r := s.find("gem")
_check(not r.is_empty() and r[0]["table_id"] == "skill" and r[0]["field"] == BoardSearch.FIELD_NAME, "an exact name ranks first: %s" % str(r.slice(0, 3)))
_check(r.size() > 1 and r[1]["table_id"] == "gems", "then a name that starts with it")
var entry := _find(r, "agent", "e25")
_check(not entry.is_empty() and entry["field"] == BoardSearch.FIELD_RESULT, "entry text matches, BBCode stripped")
_check(not entry.is_empty() and str(entry["snippet"]).substr(entry["hl_from"], entry["hl_len"]) == "gem", "and the snippet marks the match: %s" % str(entry))
_check(not entry.is_empty() and entry["group"] == "Careers" and entry["name"] == "Agent" and entry["kind"] == "Table", "results name the card, its kind and its group")
_check(not _find(r, "army", "").is_empty(), "details match too")
var acc := s.find("RARE")
_check(not acc.is_empty() and acc[0]["table_id"] == "agent" and acc[0]["entry_id"] == "e25", "matching ignores case and accents")
var v := s.find("endurance")
_check(v.size() >= 2 and v[0]["table_id"] == "end", "a variable card by name: %s" % str(v))
var has_var := false
for x: Dictionary in v:
if x["field"] == BoardSearch.FIELD_VARIABLE:
has_var = true
_check(has_var, "and by its variable name")
var g := s.find("careers")
_check(not g.is_empty() and g[0]["group_id"] == "careers" and g[0]["kind"] == "Group", "group names match")
var p := s.find("career calls")
_check(not p.is_empty() and p[0]["table_id"] == "pick" and p[0]["field"] == BoardSearch.FIELD_PROMPT, "choice prompts match")
var words := s.find("posting gem")
_check(not words.is_empty() and words[0]["entry_id"] == "e25", "every word must match, in any order")
_check(s.find("zzzz").is_empty() and s.find(" ").is_empty(), "no match, no results")
func _find(results: Array, tid: String, eid: String) -> Dictionary:
for r: Dictionary in results:
if r["table_id"] == tid and (eid == "" or r["entry_id"] == eid):
return r
return {}
func _test_search_panel() -> void:
var p := main.open_search()
await process_frame
_check(p.visible and p.field.has_focus(), "Search opens with the field focused")
p.field.text = "posting"
p.refresh()
_check(p.results.size() > 1 and p.selected == 0, "results show as you type")
var ev := InputEventKey.new()
ev.keycode = KEY_DOWN
ev.pressed = true
p._on_field_input(ev)
_check(p.selected == 1, "Down picks the next result")
ev.keycode = KEY_ESCAPE
p._on_field_input(ev)
_check(not p.visible, "Esc closes it")
# Ctrl+F opens it again.
var cf := InputEventKey.new()
cf.keycode = KEY_F
cf.ctrl_pressed = true
cf.pressed = true
main._shortcut_input(cf)
_check(p.visible, "Ctrl+F opens search")
p.field.text = "Gemstones"
p.refresh()
ev.keycode = KEY_ENTER
p._on_field_input(ev)
_check(not p.visible, "Enter jumps and closes")
for i in 40:
await process_frame
_check(main.card_for("gems") != null and not main.data.get_group("skills").collapsed, "jumping to a hidden card opens its group")
func _test_focus() -> void:
var g := main.data.get_group("careers")
if not g.collapsed:
main.toggle_group("careers")
await process_frame
main.board.set_zoom(0.2)
main.focus_table("agent", "e25")
for i in 120:
await process_frame
if not main.board.is_animating() and i > 5:
break
var card := main.card_for("agent")
_check(not g.collapsed and main.data.to_dict()["groups"][0].get("collapsed", false) == false, "focus expands the collapsed group (saved)")
_check(main._toast.visible and main._toast_label.text.contains("Opened group Careers"), "and says so: %s" % main._toast_label.text)
_check(card != null, "the card is built")
if card == null:
return
var view := main.board.view_rect()
var r := Rect2(card.position, card.size)
_check(main.board.zoom >= Main.MIN_FOCUS_ZOOM, "the view zooms in to read it: %.2f" % main.board.zoom)
_check(view.encloses(Rect2(r.position, Vector2(r.size.x, minf(r.size.y, view.size.y - 20.0)))), "the card is in view: %s in %s" % [str(r), str(view)])
_check(absf(view.get_center().x - r.get_center().x) < 2.0, "and centred")
_check(card.list_scroll != null and card.list_scroll.scroll_vertical > 0, "the long list scrolls to the result")
var a := card.anchor_for("e25")
_check(not a.is_empty() and a["visible"], "the result's row is in view")
_check(main.board.cards.is_flashing() and main.board.cards.flash_rect() == r, "a ring flashes around the card")
var row := main.board.cards.flash_row_rect()
_check(row.size.y > 0.0 and absf(row.get_center().y - (a["pos"] as Vector2).y) < 1.0, "and around the row: %s" % str(row))
# The ring fades after about 1.5 s.
main.board.cards._process(2.0)
_check(not main.board.cards.is_flashing(), "the flash ends")
# A collapsed loose card opens when a result is asked for.
main.data.get_table("start").collapsed = true
main.card_for("start").rebuild()
main.focus_table("start", "e2")
for i in 6:
await process_frame
_check(not main.data.get_table("start").collapsed, "focus on a result expands a collapsed card")
main.focus_table("nope")
_check(true, "an unknown id does nothing")
func _test_minimap() -> void:
var mm := main.board.minimap
main.set_minimap_visible(true)
await process_frame
_check(mm.visible and main._map_toggle.button_pressed, "the minimap shows, and its toggle is on")
_check(mm.position.x + mm.size.x <= main.board.size.x and mm.position.y + mm.size.y <= main.board.size.y, "in the board's bottom-right corner")
mm.set_world(Rect2(-100, -100, 4000, 2000))
var p := Vector2(1234, 567)
_check(mm.map_to_world(mm.world_to_map(p)).distance_to(p) < 0.01, "map and world coordinates round-trip")
main.board.set_zoom(0.5)
main.board.center_on(Vector2(1900, 900))
var v := main.board.view_rect()
var vm := mm.view_rect_on_map()
_check(vm.position.distance_to(mm.world_to_map(v.position)) < 0.01 and absf(vm.size.x - v.size.x * mm._scale) < 0.01, "the view rect is the board's view, scaled")
var target := mm.world_to_map(Vector2(500, 300))
mm.pan_to_map_point(target)
_check(main.board.view_rect().get_center().distance_to(Vector2(500, 300)) < 1.0, "clicking the map pans there")
var click := InputEventMouseButton.new()
click.button_index = MOUSE_BUTTON_LEFT
click.pressed = true
click.position = mm.world_to_map(Vector2(2500, 1000))
mm._gui_input(click)
var drag := InputEventMouseMotion.new()
drag.position = mm.world_to_map(Vector2(2600, 1200))
mm._gui_input(drag)
_check(main.board.view_rect().get_center().distance_to(Vector2(2600, 1200)) < 1.0, "dragging on it pans along")
click.pressed = false
mm._gui_input(click)
# M toggles it (not while typing).
var m := InputEventKey.new()
m.keycode = KEY_M
m.pressed = true
main._shortcut_input(m)
_check(not mm.visible, "M hides it")
main._shortcut_input(m)
_check(mm.visible, "M shows it again")
main.set_mode(Main.Mode.PLAY)
_check(not mm.visible, "it's off by default in Play")
main.set_mode(Main.Mode.BUILD)
main.set_mode(Main.Mode.PLAY)
await process_frame
func _test_pack() -> void:
main.set_mode(Main.Mode.BUILD)
var before := _blocks()
var bounds0 := main.board.content_bounds()
var moved: int = await main.pack_collapsed_groups()
var after := _blocks()
_check(moved > 0, "Pack moves blocks: %d" % moved)
_check(not _overlaps(after.values()), "nothing overlaps after Pack: %s" % str(after))
_check(after["careers"].position.x < after["skills"].position.x and after["start"].position.x < after["careers"].position.x,
"reading order holds along the top row")
_check(after["end"].position.y > after["start"].position.y and after["pick"].position.x > after["end"].position.x, "and in the row below")
var bounds1 := main.board.content_bounds()
_check(bounds1.size.x < bounds0.size.x * 0.5 and bounds1.size.y < bounds0.size.y, "the board gets much smaller: %s -> %s" % [str(bounds0.size), str(bounds1.size)])
var agent := main.data.get_table("agent")
_check(agent.position - main.data.get_group("careers").position == Vector2(22, 68), "members move with their group")
_check(main._toast.visible and main._toast_undo.visible, "with an undo toast")
main._undo()
await process_frame
var back := _blocks()
_check(back["skills"].position == before["skills"].position and back["start"].position == before["start"].position
and back["careers"].position == before["careers"].position, "undo puts everything back")
# Expanding a packed group makes room instead of overlapping.
await main.pack_collapsed_groups()
main.toggle_group("careers")
for i in 3:
await process_frame
var grown := _blocks()
_check(not _overlaps(grown.values()), "expanding a packed group pushes its neighbours clear: %s" % str(grown))
_check(grown["careers"].position.x < grown["skills"].position.x, "keeping their order")
_check(main._toast_label.text.contains("make room") and main._toast_undo.visible, "and says so, with undo: %s" % main._toast_label.text)
func _test_zoom_range() -> void:
await _load(_board_dict())
main.board.set_zoom(0.01)
_check(is_equal_approx(main.board.zoom, BoardView.MIN_ZOOM) and BoardView.MIN_ZOOM <= 0.1, "zoom goes down to about 0.1")
main.board.fit()
_check(main.board.zoom < 0.35, "Fit can zoom below the old minimum for a wide board: %.2f" % main.board.zoom)
## Rects of the blocks Pack works on: groups (compact or frame) and loose cards.
func _blocks() -> Dictionary:
var out := {}
for b: Dictionary in main._layout_blocks():
out[b["group"] if b["group"] != "" else b["table"]] = b["rect"]
return out
func _overlaps(rects: Array) -> bool:
for i in rects.size():
for j in range(i + 1, rects.size()):
if (rects[i] as Rect2).intersects(rects[j]):
return true
return false
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print("FAIL ", what)

View file

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

View file

@ -1,424 +0,0 @@
extends SceneTree
## Headless checks for conditional pipes and router cards (docs/LOGIC.md §3a
## and §3b): when / otherwise selection, the snapshot rule, expression errors,
## first-match routing, "No case matched", the file format, lint_pipes() and a
## small board where a router replaces a chain-variable workaround.
## Run: godot --headless --path . -s res://tests/test_router.gd
var _failures := 0
func _init() -> void:
_test_when_otherwise()
_test_snapshot()
_test_errors()
_test_router()
_test_no_case()
_test_json()
_test_lint()
_test_cycles()
await _test_mini_board()
_test_ui_helpers()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
# ---------------------------------------------------------------- helpers
func _rng(seed_value: int = 1) -> RandomNumberGenerator:
var r := RandomNumberGenerator.new()
r.seed = seed_value
return r
func _board(tables: Array) -> TowerBoard:
var b := TowerBoard.new()
b.id = "router-test"
for t in tables:
b.tables.append(t)
return b
## A one-entry roll table.
func _one(id: String, text: String, effects: String = "") -> RollTable:
var t := RollTable.new(id, id.capitalize())
var e := TableEntry.new("e1", text)
e.effects = effects
t.entries.append(e)
return t
func _roll(b: TowerBoard, id: String, vars: Dictionary = {}) -> Dictionary:
var ctx := Roller.new_context(b, _rng(), vars)
return Roller.roll(b, id, ctx.rng, 0, {}, ctx)
## Table ids of a tree's steps, in roll order.
func _ids(tree: Dictionary) -> Array:
var out := []
for s: Dictionary in Roller.flatten(tree):
out.append(str(s["table_id"]))
return out
func _var(vars: Dictionary, name: String) -> Variant:
var v: Variant = vars.get(name)
return (v as Dictionary).get("value") if v is Dictionary else null
func _errors(tree: Dictionary) -> Array:
var out := []
for s: Dictionary in Roller.flatten(tree):
for fx: Dictionary in s.get("effects", []):
if fx.get("error", false):
out.append(str(fx["text"]))
return out
# ---------------------------------------------------------------- when / otherwise
## start --if @str >= 8--> strong, --if @str < 4--> weak, --otherwise--> plain,
## --(always)--> after.
func _branch_board(str_value: int) -> TowerBoard:
var start := _one("start", "Begin", "@str = %d" % str_value)
var e := start.entries[0]
e.add_pipe("strong")
e.set_pipe_when("strong", "@str >= 8")
e.add_pipe("weak")
e.set_pipe_when("weak", "@str < 4")
e.add_pipe("plain")
e.set_pipe_otherwise("plain", true)
e.add_pipe("after")
return _board([start, _one("strong", "Strong"), _one("weak", "Weak"), _one("plain", "Plain"), _one("after", "After")])
func _test_when_otherwise() -> void:
_eq(_ids(_roll(_branch_board(10), "start")), ["start", "strong", "after"], "a true condition runs its pipe; otherwise is skipped")
_eq(_ids(_roll(_branch_board(2), "start")), ["start", "weak", "after"], "the second condition can be the true one")
_eq(_ids(_roll(_branch_board(6), "start")), ["start", "plain", "after"], "no condition true: the otherwise pipe runs")
# Two true conditions both run (pipes aren't else-if; use a router for that).
var b := _branch_board(10)
b.get_table("start").entries[0].set_pipe_when("weak", "@str > 1")
_eq(_ids(_roll(b, "start")), ["start", "strong", "weak", "after"], "every true condition runs, in pipe order")
# A condition clears otherwise, and otherwise can't be set while there's a condition.
var e := TableEntry.new("e1", "x")
e.add_pipe("y")
e.set_pipe_otherwise("y", true)
_check(e.is_otherwise("y"), "otherwise is set")
e.set_pipe_when("y", "@a = 1")
_check(not e.is_otherwise("y") and e.when_for("y") == "@a = 1", "a condition replaces otherwise")
e.set_pipe_otherwise("y", true)
_check(not e.is_otherwise("y"), "otherwise is refused while a condition is set")
e.remove_pipe("y")
_check(e.pipe_when.is_empty() and e.pipe_otherwise.is_empty(), "remove_pipe clears the condition")
# Only the pipes taken light up.
var lit_e := {}
var lit_p := {}
Roller.collect_lit(_roll(_branch_board(10), "start"), lit_e, lit_p)
_check(lit_p.has(Roller.pipe_key("start", "e1", "strong")) and lit_p.has(Roller.pipe_key("start", "e1", "after")), "taken pipes light")
_check(not lit_p.has(Roller.pipe_key("start", "e1", "weak")) and not lit_p.has(Roller.pipe_key("start", "e1", "plain")), "skipped pipes stay dark")
# ---------------------------------------------------------------- snapshot
func _test_snapshot() -> void:
# The first pipe's subtree changes @x and @n; the later pipes still see the
# values from when the entry was chosen.
var start := _one("start", "Begin", "@x = 0; @n = 1")
var e := start.entries[0]
e.add_pipe("first")
e.set_pipe_when("first", "@x = 0")
e.add_pipe("second")
e.set_pipe_when("second", "@x = 0")
e.add_pipe("third")
e.set_pipe_count("third", "@n")
e.add_pipe("fallback")
e.set_pipe_otherwise("fallback", true)
var first := _one("first", "First", "@x = 1; @n = 4")
var b := _board([start, first, _one("second", "Second"), _one("third", "Third"), _one("fallback", "Fallback")])
var vars := {}
var ids := _ids(_roll(b, "start", vars))
_eq(ids, ["start", "first", "second", "third"], "conditions and counts come from the snapshot, not the changed variables")
_eq(_var(vars, "x"), 1, "the first pipe's subtree did change @x")
# An otherwise pipe doesn't fire because a when pipe's subtree made the
# conditions false afterwards.
_check(not ids.has("fallback"), "otherwise reads the snapshot too")
# A self-pipe with a counting condition still counts up (the condition is
# checked each time the entry is chosen).
var link := _one("link", "Link {@k}", "@k += 1")
link.entries[0].add_pipe("link")
link.entries[0].set_pipe_when("link", "@k < 5")
var v2 := {}
_eq(_ids(_roll(_board([link]), "link", v2)).size(), 5, "a conditional self-pipe stops when its condition turns false")
_eq(_var(v2, "k"), 5, "it ran five times")
# ---------------------------------------------------------------- errors
func _test_errors() -> void:
var start := _one("start", "Begin")
var e := start.entries[0]
e.add_pipe("bad")
e.set_pipe_when("bad", "@x + * 2")
e.add_pipe("other")
e.set_pipe_otherwise("other", true)
var tree := _roll(_board([start, _one("bad", "Bad"), _one("other", "Other")]), "start")
_eq(_ids(tree), ["start", "other"], "a condition that errors counts as false (so otherwise runs)")
var errs := _errors(tree)
_check(errs.size() == 1 and str(errs[0]).begins_with("Pipe condition @x + * 2"), "the error shows as an error line on the node: %s" % str(errs))
var step: Dictionary = Roller.flatten(tree)[0]
_check((step.get("effects", []) as Array).size() == 1, "the error line is in the step's effects")
# ---------------------------------------------------------------- routers
func _router_board() -> TowerBoard:
var r := RollTable.create(RollTable.KIND_ROUTER, "route", "Route")
r.entries.clear()
var cases := [["@species = \"Aslan\"", "Aslan path", "aslan"], ["@str >= 8", "Strong path", "strong"], ["", "Otherwise", "plain"]]
for i in cases.size():
var c := TableEntry.new("c%d" % (i + 1), cases[i][1])
c.when = cases[i][0]
c.effects = "@took = \"%s\"" % cases[i][2]
c.add_pipe(cases[i][2])
r.entries.append(c)
return _board([r, _one("aslan", "Aslan"), _one("strong", "Strong"), _one("plain", "Plain")])
func _test_router() -> void:
var t := RollTable.create(RollTable.KIND_ROUTER, "r", "Router")
_eq(t.kind, "router", "create makes a router")
_eq(t.entries.size(), 2, "a new router has two cases")
_eq(t.entries[0].text, "if …", "its first case")
_check(t.entries[0].when != "" and Expr.check(t.entries[0].when) == "", "the first case has a valid condition")
_check(t.entries[1].text == "Otherwise" and t.entries[1].when == "", "the second is Otherwise")
_eq(t.otherwise_index(), 1, "otherwise_index")
var b := _router_board()
var vars := {"species": {"value": "Aslan", "source": ""}, "str": {"value": 10, "source": ""}}
var tree := _roll(b, "route", vars)
_eq(_ids(tree), ["route", "aslan"], "the first true case wins, even when a later one is true too")
_eq(str(tree.get("kind", "")), "router", "the node's kind is router")
_eq(tree.get("case"), 0, "the node's case index")
_eq(_var(vars, "took"), "aslan", "the case's effects ran")
_eq(Formatter.strip_tags(str(tree["summary"])), "Aslan path", "the case's text is the summary")
var step: Dictionary = Roller.flatten(tree)[0]
_check(step.get("kind") == "router" and step.get("case") == 0 and str(step.get("num", "")) == "", "the step has kind and case, and no rolled number: %s" % str(step))
var v2 := {"str": {"value": 9, "source": ""}}
_eq(_ids(_roll(b, "route", v2)), ["route", "strong"], "the second case")
_eq(_ids(_roll(b, "route", {})), ["route", "plain"], "nothing true: Otherwise")
# One action per router.
var ctx := Roller.new_context(b, _rng(), {})
Roller.roll(b, "route", ctx.rng, 0, {}, ctx)
_eq(ctx.actions, 2, "a router is one action (plus the table it pipes to)")
# A case condition with an error counts as false and is reported.
b.get_table("route").entries[0].when = "@species = = 3 +"
var t3 := _roll(b, "route", {})
_eq(_ids(t3), ["route", "plain"], "an erroring case is skipped")
var errs := _errors(t3)
_check(errs.size() == 1 and str(errs[0]).begins_with("Case "), "the case error is on the router node: %s" % str(errs))
# Lighting: the matched case is lit.
var le := {}
var lp := {}
Roller.collect_lit(_roll(_router_board(), "route", {}), le, lp)
_check(le.has(Roller.entry_key("route", "c3")) and not le.has(Roller.entry_key("route", "c1")), "only the matched case lights")
func _test_no_case() -> void:
var b := _router_board()
var r := b.get_table("route")
r.entries.remove_at(2) # no Otherwise
var tree := _roll(b, "route", {})
_check(tree.has("stop") and str(tree["summary"]) == Roller.NO_CASE, "nothing matched: the node stops with \"No case matched\"")
_eq(str(tree.get("kind", "")), "router", "the stop node is a router node")
_eq(_ids(tree), ["route"], "nothing follows")
var step: Dictionary = Roller.flatten(tree)[0]
_check(step.get("stop", false) and str(step["text"]) == "No case matched", "the step shows it")
# A router with no cases at all.
r.entries.clear()
_check(_roll(b, "route", {}).has("stop"), "an empty router stops")
# ---------------------------------------------------------------- file format
func _test_json() -> void:
var b := _router_board()
var e := b.get_table("route").entries[1]
e.add_pipe("aslan", 2, "who")
e.set_pipe_when("aslan", "@str > 9")
e.add_pipe("plain")
e.set_pipe_otherwise("plain", true)
var d := b.get_table("route").to_dict()
_eq(str(d.get("kind", "")), "router", "kind is written")
var ed: Dictionary = d["entries"][1]
_eq(str(ed.get("when", "")), "@str >= 8", "an entry's when is written")
_check(not (d["entries"][2] as Dictionary).has("when"), "the Otherwise case has no when")
var pipes: Array = ed["pipes"]
_eq(pipes[1], {"table": "aslan", "count": 2, "save_as": "who", "when": "@str > 9"}, "a pipe's when is written with its other options")
_eq(pipes[2], {"table": "plain", "otherwise": true}, "an otherwise pipe")
_eq(pipes[0], "strong", "a plain pipe stays a bare id")
var back := RollTable.from_dict(d)
var be := back.entries[1]
_check(back.kind == "router" and be.when == "@str >= 8" and be.when_for("aslan") == "@str > 9" and be.is_otherwise("plain") and be.count_for("aslan") == 2 and be.save_for("aslan") == "who", "the table round-trips")
_eq(back.to_dict(), d, "to_dict(from_dict(d)) == d")
# Canonical form keeps them, drops bad values, and drops otherwise next to a when.
var raw := {"tables": [{"id": "x", "name": "X", "kind": "router", "entries": [
{"id": "a", "text": "A", "when": " @a = 1 ", "pipes": [{"table": "y", "when": "@b", "otherwise": true}, {"table": "z", "otherwise": true}, {"table": "w", "otherwise": "yes"}, {"table": "v", "when": ""}]},
{"id": "b", "text": "B", "when": ""}]}]}
var c := JsonIO.canonical(raw)
var ce: Dictionary = c["tables"][0]["entries"][0]
_eq(str(c["tables"][0].get("kind", "")), "router", "canonical keeps kind router")
_eq(str(ce.get("when", "")), "@a = 1", "canonical keeps (trimmed) entry when")
_check(not (c["tables"][0]["entries"][1] as Dictionary).has("when"), "canonical drops an empty when")
_eq(ce["pipes"], [{"table": "y", "when": "@b"}, {"table": "z", "otherwise": true}, {"table": "w"}, {"table": "v"}], "canonical pipe conditions")
var text := JsonIO.export_json(b.to_dict())
var imp := JsonIO.import_json(text)
_check(imp["ok"], "the export imports")
var b2 := TowerBoard.new()
b2.load_dict(imp["collection"])
var e2 := b2.get_table("route").entries[1]
_check(e2.when == "@str >= 8" and e2.when_for("aslan") == "@str > 9" and e2.is_otherwise("plain"), "a JSON export round-trips conditions")
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "y", "when": "@str >= 8", "count": 2, "save_as": "w"})), "if @str >= 8 ×2 → w", "edge label for a conditional pipe")
_eq(JsonIO.pipe_label(JsonIO.pipe_info({"table": "y", "otherwise": true})), "otherwise", "edge label for an otherwise pipe")
# ---------------------------------------------------------------- lint
func _test_lint() -> void:
_eq(Roller.lint_pipes(_router_board()), [] as Array[Dictionary], "a clean board has no lint")
var b := _router_board()
var r := b.get_table("route")
# Otherwise first: the cases after it can't be chosen.
var other := r.entries[2]
r.entries.remove_at(2)
r.entries.insert(0, other)
r.entries[1].when = "@str >= = 8"
var start := _one("start", "Begin")
var e := start.entries[0]
e.add_pipe("plain")
e.set_pipe_otherwise("plain", true)
e.add_pipe("strong")
e.set_pipe_when("strong", "(((")
var lonely := _one("lonely", "Lonely")
lonely.entries[0].add_pipe("plain")
lonely.entries[0].set_pipe_otherwise("plain", true)
var empty := RollTable.create(RollTable.KIND_ROUTER, "empty", "Empty")
empty.entries.clear()
b.tables.append_array([start, lonely, empty])
var lint := Roller.lint_pipes(b)
var msgs := {}
for item: Dictionary in lint:
_check(item.has("table_id") and item.has("entry_id") and item.has("message"), "lint items have table_id, entry_id, message")
msgs["%s:%s" % [item["table_id"], item["entry_id"]]] = str(msgs.get("%s:%s" % [item["table_id"], item["entry_id"]], "")) + str(item["message"]) + "|"
_check(str(msgs.get("route:c3", "")).contains("Otherwise case isn't last"), "Otherwise case not last: %s" % str(lint))
_check(str(msgs.get("route:c1", "")).begins_with("Case @str >= = 8"), "a bad case condition: %s" % str(lint))
_check(str(msgs.get("start:e1", "")).contains("Pipe condition (((") and str(msgs.get("start:e1", "")).contains("comes before a conditional pipe"), "a bad pipe condition, and otherwise before when: %s" % str(lint))
_check(str(msgs.get("lonely:e1", "")).contains("always runs"), "otherwise with no conditional pipe: %s" % str(lint))
_check(str(msgs.get("empty:", "")).contains("no cases"), "a router with no cases: %s" % str(lint))
_eq(lint.size(), 6, "six lint items")
func _test_cycles() -> void:
# A table whose only pipe back to itself is conditional can finish.
var link := _one("link", "Link", "@k += 1")
link.entries[0].add_pipe("link")
link.entries[0].set_pipe_when("link", "@k < 3")
_eq(Roller.endless_cycles(_board([link])), [] as Array[String], "a conditional self-pipe is not an endless cycle")
var r := RollTable.create(RollTable.KIND_ROUTER, "r", "R")
r.entries[0].add_pipe("r")
_eq(Roller.endless_cycles(_board([r])), [] as Array[String], "a router with a case that finishes is fine")
r.entries[1].add_pipe("r")
_eq(Roller.endless_cycles(_board([r])), ["r"] as Array[String], "a router whose every case loops back is endless")
# ---------------------------------------------------------------- mini board
## The workaround a big board used before routers: the Species choice's
## answer sets a chain flag, and two pipes count on it (1 or 0 times). With
## lazy counts, the second count was read after the first branch had run, so
## a branch that changed @species made both fire. The router version checks
## once and picks one case.
func _species_board(use_router: bool) -> TowerBoard:
var species := RollTable.create(RollTable.KIND_CHOICE, "species", "Species", "pick")
species.save_as = "@species"
species.entries[0].text = "Aslan"
species.entries[1].text = "Human"
species.entries.resize(2)
# The Aslan branch rewrites @species (e.g. a clan name), which used to
# confuse the flag on the second pipe.
var aslan := _one("aslan", "Clan training", "@species = \"Aslan (Hkasuao)\"; @path += \"aslan\"")
var human := _one("human", "Human schooling", "@path += \"human\"")
var sheet := RollTable.create(RollTable.KIND_SHEET, "sheet", "Sheet")
sheet.entries[0].text = "{@species}: {@path}"
var tables: Array = [species, aslan, human, sheet]
for e in species.entries:
if use_router:
e.add_pipe("route")
else:
e.effects = "is_aslan = if(@species = \"Aslan\", 1, 0)"
e.add_pipe("aslan", "if(@species = \"Aslan\", 1, 0)")
e.add_pipe("human", "if(@species = \"Aslan\", 0, 1)")
e.add_pipe("sheet")
if use_router:
var route := RollTable.create(RollTable.KIND_ROUTER, "route", "Which upbringing")
route.entries[0].text = "Aslan upbringing"
route.entries[0].when = "@species = \"Aslan\""
route.entries[0].add_pipe("aslan")
route.entries[1].text = "Human upbringing"
route.entries[1].add_pipe("human")
for c in route.entries:
c.add_pipe("sheet")
tables.append(route)
return _board(tables)
func _pick(index: int) -> Callable:
return func(_req: Dictionary) -> Variant: return index
func _test_mini_board() -> void:
for use_router in [false, true]:
for pick in [0, 1]:
var b := _species_board(use_router)
var vars := {}
var ctx := Roller.new_context(b, _rng(), vars)
ctx.prompt = _pick(pick)
var tree: Dictionary = await Roller.roll_async(b, "species", ctx)
var ids := _ids(tree)
var label := "%s, picked %s" % ["router" if use_router else "workaround", "Aslan" if pick == 0 else "Human"]
_check(ids.has("aslan") != ids.has("human"), "%s: exactly one branch runs: %s" % [label, str(ids)])
_check(ids.has("aslan" if pick == 0 else "human"), "%s: the right branch: %s" % [label, str(ids)])
_eq(_var(vars, "path"), "aslan" if pick == 0 else "human", "%s: @path" % label)
_check(_errors(tree).is_empty(), "%s: no errors" % label)
if use_router:
_check(ids.has("route") and ids.has("sheet"), "%s: through the router to the sheet" % label)
# The router version lints clean and has no cycles.
_eq(Roller.lint_pipes(_species_board(true)), [] as Array[Dictionary], "the router board lints clean")
# ---------------------------------------------------------------- UI helpers
func _test_ui_helpers() -> void:
_eq(PipePopover.when_error(""), "", "an empty Only if is fine (always)")
_eq(PipePopover.when_error("@str >= 8"), "", "a valid condition")
_check(PipePopover.when_error("@str >= = 8") != "", "a bad condition is caught")
var r := RollTable.create(RollTable.KIND_ROUTER, "r", "R")
_eq(TableCard.case_label(r.entries[0]), "if " + RollTable.ROUTER_DEFAULT_WHEN, "case label")
_eq(TableCard.case_label(r.entries[1]), "Otherwise", "Otherwise label")
var bad := TableSettingsDialog.apply_settings(r, {"name": "R", "cases": ["@a = = 1", ""]})
_check(not bad["ok"] and str(bad["error"]).begins_with("Case 1"), "settings refuse a bad case: %s" % str(bad))
var ok := TableSettingsDialog.apply_settings(r, {"name": "R", "cases": ["@a = 1", ""], "card_mode": true, "ranged": true})
_check(ok["ok"] and r.entries[0].when == "@a = 1" and not r.card_mode and not r.is_ranged(), "settings set case conditions; no card mode or ranges: %s" % str(ok))
_check(TableSettingsDialog.router_hint(["", "@a"]) != "" and TableSettingsDialog.router_hint(["@a", ""]) == "", "router order hint")
_eq(TablePreview.kind_line(r), "Router · if / else if / otherwise", "preview kind line")
# ---------------------------------------------------------------- checks
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(typeof(got) == typeof(want) and got == want or (got is Array and want is Array and str(got) == str(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

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

View file

@ -1,14 +1,16 @@
extends SceneTree extends SceneTree
## Keeps the simulator (BoardTester, and its CLI tools/simulate_board.gd) working: runs it on a small inline board with ## Keeps tools/simulate_board.gd working: runs it on a small inline board with
## a choice, a loop, a check, a bad effect, an unreachable table and a sheet. ## a choice, a loop, a check, a bad effect, an unreachable table and a sheet.
## Run: godot --headless --path . -s res://tests/test_simulate.gd ## Run: godot --headless --path . -s res://tests/test_simulate.gd
const Sim := preload("res://tools/simulate_board.gd")
var _failures := 0 var _failures := 0
func _init() -> void: func _init() -> void:
var b := _board() var b := _board()
var r: Dictionary = await BoardTester.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]}) var r: Dictionary = await Sim.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]})
_eq(r["runs"], 60, "60 runs") _eq(r["runs"], 60, "60 runs")
_eq(r["completed"], 60, "every run completes") _eq(r["completed"], 60, "every run completes")
_check((r["halted"] as Dictionary).is_empty(), "nothing halted: %s" % str(r["halted"])) _check((r["halted"] as Dictionary).is_empty(), "nothing halted: %s" % str(r["halted"]))
@ -22,7 +24,7 @@ func _init() -> void:
_check(not uc.has("pick"), "every pick option was chosen at some point") _check(not uc.has("pick"), "every pick option was chosen at some point")
var sheet := str(r["sample_sheet"]) var sheet := str(r["sample_sheet"])
_check(sheet.begins_with("Hero: ") and sheet.contains("Gold "), "a sample sheet is kept: %s" % sheet) _check(sheet.begins_with("Hero: ") and sheet.contains("Gold "), "a sample sheet is kept: %s" % sheet)
_check(not BoardTester.is_clean(r), "a run with an effect error is not clean") _check(not Sim.is_clean(r), "a run with an effect error is not clean")
# Each run starts with empty variables: gold never grows past one run's worth. # Each run starts with empty variables: gold never grows past one run's worth.
var gold := int((r["sample_vars"].get("gold", {}) as Dictionary).get("value", -1)) var gold := int((r["sample_vars"].get("gold", {}) as Dictionary).get("value", -1))
_check(gold <= 18, "variables start clean for every run (gold %d)" % gold) _check(gold <= 18, "variables start clean for every run (gold %d)" % gold)
@ -34,13 +36,13 @@ func _init() -> void:
var lg: Dictionary = r["longest"] var lg: Dictionary = r["longest"]
_check(int(lg["actions"]) == int(a["max"]) and not (lg["top"] as Array).is_empty(), "the longest run's busiest tables are kept: %s" % str(lg)) _check(int(lg["actions"]) == int(a["max"]) and not (lg["top"] as Array).is_empty(), "the longest run's busiest tables are kept: %s" % str(lg))
# A preference picks the matching option every time. # A preference picks the matching option every time.
var r2: Dictionary = await BoardTester.simulate(b, "start", {"runs": 20, "seed": 4, "prefer": "^Mine$"}) var r2: Dictionary = await Sim.simulate(b, "start", {"runs": 20, "seed": 4, "prefer": "^Mine$"})
_check((r2["unchosen"] as Dictionary).has("pick"), "--prefer always picks the matching option") _check((r2["unchosen"] as Dictionary).has("pick"), "--prefer always picks the matching option")
_check(int((r2["table_hits"] as Dictionary).get("mine", 0)) == 20 * 3, "the preferred option's pipe ran on every pass") _check(int((r2["table_hits"] as Dictionary).get("mine", 0)) == 20 * 3, "the preferred option's pipe ran on every pass")
# The action limit is reported as a halt reason. # The action limit is reported as a halt reason.
var r3: Dictionary = await BoardTester.simulate(b, "start", {"runs": 5, "seed": 5, "max_actions": 4}) var r3: Dictionary = await Sim.simulate(b, "start", {"runs": 5, "seed": 5, "max_actions": 4})
_eq((r3["halted"] as Dictionary).get("Action limit", 0), 5, "the action limit is a halt reason") _eq((r3["halted"] as Dictionary).get("Action limit", 0), 5, "the action limit is a halt reason")
var text := BoardTester.format_report(r) var text := Sim.format_report(r)
_check(text.contains("Runs: 60") and text.contains("Tables never reached: 1") and text.contains("Sample final sheet") and text.contains("@gold: min"), "the report prints:\n%s" % text) _check(text.contains("Runs: 60") and text.contains("Tables never reached: 1") and text.contains("Sample final sheet") and text.contains("@gold: min"), "the report prints:\n%s" % text)
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0) quit(1 if _failures else 0)

View file

@ -22,10 +22,9 @@ extends SceneTree
## persistent-vars dictionary), so runs never leak state into each other. ## persistent-vars dictionary), so runs never leak state into each other.
## The exit code is 1 when any run hit an error, the action limit, or a ## The exit code is 1 when any run hit an error, the action limit, or a
## dead end ("No result for ..."), else 0. ## dead end ("No result for ..."), else 0.
## --check also print the static checks (BoardTester.static_checks).
## ##
## A thin wrapper around BoardTester (core/board_tester.gd); simulate(), ## Other scripts can call simulate() and format_report() directly (see
## answer(), is_clean() and format_report() forward to it. ## tests/test_simulate.gd).
func _init() -> void: func _init() -> void:
@ -33,7 +32,7 @@ func _init() -> void:
var path := str(args.get("board", "")) var path := str(args.get("board", ""))
var start := str(args.get("start", "")) var start := str(args.get("start", ""))
if path == "" or start == "": if path == "" or start == "":
print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<table id> --runs=N [--seed=S] [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet] [--check]") print("Usage: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<table id> --runs=N [--seed=S] [--prefer=<regex>] [--track=a,b] [--max-actions=N] [--list=N] [--quiet]")
quit(2) quit(2)
return return
var text := FileAccess.get_file_as_string(path) var text := FileAccess.get_file_as_string(path)
@ -59,8 +58,6 @@ func _init() -> void:
} }
var report: Dictionary = await simulate(board, start, opts) var report: Dictionary = await simulate(board, start, opts)
print(format_report(report, int(args.get("list", "40")), not args.has("quiet"))) print(format_report(report, int(args.get("list", "40")), not args.has("quiet")))
if args.has("check"):
print("\n".join(BoardTester.format_problems(BoardTester.static_checks(board), int(args.get("list", "40")))))
quit(0 if is_clean(report) else 1) quit(0 if is_clean(report) else 1)
@ -78,17 +75,292 @@ static func _parse_args(list: PackedStringArray) -> Dictionary:
return out return out
## Runs `opts.runs` top-level rolls of `start` and gathers statistics.
## opts: runs (int), seed (int), prefer (String regex, may be ""),
## max_actions (int), track (Array of variable names). Returns the report
## Dictionary that format_report() prints:
## runs, completed, halted {reason: count}, actions {max, mean, p95},
## longest {actions, run, top: [{table, count}]} (the most-rolled tables
## of the run that took the most actions), track {name: {min, max, sum, n}},
## prompts_mean, errors [{table, entry, text, count}], dead_ends
## [{table, text, count}], unset_markers [{table, entry, text, count}]
## (unset {@var?}, missing [[table]] and failed {= expr} markers),
## unreached [table ids], unchosen {table id: [entry texts]},
## table_hits {table id: count}, sample_sheet (String), sample_vars
## (Dictionary), sample_halted (String)
static func simulate(board: TowerBoard, start: String, opts: Dictionary = {}) -> Dictionary: static func simulate(board: TowerBoard, start: String, opts: Dictionary = {}) -> Dictionary:
return await BoardTester.simulate(board, start, opts) var runs := maxi(1, int(opts.get("runs", 100)))
var rng := RandomNumberGenerator.new()
rng.seed = int(opts.get("seed", 1))
var answer_rng := RandomNumberGenerator.new()
answer_rng.seed = rng.seed * 7919 + 17
var prefer: RegEx = null
var pat := str(opts.get("prefer", ""))
if pat != "":
prefer = RegEx.create_from_string("(?i)" + pat)
var max_actions := int(opts.get("max_actions", RollContext.DEFAULT_MAX_ACTIONS))
var completed := 0
var halted := {}
var actions: Array[int] = []
var prompts_total := 0
var errors := {} # key -> {table, entry, text, count}
var dead_ends := {} # key -> {table, text, count}
var markers := {} # key -> {table, entry, text, count}
var table_hits := {} # table id -> count
var entry_hits := {} # "table:entry" -> count
var sample_sheet := ""
var sample_vars := {}
var sample_halted := ""
var longest := {"actions": -1, "run": 0, "top": []}
var track := {} # name -> {min, max, sum, n}
for name: String in opts.get("track", []):
track[name.strip_edges().trim_prefix("@")] = {"min": INF, "max": -INF, "sum": 0.0, "n": 0}
for run in runs:
var vars := {}
var ctx := Roller.new_context(board, rng, vars, {})
ctx.max_actions = max_actions
var counter := [0]
ctx.prompt = func(req: Dictionary) -> Variant:
counter[0] += 1
var texts: Array = [str(req.get("prompt", ""))]
for o: Dictionary in req.get("options", []):
texts.append(str(o.get("text", "")))
for txt: String in texts:
for m in _marker_re().search_all(txt):
var what := Formatter.strip_tags(m.get_string())
var tid := str(req.get("table_id", ""))
var mk := tid + ":prompt|" + what
if not markers.has(mk):
markers[mk] = {"table": "%s (%s)" % [Formatter.strip_tags(str(req.get("title", ""))), tid], "entry": "(prompt)", "text": what, "count": 0}
markers[mk]["count"] += 1
return answer(req, answer_rng, prefer)
var root: Dictionary = await Roller.roll_async(board, start, ctx)
prompts_total += counter[0]
actions.append(ctx.actions)
if ctx.halted == "":
completed += 1
else:
var why := "Action limit" if ctx.halted.begins_with("Stopped after") else ctx.halted
halted[why] = int(halted.get(why, 0)) + 1
for name: String in track:
var v: Variant = Expr.to_value((vars.get(name, {}) as Dictionary).get("value") if vars.get(name) is Dictionary else null)
if v is int or v is float:
var tr: Dictionary = track[name]
tr["min"] = minf(tr["min"], v)
tr["max"] = maxf(tr["max"], v)
tr["sum"] += v
tr["n"] += 1
var run_hits := {}
for st: Dictionary in Roller.flatten(root, []):
var tid := str(st.get("table_id", ""))
run_hits[tid] = int(run_hits.get(tid, 0)) + 1
var eid := str(st.get("entry_id", ""))
var tname := Formatter.strip_tags(str(st.get("table", "")))
if st.get("stop", false):
if not st.get("limit", false) and not st.get("cancelled", false):
var dk := tid + "|" + str(st.get("text", ""))
if not dead_ends.has(dk):
dead_ends[dk] = {"table": "%s (%s)" % [tname, tid], "text": Formatter.strip_tags(str(st.get("text", ""))), "count": 0}
dead_ends[dk]["count"] += 1
continue
table_hits[tid] = int(table_hits.get(tid, 0)) + 1
if eid != "" and not st.has("pass") and not st.has("after"):
entry_hits[tid + ":" + eid] = int(entry_hits.get(tid + ":" + eid, 0)) + 1
elif st.has("pass"):
entry_hits[tid + ":" + _loop_entry_id(board, tid, 0)] = 1
elif st.has("after"):
entry_hits[tid + ":" + _loop_entry_id(board, tid, 1)] = 1
for l: Variant in st.get("effects", []):
if l is Dictionary and (l as Dictionary).get("error", false):
var text := str((l as Dictionary).get("text", ""))
var ek := tid + ":" + eid + "|" + text
if not errors.has(ek):
errors[ek] = {"table": "%s (%s)" % [tname, tid], "entry": _entry_label(board, tid, eid), "text": text, "count": 0}
errors[ek]["count"] += 1
for m in _marker_re().search_all(str(st.get("text", ""))):
var what := Formatter.strip_tags(m.get_string())
var mk := tid + ":" + eid + "|" + what
if not markers.has(mk):
markers[mk] = {"table": "%s (%s)" % [tname, tid], "entry": _entry_label(board, tid, eid), "text": what, "count": 0}
markers[mk]["count"] += 1
if ctx.actions > int(longest["actions"]):
var top: Array = []
for k: String in run_hits:
top.append({"table": k, "count": run_hits[k]})
top = _sorted_by_count(top).slice(0, 8)
longest = {"actions": ctx.actions, "run": run + 1, "top": top}
if run == runs - 1 or (sample_sheet == "" and ctx.halted == ""):
var sheet := Roller.last_sheet(root)
if not sheet.is_empty():
sample_sheet = Formatter.strip_tags(str(sheet.get("summary", "")))
sample_vars = vars.duplicate(true)
sample_halted = ctx.halted
var unreached: Array[String] = []
var unchosen := {}
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE:
continue
if not table_hits.has(t.id):
unreached.append(t.id)
continue
var missing: Array[String] = []
for e in t.entries:
if t.kind == RollTable.KIND_ROLL and not t.can_come_up(e):
continue
if not entry_hits.has(t.id + ":" + e.id):
missing.append(Formatter.strip_tags(e.text).substr(0, 60))
if not missing.is_empty():
unchosen[t.id] = missing
var sorted_actions := actions.duplicate()
sorted_actions.sort()
var total := 0
for a in actions:
total += a
var p95: int = sorted_actions[clampi(ceili(0.95 * sorted_actions.size()) - 1, 0, sorted_actions.size() - 1)]
return {
"runs": runs,
"completed": completed,
"halted": halted,
"actions": {"max": sorted_actions.back(), "mean": float(total) / runs, "p95": p95},
"longest": longest,
"track": track,
"prompts_mean": float(prompts_total) / runs,
"errors": _sorted_by_count(errors.values()),
"dead_ends": _sorted_by_count(dead_ends.values()),
"unset_markers": _sorted_by_count(markers.values()),
"unreached": unreached,
"unchosen": unchosen,
"table_hits": table_hits,
"sample_sheet": sample_sheet,
"sample_vars": sample_vars,
"sample_halted": sample_halted,
}
## The simulated player's reply to a prompt request (docs/LOGIC.md §8): a
## random option or Random for a pick (or an option matching `prefer`), a
## random number in range, a short random word for text.
static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant: static func answer(req: Dictionary, rng: RandomNumberGenerator, prefer: RegEx = null) -> Variant:
return BoardTester.answer(req, rng, prefer) match str(req.get("kind", "pick")):
"number":
return rng.randi_range(int(req.get("min", 0)), int(req.get("max", 0)))
"text":
var letters := "abcdefghijklmnopqrstuvwxyz"
var s := ""
for k in rng.randi_range(3, 8):
s += letters[rng.randi_range(0, letters.length() - 1)]
return s.capitalize()
var options: Array = req.get("options", [])
if prefer != null:
for o: Dictionary in options:
if prefer.search(Formatter.strip_tags(str(o.get("text", "")))) != null:
return int(o["index"])
if options.is_empty():
return -1
# Random (-1) is offered beside every option.
var k := rng.randi_range(-1, options.size() - 1)
return -1 if k < 0 else int(options[k]["index"])
## True when no run hit an error, a dead end or the action limit.
static func is_clean(report: Dictionary) -> bool: static func is_clean(report: Dictionary) -> bool:
return BoardTester.is_clean(report) return (report["errors"] as Array).is_empty() and (report["dead_ends"] as Array).is_empty() \
and not (report["halted"] as Dictionary).has("Action limit")
static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String: static func format_report(r: Dictionary, list: int = 40, show_sheet: bool = true) -> String:
return BoardTester.format_report(r, list, show_sheet) var out := PackedStringArray()
var a: Dictionary = r["actions"]
out.append("Runs: %d completed: %d prompts per run: %.1f" % [r["runs"], r["completed"], r["prompts_mean"]])
var hl := PackedStringArray()
for k: String in r["halted"]:
hl.append("%s %d" % [k, r["halted"][k]])
out.append("Halted: %s" % (", ".join(hl) if not hl.is_empty() else "none"))
out.append("Actions: max %d, mean %.1f, p95 %d" % [a["max"], a["mean"], a["p95"]])
var lg: Dictionary = r.get("longest", {})
if not (lg.get("top", []) as Array).is_empty():
var parts := PackedStringArray()
for x: Dictionary in lg["top"]:
parts.append("%s %d" % [x["table"], x["count"]])
out.append("Longest run (#%d) most-rolled tables: %s" % [lg["run"], ", ".join(parts)])
var tr: Dictionary = r.get("track", {})
for name: String in tr:
var t: Dictionary = tr[name]
if int(t["n"]) == 0:
out.append("@%s: never a number" % name)
else:
out.append("@%s: min %s, mean %.1f, max %s (%d runs)" % [name, Expr.format_value(t["min"]), t["sum"] / t["n"], Expr.format_value(t["max"]), t["n"]])
_section(out, "Effect / expression errors", r["errors"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
_section(out, "Dead ends (rolls that stopped)", r["dead_ends"], list, func(e: Dictionary) -> String:
return "%dx %s: %s" % [e["count"], e["table"], e["text"]])
_section(out, "Unset variables, missing tables and {= } errors in text", r["unset_markers"], list, func(e: Dictionary) -> String:
return "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]])
var un: Array = r["unreached"]
out.append("Tables never reached: %d" % un.size())
for k in mini(list, un.size()):
out.append(" " + str(un[k]))
if un.size() > list:
out.append(" ... and %d more" % (un.size() - list))
var uc: Dictionary = r["unchosen"]
var n_entries := 0
for k: String in uc:
n_entries += (uc[k] as Array).size()
out.append("Entries never chosen: %d in %d reached tables" % [n_entries, uc.size()])
var shown := 0
for k: String in uc:
if shown >= list:
out.append(" ... and %d more tables" % (uc.size() - shown))
break
var items: Array = uc[k]
var names := PackedStringArray()
for x in mini(4, items.size()):
names.append("\"%s\"" % items[x])
out.append(" %s: %d (%s%s)" % [k, items.size(), ", ".join(names), ", ..." if items.size() > 4 else ""])
shown += 1
if show_sheet:
out.append("Sample final sheet%s:" % (" (" + str(r["sample_halted"]) + ")" if str(r["sample_halted"]) != "" else ""))
out.append(str(r["sample_sheet"]) if str(r["sample_sheet"]) != "" else " (no sheet card was reached)")
return "\n".join(out)
static func _section(out: PackedStringArray, title: String, items: Array, list: int, fmt: Callable) -> void:
out.append("%s: %d" % [title, items.size()])
for k in mini(list, items.size()):
out.append(" " + str(fmt.call(items[k])))
if items.size() > list:
out.append(" ... and %d more" % (items.size() - list))
static func _sorted_by_count(list: Array) -> Array:
var out := list.duplicate()
out.sort_custom(func(x: Dictionary, y: Dictionary) -> bool: return int(x["count"]) > int(y["count"]))
return out
static func _entry_label(board: TowerBoard, tid: String, eid: String) -> String:
var t := board.get_table(tid)
if t == null:
return eid
var e := t.find_entry(eid)
return eid if e == null else Formatter.strip_tags(e.text).substr(0, 50)
static func _loop_entry_id(board: TowerBoard, tid: String, index: int) -> String:
var t := board.get_table(tid)
if t == null or t.entries.size() <= index:
return ""
return t.entries[index].id
static var _marker: RegEx = null
static func _marker_re() -> RegEx:
if _marker == null:
_marker = RegEx.create_from_string("\\[url=(?:unset|missing|error):[^\\]]*\\][^\\[]*\\[/url\\]")
return _marker

View file

@ -1,107 +0,0 @@
class_name BoardLayout
extends RefCounted
## Pure layout helpers for whole blocks on the board (group frames, collapsed
## group cards, loose cards), given as world rects. Each returns one offset
## per rect, in the same order; Main moves the blocks.
## Closes the big gaps between blocks while keeping their order.
##
## Blocks whose rows overlap form a band (top to bottom); inside a band,
## blocks whose columns overlap form a column (left to right), which keeps its
## inner layout. Gaps wider than `gap_x` between columns shrink to `gap_x`, the
## first column of every band moves to the board's left edge, and gaps wider
## than `gap_y` between bands shrink to `gap_y`. The mapping only ever moves
## blocks left and up, in order, so nothing that didn't overlap before
## overlaps after, and reading order (left to right, top to bottom) holds.
static func pack(rects: Array, gap_x: float = 60.0, gap_y: float = 60.0) -> Array[Vector2]:
var out: Array[Vector2] = []
out.resize(rects.size())
for i in rects.size():
out[i] = Vector2.ZERO
if rects.is_empty():
return out
var left := INF
for r: Rect2 in rects:
left = minf(left, r.position.x)
var bands := _clusters(rects, range(rects.size()), false)
var y_cursor := 0.0
for b in bands.size():
var band: Dictionary = bands[b]
var new_top: float = band["lo"]
if b > 0:
var prev: Dictionary = bands[b - 1]
new_top = y_cursor + minf(float(band["lo"]) - float(prev["hi"]), gap_y)
var dy := new_top - float(band["lo"])
y_cursor = float(band["hi"]) + dy
var cols := _clusters(rects, band["members"], true)
var x_cursor := left
for c in cols.size():
var col: Dictionary = cols[c]
var new_left := left
if c > 0:
var pc: Dictionary = cols[c - 1]
new_left = x_cursor + minf(float(col["lo"]) - float(pc["hi"]), gap_x)
var dx := new_left - float(col["lo"])
x_cursor = float(col["hi"]) + dx
for i: int in col["members"]:
out[i] = Vector2(dx, dy)
return out
## Groups indices whose rects overlap along one axis (x when `horizontal`)
## into clusters sorted along that axis: [{lo, hi, members}].
static func _clusters(rects: Array, idx: Array, horizontal: bool) -> Array:
var order := idx.duplicate()
order.sort_custom(func(a: int, b: int) -> bool:
var ra: Rect2 = rects[a]
var rb: Rect2 = rects[b]
return (ra.position.x < rb.position.x) if horizontal else (ra.position.y < rb.position.y))
var out: Array = []
for i: int in order:
var r: Rect2 = rects[i]
var lo := r.position.x if horizontal else r.position.y
var hi := r.end.x if horizontal else r.end.y
if not out.is_empty() and lo < float(out[-1]["hi"]):
out[-1]["hi"] = maxf(float(out[-1]["hi"]), hi)
(out[-1]["members"] as Array).append(i)
else:
out.append({"lo": lo, "hi": hi, "members": [i]})
return out
## Makes room for a block that grew from `compact` to `grown` (a group
## expanding in place; both share their top-left corner). Blocks to its right
## whose rows it now covers shift right together, and the blocks below it
## shift down together, each by just enough to clear it with `gap`. Blocks
## that already clear it don't move. Returns one offset per rect.
static func make_room(rects: Array, compact: Rect2, grown: Rect2, gap: float = 60.0) -> Array[Vector2]:
var out: Array[Vector2] = []
out.resize(rects.size())
for i in rects.size():
out[i] = Vector2.ZERO
var right: Array[int] = []
var below: Array[int] = []
for i in rects.size():
var r: Rect2 = rects[i]
if r.position.x >= compact.end.x - 1.0 and r.position.y < grown.end.y + gap and r.end.y > grown.position.y:
right.append(i)
elif r.position.y >= compact.end.y - 1.0:
below.append(i)
var dx := 0.0
for i in right:
var r: Rect2 = rects[i]
if r.position.y < grown.end.y and r.end.y > grown.position.y:
dx = maxf(dx, grown.end.x + gap - r.position.x)
if dx > 0.0:
for i in right:
out[i].x = dx
var dy := 0.0
for i in below:
var r: Rect2 = rects[i]
if r.position.x < grown.end.x + gap and r.end.x > grown.position.x - gap:
dy = maxf(dy, grown.end.y + gap - r.position.y)
if dy > 0.0:
for i in below:
out[i].y = dy
return out

View file

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

View file

@ -1,223 +0,0 @@
class_name BoardSearch
extends RefCounted
## Finds text on a board: table names, result text and details, choice
## prompts, variable names and effects, table details and group names. Text is
## matched as plain text (BBCode stripped with Formatter.strip_tags),
## case-insensitive and ignoring accents. Built once per board revision (the
## index), then queried as the player types.
##
## A result is a Dictionary:
## table_id, entry_id ("" for the card itself), group_id ("" unless the
## match is a group's name), field (FIELD_*), name (card or group name),
## kind (KIND label, e.g. "Table", "Choice", "Group"), group (the card's
## group name, or ""), snippet (one line of plain text around the match),
## hl_from / hl_len (the match inside snippet) and score.
const FIELD_NAME := "name"
const FIELD_GROUP := "group"
const FIELD_VARIABLE := "variable"
const FIELD_PROMPT := "prompt"
const FIELD_RESULT := "result"
const FIELD_EFFECTS := "effects"
const FIELD_DETAILS := "details"
## How much a match in each field counts, before the exact/prefix bonus.
const FIELD_WEIGHT := {
FIELD_NAME: 100, FIELD_GROUP: 90, FIELD_VARIABLE: 80, FIELD_PROMPT: 50,
FIELD_RESULT: 40, FIELD_EFFECTS: 30, FIELD_DETAILS: 20,
}
const KIND_LABELS := {
RollTable.KIND_ROLL: "Table", RollTable.KIND_CHOICE: "Choice", RollTable.KIND_LOOP: "Loop",
RollTable.KIND_VARIABLE: "Variable", RollTable.KIND_SHEET: "Sheet",
}
const SNIPPET_BEFORE := 28
const SNIPPET_AFTER := 60
## Accented letters and the plain letter each folds to (one for one, so
## positions in the folded text are positions in the original).
const _ACCENTS := {
"a": "àáâãäåāăąǎ", "c": "çćĉċč", "d": "ďđ", "e": "èéêëēĕėęě", "g": "ĝğġģ",
"h": "ĥħ", "i": "ìíîïĩīĭįı", "j": "ĵ", "k": "ķ", "l": "ĺļľŀł", "n": "ñńņňʼn",
"o": "òóôõöøōŏőǒ", "r": "ŕŗř", "s": "śŝşšș", "t": "ţťŧț", "u": "ùúûüũūŭůűųǔ",
"w": "ŵ", "y": "ýÿŷ", "z": "źżž",
}
static var _fold_map: Dictionary = {}
## [{table_id, entry_id, group_id, field, text, folded, order}]
var items: Array = []
var _names: Dictionary = {} # table id -> plain name
var _kinds: Dictionary = {} # table id -> kind label
var _groups: Dictionary = {} # table id -> plain group name
func _init(board: TowerBoard = null) -> void:
if board:
build(board)
## Lower case, accents removed; the same length as `s`.
static func fold(s: String) -> String:
if _fold_map.is_empty():
for plain: String in _ACCENTS:
var accented: String = _ACCENTS[plain]
for i in accented.length():
_fold_map[accented[i]] = plain
var low := s.to_lower()
if low.length() != s.length():
low = s # a lower-casing that changes the length; keep positions right
if low.to_utf8_buffer().size() == low.length():
return low # plain ASCII
var parts := PackedStringArray()
for i in low.length():
var ch := low[i]
parts.append(str(_fold_map.get(ch, ch)))
return "".join(parts)
## One-line plain text for an entry, detail or name.
static func plain(text: String) -> String:
if text == "":
return ""
var p := Formatter.strip_tags(text) if text.contains("[") else text
return p.replace("\n", " ").replace("\t", " ").strip_edges()
func build(board: TowerBoard) -> void:
items.clear()
_names.clear()
_kinds.clear()
_groups.clear()
for g in board.groups:
var gname := plain(g.name)
for tid in g.members:
_groups[tid] = gname
_add("", "", g.id, FIELD_GROUP, gname)
_add("", "", g.id, FIELD_DETAILS, plain(g.details))
for t in board.tables:
_names[t.id] = plain(t.name)
_kinds[t.id] = str(KIND_LABELS.get(t.kind, "Table"))
_add(t.id, "", "", FIELD_NAME, _names[t.id])
_add(t.id, "", "", FIELD_DETAILS, plain(t.details))
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
_add(t.id, "", "", FIELD_VARIABLE, "@" + t.var_name)
if t.kind == RollTable.KIND_CHOICE:
_add(t.id, "", "", FIELD_PROMPT, plain(t.prompt))
if t.save_as != "":
_add(t.id, "", "", FIELD_VARIABLE, t.save_as)
for e in t.entries:
_add(t.id, e.id, "", FIELD_RESULT, plain(e.text))
_add(t.id, e.id, "", FIELD_DETAILS, plain(e.details))
if e.effects != "":
_add(t.id, e.id, "", FIELD_EFFECTS, plain(e.effects))
for to: String in e.pipe_save:
var sv := str(e.pipe_save[to])
if sv != "":
_add(t.id, e.id, "", FIELD_VARIABLE, sv)
func _add(tid: String, eid: String, gid: String, field: String, text: String) -> void:
if text == "":
return
items.append({"table_id": tid, "entry_id": eid, "group_id": gid, "field": field,
"text": text, "folded": fold(text), "order": items.size()})
## The best matches for `query`, best first, at most `limit`. Every word of
## the query must appear in the one field; the whole query as typed ranks
## higher, and so do exact names and matches at the start of a word.
func find(query: String, limit: int = 50) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var q := fold(query.strip_edges())
if q == "":
return out
var words := q.split(" ", false)
var scored: Array = []
for it: Dictionary in items:
var f: String = it["folded"]
var at := f.find(q)
var hl_len := q.length()
var score := 0
if at >= 0:
if f == q:
score = 1000
elif at == 0:
score = 300
elif _word_start(f, at):
score = 150
else:
score = 0
elif words.size() > 1:
var all := true
for w in words:
if not f.contains(w):
all = false
break
if not all:
continue
at = f.find(words[0])
hl_len = words[0].length()
score = -10
else:
continue
score += int(FIELD_WEIGHT.get(it["field"], 0))
scored.append([score, f.length(), int(it["order"]), it, at, hl_len])
scored.sort_custom(func(a: Array, b: Array) -> bool:
if a[0] != b[0]:
return a[0] > b[0]
if a[1] != b[1]:
return a[1] < b[1]
return a[2] < b[2])
for i in mini(limit, scored.size()):
var s: Array = scored[i]
out.append(_result(s[3], int(s[4]), int(s[5]), int(s[0])))
return out
## How many items match `query` in all (find() stops at its limit).
func count(query: String) -> int:
return find(query, 1 << 30).size()
static func _word_start(f: String, at: int) -> bool:
if at <= 0:
return true
var prev := f.unicode_at(at - 1)
return not ((prev >= 97 and prev <= 122) or (prev >= 48 and prev <= 57))
func _result(it: Dictionary, at: int, hl_len: int, score: int) -> Dictionary:
var text: String = it["text"]
var from := maxi(0, at - SNIPPET_BEFORE)
var to := mini(text.length(), at + hl_len + SNIPPET_AFTER)
# Start and end at word breaks where that's close by.
if from > 0:
var sp := text.rfind(" ", from + 8)
if sp >= 0 and sp < at and sp > from - 12:
from = sp + 1
var snippet := text.substr(from, to - from)
var hl_from := at - from
if from > 0:
snippet = "…" + snippet
hl_from += 1
if to < text.length():
snippet += "…"
var tid: String = it["table_id"]
var gid: String = it["group_id"]
var r := {"table_id": tid, "entry_id": it["entry_id"], "group_id": gid, "field": it["field"],
"snippet": snippet, "hl_from": hl_from, "hl_len": hl_len, "score": score}
if gid != "":
r["name"] = text if it["field"] == FIELD_GROUP else _group_name(gid)
r["kind"] = "Group"
r["group"] = ""
else:
r["name"] = str(_names.get(tid, tid))
r["kind"] = str(_kinds.get(tid, "Table"))
r["group"] = str(_groups.get(tid, ""))
return r
func _group_name(gid: String) -> String:
for it: Dictionary in items:
if it["group_id"] == gid and it["field"] == FIELD_GROUP:
return it["text"]
return gid

View file

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

View file

@ -4,12 +4,8 @@ extends Control
## cards, the cards, and the ports (pipe ends) on top. Drag the felt to pan, ## cards, the cards, and the ports (pipe ends) on top. Drag the felt to pan,
## Ctrl+wheel or pinch to zoom. ## Ctrl+wheel or pinch to zoom.
## Low enough that Fit shows a whole board of several hundred cards. const MIN_ZOOM := 0.35
const MIN_ZOOM := 0.08
const MAX_ZOOM := 1.5 const MAX_ZOOM := 1.5
## Below this zoom text can't be read, so cards draw as plain cards (their
## contents aren't rendered) and group names show large (CardLayer).
const FAR_ZOOM := 0.22
const WORLD_SIZE := 40000.0 const WORLD_SIZE := 40000.0
var main: Main var main: Main
@ -20,19 +16,6 @@ var cards: CardLayer
var ports: PortLayer var ports: PortLayer
var overlay: Control var overlay: Control
var zoom: float = 1.0 var zoom: float = 1.0
## The overview in the bottom-right corner (hidden unless turned on).
var minimap: Minimap
## Bumped whenever something the layers draw from changes (see _signature):
## cards or groups moved, resized, rebuilt or scrolled, lit results, edits.
## The pipe, port and card layers redraw only when it changes.
var geometry_rev := 0
var _sig_f := PackedFloat32Array()
var _sig_i := PackedInt64Array()
var _view_sig := PackedFloat32Array()
var _view_tween: Tween
var _settle := 0
var _culled_rev := -1
var _panning := false var _panning := false
var _banding := false var _banding := false
@ -60,9 +43,7 @@ func setup(p_main: Main) -> void:
pipes.main = main pipes.main = main
world.add_child(pipes) world.add_child(pipes)
cards = CardLayer.new() cards = CardLayer.new()
cards.main = main
world.add_child(cards) world.add_child(cards)
world.add_child(cards.overlay)
ports = PortLayer.new() ports = PortLayer.new()
ports.main = main ports.main = main
world.add_child(ports) world.add_child(ports)
@ -72,9 +53,6 @@ func setup(p_main: Main) -> void:
overlay.set_anchors_and_offsets_preset(PRESET_FULL_RECT) overlay.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
overlay.draw.connect(_draw_band) overlay.draw.connect(_draw_band)
add_child(overlay) add_child(overlay)
minimap = Minimap.new()
minimap.setup(self)
add_child(minimap)
var img := Image.create(6, 6, false, Image.FORMAT_RGBA8) var img := Image.create(6, 6, false, Image.FORMAT_RGBA8)
img.fill(Color(0, 0, 0, 0)) img.fill(Color(0, 0, 0, 0))
@ -93,89 +71,6 @@ func setup(p_main: Main) -> void:
resized.connect(queue_redraw) resized.connect(queue_redraw)
func _process(_delta: float) -> void:
if main == null or main.data == null:
return
_signature()
var v := PackedFloat32Array([world.position.x, world.position.y, zoom, size.x, size.y])
if v != _view_sig or _culled_rev != geometry_rev:
var far := zoom < FAR_ZOOM
if far != cards.far or (far and (_view_sig.is_empty() or v[2] != _view_sig[2])):
cards.far = far
cards.overlay.queue_redraw()
_view_sig = v
_cull()
minimap.refresh()
## Stops rendering cards and group frames far outside the view (half a
## screen of margin), so a big expanded board only draws what's near, and far
## out (FAR_ZOOM) stops rendering their text (CardLayer sketches them). This
## is the renderer's own visibility, not `visible`: input, layout and the
## pipe geometry are untouched. Runs when the view or the geometry changed.
func _cull() -> void:
_culled_rev = geometry_rev
var view := view_rect()
view = view.grow(maxf(view.size.x, view.size.y) * 0.5)
for layer: Control in [cards, groups]:
for c in layer.get_children():
var n := c as Control
if n == null or not n.visible:
continue
RenderingServer.canvas_item_set_visible(n.get_canvas_item(), view.intersects(Rect2(n.position, n.size).grow(40.0)))
var content := _content_of(n)
if content:
RenderingServer.canvas_item_set_visible(content.get_canvas_item(), content.visible and not cards.far)
## Collects what the layers draw from into two packed arrays and bumps
## geometry_rev when they differ from last frame. Hidden table cards don't
## exist (Main builds them lazily), so this walks only what's on the board.
func _signature() -> void:
var f := PackedFloat32Array()
var ids := PackedInt64Array([main.view_rev, main.mode])
for layer: Control in [cards, groups]:
for c in layer.get_children():
var n := c as Control
if n == null or not n.visible:
continue
f.append(n.position.x)
f.append(n.position.y)
f.append(n.size.x)
f.append(n.size.y)
ids.append(n.get_child(0).get_instance_id() if n.get_child_count() > 0 else 0)
var tc := n as TableCard
if tc and tc.list_scroll != null:
f.append(tc.list_scroll.scroll_vertical)
var changed := f != _sig_f or ids != _sig_i
if changed:
_sig_f = f
_sig_i = ids
# Containers inside a rebuilt card can settle a frame or two later
# without the card's own rect changing, so redraw a little longer.
_settle = 2
elif _settle > 0:
_settle -= 1
changed = true
if changed:
geometry_rev += 1
cards.queue_redraw()
if cards.far:
cards.overlay.queue_redraw()
minimap.refresh()
## The part of a card or group card that holds its text (hidden far out).
func _content_of(n: Control) -> CanvasItem:
if n.get_child_count() == 0:
return null
var first := n.get_child(0)
var gc := n as GroupCard
if gc and gc.group and gc.group.collapsed:
return first.get_child(0) as CanvasItem if first.get_child_count() > 0 else null
return first as CanvasItem
func _draw() -> void: func _draw() -> void:
var r := Rect2(Vector2.ZERO, size) var r := Rect2(Vector2.ZERO, size)
draw_rect(r, Style.FELT) draw_rect(r, Style.FELT)
@ -206,54 +101,12 @@ func fit() -> void:
var bounds := content_bounds() var bounds := content_bounds()
if bounds.size == Vector2.ZERO: if bounds.size == Vector2.ZERO:
return return
stop_animation()
bounds = bounds.grow(20.0) 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) 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.scale = Vector2(zoom, zoom)
world.position = Vector2(maxf(8.0, (size.x - bounds.size.x * zoom) / 2.0), 8.0) - bounds.position * zoom world.position = Vector2(maxf(8.0, (size.x - bounds.size.x * zoom) / 2.0), 8.0) - bounds.position * zoom
## The part of the world the board shows right now.
func view_rect() -> Rect2:
return Rect2(screen_to_world(Vector2.ZERO), size / zoom)
## Pans so a world point sits in the middle of the board.
func center_on(p: Vector2) -> void:
stop_animation()
world.position = size / 2.0 - p * zoom
## Glides to `z` with the world point `p` in the middle (duration 0 jumps).
func animate_to(p: Vector2, z: float, duration: float = 0.3) -> void:
stop_animation()
z = clampf(snappedf(z, 0.01), MIN_ZOOM, MAX_ZOOM)
if duration <= 0.0 or not is_inside_tree():
_apply_view(p, z)
return
var from_p := screen_to_world(size / 2.0)
var from_z := zoom
_view_tween = create_tween().set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT)
_view_tween.tween_method(func(t: float) -> void:
_apply_view(from_p.lerp(p, t), lerpf(from_z, z, t)), 0.0, 1.0, duration)
func is_animating() -> bool:
return _view_tween != null and _view_tween.is_valid() and _view_tween.is_running()
func stop_animation() -> void:
if _view_tween and _view_tween.is_valid():
_view_tween.kill()
_view_tween = null
func _apply_view(p: Vector2, z: float) -> void:
zoom = z
world.scale = Vector2(zoom, zoom)
world.position = size / 2.0 - p * zoom
## The world rect of every visible card, group card and group frame (empty ## The world rect of every visible card, group card and group frame (empty
## when there are none). ## when there are none).
func content_bounds() -> Rect2: func content_bounds() -> Rect2:
@ -292,7 +145,6 @@ func _gui_input(ev: InputEvent) -> void:
return return
_press_at = mb.position _press_at = mb.position
_panning = true _panning = true
stop_animation()
mouse_default_cursor_shape = CURSOR_DRAG mouse_default_cursor_shape = CURSOR_DRAG
else: else:
if _banding and mb.button_index == MOUSE_BUTTON_LEFT: if _banding and mb.button_index == MOUSE_BUTTON_LEFT:

View file

@ -1,29 +1,8 @@
class_name CardLayer class_name CardLayer
extends Control extends Control
## Holds the table cards and paints their hard drop shadow underneath them. ## Holds the table cards and paints their hard drop shadow underneath them.
## Redraws only when the board's geometry changes (BoardView calls
## queue_redraw), not every frame.
##
## Far out (BoardView.FAR_ZOOM) the cards' contents aren't rendered; the
## overlay sketches each card's title line (brass when it holds a lit result)
## and writes group names large enough to read.
##
## It also owns the focus flash (Main.focus_table): a brass ring around a card
## and, optionally, around one of its rows, fading out over FLASH_TIME. The
## flash is drawn in `overlay`, a layer BoardView puts above the cards.
const FLASH_TIME := 1.5
## Drawn above the cards (BoardView adds it to the world after this layer).
var overlay: Control
var main: Main
## True while the board is zoomed out past BoardView.FAR_ZOOM.
var far := false
var _shadow: StyleBoxFlat var _shadow: StyleBoxFlat
var _ring: StyleBoxFlat
var _flash_node: Control = null
var _flash_row: Rect2 = Rect2()
var _flash_left := 0.0
func _init() -> void: func _init() -> void:
@ -31,14 +10,10 @@ func _init() -> void:
# Controls only draw inside their own rect, so cover the whole world. # Controls only draw inside their own rect, so cover the whole world.
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
_shadow = Style.box(Color(0, 0, 0, 0.22), 10) _shadow = Style.box(Color(0, 0, 0, 0.22), 10)
_ring = Style.box(Color(0, 0, 0, 0), 14)
_ring.draw_center = false
Style.bordered(_ring, 4, Style.BRASS) func _process(_delta: float) -> void:
overlay = Control.new() queue_redraw()
overlay.mouse_filter = MOUSE_FILTER_IGNORE
overlay.size = size
overlay.draw.connect(_draw_flash)
set_process(false)
func _draw() -> void: func _draw() -> void:
@ -46,99 +21,3 @@ func _draw() -> void:
var card := c as Control var card := c as Control
if card and card.visible: if card and card.visible:
draw_style_box(_shadow, Rect2(card.position + Vector2(0, 5), card.size)) draw_style_box(_shadow, Rect2(card.position + Vector2(0, 5), card.size))
## Flashes a ring around `node` (a TableCard or GroupCard) for FLASH_TIME.
## `row` is a world rect inside it to ring as well (Rect2() for none).
func flash(node: Control, row: Rect2 = Rect2()) -> void:
_flash_node = node
_flash_row = row
_flash_left = FLASH_TIME
set_process(true)
overlay.queue_redraw()
func is_flashing() -> bool:
return _flash_left > 0.0 and is_instance_valid(_flash_node)
## The world rect of the flashed card, or Rect2() when nothing flashes.
func flash_rect() -> Rect2:
if not is_flashing():
return Rect2()
return Rect2(_flash_node.position, _flash_node.size)
func flash_row_rect() -> Rect2:
return _flash_row if is_flashing() else Rect2()
func _process(delta: float) -> void:
_flash_left -= delta
overlay.queue_redraw()
if _flash_left <= 0.0:
_flash_node = null
set_process(false)
func _draw_flash() -> void:
if far:
_draw_far()
if not is_flashing():
return
var t := clampf(_flash_left / FLASH_TIME, 0.0, 1.0)
# Two quick pulses, then a fade.
var pulse := 0.65 + 0.35 * cos((1.0 - t) * TAU * 2.0)
var a := minf(1.0, t * 2.5) * pulse
var r := Rect2(_flash_node.position, _flash_node.size).grow(8.0)
overlay.draw_style_box(_glow_box(a), r.grow(6.0))
_ring.border_color = Color(Style.BRASS, a)
overlay.draw_style_box(_ring, r)
if _flash_row.size != Vector2.ZERO:
overlay.draw_rect(_flash_row, Color(Style.BRASS, 0.28 * a))
overlay.draw_rect(_flash_row, Color(Style.BRASS_DARK, a), false, 2.5)
func _glow_box(a: float) -> StyleBoxFlat:
var g := Style.box(Color(0, 0, 0, 0), 20)
g.draw_center = false
Style.bordered(g, 8, Color(Style.BRASS, 0.25 * a))
return g
## The far-out sketch: a title line per card, group names in large type.
func _draw_far() -> void:
if main == null or main.data == null:
return
var lit := {}
for k: String in main.lit_entries:
lit[k.substr(0, k.rfind(":"))] = true
var ink := Color(Style.INK, 0.45)
for c in get_children():
var card := c as TableCard
if card == null or not card.visible or card.table == null:
continue
var p := card.position
var w := card.size.x
overlay.draw_rect(Rect2(p + Vector2(14, 16), Vector2(w * 0.6, 16)), ink)
if lit.has(card.table.id):
overlay.draw_rect(Rect2(p + Vector2(0, 46), Vector2(w, minf(40.0, card.size.y - 52.0))), Style.BRASS)
var z := main.board.zoom
var font := Style.display(true)
for g in main.data.groups:
var n := main.group_node(g.id)
if n == null:
continue
var r := Rect2(n.position, n.size)
var text := Formatter.strip_tags(g.name)
var fs := int(18.0 / z)
var tw := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var room := maxf(r.size.x, 520.0) * 1.1
if tw > room:
fs = maxi(8, int(fs * room / tw))
tw = font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var at := Vector2(r.position.x + (r.size.x - tw) / 2.0, r.position.y + fs * 0.85)
if g.collapsed:
at.y = r.position.y + r.size.y / 2.0 + fs * 0.3
overlay.draw_string_outline(font, at, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, maxi(2, int(4.0 / z)), Style.FELT_DEEP)
overlay.draw_string(font, at, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.ON_FELT if not g.collapsed else Style.BRASS)

View file

@ -229,8 +229,6 @@ func table_summary(t: RollTable) -> String:
return "Variable @%s · %s" % [t.var_name, t.var_type] return "Variable @%s · %s" % [t.var_name, t.var_type]
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
return "Sheet" return "Sheet"
RollTable.KIND_ROUTER:
return "Router · %d cases · the first true case is taken" % t.entries.size()
var parts := PackedStringArray([t.dice_label()]) var parts := PackedStringArray([t.dice_label()])
parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"]) parts.append("%d %s" % [t.entries.size(), "ranges" if t.is_ranged() else "results"])
if t.card_mode: if t.card_mode:

View file

@ -5,7 +5,6 @@ extends MenuButton
const ID_RESET := 1 const ID_RESET := 1
const ID_IMPORT := 2 const ID_IMPORT := 2
const ID_TEST := 3
const ID_EXPORT := 100 const ID_EXPORT := 100
## Export formats: label, file extension, FileDialog filter. ## Export formats: label, file extension, FileDialog filter.
@ -28,7 +27,6 @@ const IMPORT_FILTERS: Array[String] = [
signal reset_requested signal reset_requested
signal import_requested signal import_requested
signal export_requested(format: Dictionary) signal export_requested(format: Dictionary)
signal test_requested
func setup(can_reset: bool, can_import: bool) -> void: func setup(can_reset: bool, can_import: bool) -> void:
@ -46,7 +44,6 @@ func setup(can_reset: bool, can_import: bool) -> void:
var pm := get_popup() var pm := get_popup()
ModalCard.style_popup(pm) ModalCard.style_popup(pm)
pm.add_item("Reset sample", ID_RESET) pm.add_item("Reset sample", ID_RESET)
pm.add_item("Test board…", ID_TEST)
pm.add_separator("Import") pm.add_separator("Import")
pm.add_item("Import as new collection…", ID_IMPORT) pm.add_item("Import as new collection…", ID_IMPORT)
pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import) pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import)
@ -56,8 +53,6 @@ func setup(can_reset: bool, can_import: bool) -> void:
pm.id_pressed.connect(func(id: int) -> void: pm.id_pressed.connect(func(id: int) -> void:
if id == ID_RESET: if id == ID_RESET:
reset_requested.emit() reset_requested.emit()
elif id == ID_TEST:
test_requested.emit()
elif id == ID_IMPORT: elif id == ID_IMPORT:
import_requested.emit() import_requested.emit()
elif id >= ID_EXPORT and id < ID_EXPORT + EXPORTS.size(): elif id >= ID_EXPORT and id < ID_EXPORT + EXPORTS.size():

View file

@ -22,10 +22,6 @@ var lit_pipes: Dictionary = {} # "tid:eid>to" -> true
var current: Dictionary = {} var current: Dictionary = {}
var history: Array = [] var history: Array = []
var rng := RandomNumberGenerator.new() var rng := RandomNumberGenerator.new()
## Bumped by mark_dirty and _refresh_lit; BoardView redraws its layers when it changes.
var view_rev := 0
## Bumped by mark_dirty: the search index is rebuilt when it changes.
var edit_rev := 0
var board: BoardView var board: BoardView
var tray: ResultTray var tray: ResultTray
@ -216,23 +212,14 @@ func _build_top_bar() -> Control:
_board_menu.setup(true, collections_enabled()) _board_menu.setup(true, collections_enabled())
_board_menu.reset_requested.connect(reset_sample) _board_menu.reset_requested.connect(reset_sample)
_board_menu.import_requested.connect(import_collection) _board_menu.import_requested.connect(import_collection)
_board_menu.test_requested.connect(open_test_board)
_board_menu.export_requested.connect(export_collection) _board_menu.export_requested.connect(export_collection)
tools.add_child(_board_menu) tools.add_child(_board_menu)
var test_btn := Style.bar_button("Test board…")
test_btn.tooltip_text = "Roll the board many times and look for problems"
test_btn.pressed.connect(open_test_board)
tools.add_child(test_btn)
tools.add_child(_make_arrange_menu())
tools.visible = false tools.visible = false
h.add_child(tools) h.add_child(tools)
_endless_chip = _make_endless_chip() _endless_chip = _make_endless_chip()
h.add_child(_endless_chip) h.add_child(_endless_chip)
_search_button = _make_search_button()
h.add_child(_search_button)
_collapse_all = Style.bar_button("Collapse all") _collapse_all = Style.bar_button("Collapse all")
_collapse_all.tooltip_text = "Collapse or expand every table at once" _collapse_all.tooltip_text = "Collapse or expand every table at once"
_collapse_all.pressed.connect(func() -> void: set_all_collapsed(_any_expanded())) _collapse_all.pressed.connect(func() -> void: set_all_collapsed(_any_expanded()))
@ -253,8 +240,6 @@ func _build_top_bar() -> Control:
zin.pressed.connect(func() -> void: board.set_zoom(board.zoom * 1.15)) zin.pressed.connect(func() -> void: board.set_zoom(board.zoom * 1.15))
for b in [zout, zfit, zin]: for b in [zout, zfit, zin]:
zoom.add_child(b) zoom.add_child(b)
_map_toggle = _make_map_toggle()
zoom.add_child(_map_toggle)
h.add_child(zoom) h.add_child(zoom)
return bar return bar
@ -347,14 +332,16 @@ func is_entry_lit(tid: String, eid: String) -> bool:
return lit_entries.has(Roller.entry_key(tid, eid)) return lit_entries.has(Roller.entry_key(tid, eid))
## Rebuilds every card. Cards hidden in collapsed groups aren't built at all
## (card_for gives null for them) until their group expands; see
## _apply_group_visibility.
func _rebuild_cards() -> void: func _rebuild_cards() -> void:
for c in board.cards.get_children(): for c in board.cards.get_children():
board.cards.remove_child(c) board.cards.remove_child(c)
c.queue_free() c.queue_free()
cards.clear() cards.clear()
for t in data.tables:
var card := TableCard.new()
board.cards.add_child(card)
card.setup(self, t)
cards[t.id] = card
selection.clear() selection.clear()
_rebuild_groups() _rebuild_groups()
_update_selection_bar() _update_selection_bar()
@ -362,7 +349,6 @@ func _rebuild_cards() -> void:
func _refresh_lit() -> void: func _refresh_lit() -> void:
view_rev += 1
for card in cards.values(): for card in cards.values():
(card as TableCard).refresh_lit() (card as TableCard).refresh_lit()
_refresh_group_lits() _refresh_group_lits()
@ -385,15 +371,12 @@ func set_mode(m: Mode) -> void:
for n in _group_nodes.values(): for n in _group_nodes.values():
(n as GroupCard).rebuild() (n as GroupCard).rebuild()
_update_endless_chip() _update_endless_chip()
_nav_mode_changed()
func mark_dirty() -> void: func mark_dirty() -> void:
if _saving_enabled: if _saving_enabled:
_save_timer.start() _save_timer.start()
_ref_cache.clear() _ref_cache.clear()
view_rev += 1
edit_rev += 1
_update_collapse_all() _update_collapse_all()
_update_endless_chip() _update_endless_chip()
if mode == Mode.BUILD: if mode == Mode.BUILD:
@ -434,9 +417,7 @@ func set_all_collapsed(collapsed: bool) -> void:
for t in data.tables: for t in data.tables:
if t.collapsed != collapsed: if t.collapsed != collapsed:
t.collapsed = collapsed t.collapsed = collapsed
var card := card_for(t.id) card_for(t.id).rebuild()
if card:
card.rebuild()
var changed := false var changed := false
for g in data.groups: for g in data.groups:
if g.collapsed != collapsed: if g.collapsed != collapsed:
@ -454,7 +435,6 @@ const ADD_KINDS := [
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"], ["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"], ["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
["Loop", RollTable.KIND_LOOP, "times", "Repeat"], ["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
["Router: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Router"],
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"], ["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
["Sheet", RollTable.KIND_SHEET, "", "Sheet"], ["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
] ]
@ -602,8 +582,7 @@ func delete_table(tid: String) -> void:
selection.erase(tid) selection.erase(tid)
var card := card_for(tid) var card := card_for(tid)
cards.erase(tid) cards.erase(tid)
if card: card.queue_free()
card.queue_free()
for c in cards.values(): for c in cards.values():
(c as TableCard).rebuild() (c as TableCard).rebuild()
if in_group: if in_group:
@ -749,34 +728,15 @@ func _groups_changed() -> void:
_update_collapse_all() _update_collapse_all()
## Builds the cards that are on show and frees the ones hidden in collapsed
## groups, so a big board with most of it collapsed stays light.
func _apply_group_visibility() -> void: func _apply_group_visibility() -> void:
_hidden_cache = null _hidden_cache = null
var hidden := hidden_groups() var hidden := hidden_groups()
var built := false for tid: String in cards:
for t in data.tables: var c: TableCard = cards[tid]
var c: TableCard = cards.get(t.id) var hide := hidden.has(tid)
if hidden.has(t.id): c.visible = not hide
if c: if hide and selection.erase(tid):
selection.erase(t.id) c.set_selected(false)
cards.erase(t.id)
# Hidden until it goes at the end of the frame (a deferred
# call of its own may still run).
c.hide()
c.queue_free()
elif c == null:
c = TableCard.new()
board.cards.add_child(c)
c.setup(self, t)
cards[t.id] = c
built = true
if built:
# Collapsed group cards stay on top of the table cards.
for g in data.groups:
var n := group_node(g.id)
if g.collapsed and n and n.get_parent() == board.cards:
board.cards.move_child(n, -1)
_update_selection_bar() _update_selection_bar()
@ -804,21 +764,10 @@ func toggle_group(gid: String) -> void:
var g := data.get_group(gid) var g := data.get_group(gid)
if g == null: if g == null:
return return
var compact := Rect2()
var blocks: Array = []
var n := group_node(gid)
if g.collapsed and n:
compact = Rect2(n.position, n.size)
blocks = _layout_blocks(gid)
g.collapsed = not g.collapsed g.collapsed = not g.collapsed
details().hide_for() details().hide_for()
_groups_changed() _groups_changed()
mark_dirty() mark_dirty()
if not g.collapsed:
var room := _make_room_for(g, compact, blocks)
if int(room["moved"]) > 0:
toast("Opened %s and moved %d %s to make room" % [Formatter.strip_tags(g.name), room["moved"],
"block" if int(room["moved"]) == 1 else "blocks"], room["snap"])
func set_group_collapsed(gid: String, collapsed: bool) -> void: func set_group_collapsed(gid: String, collapsed: bool) -> void:
@ -1673,7 +1622,6 @@ func _run_cli(args: PackedStringArray) -> void:
if roll != "": if roll != "":
start_roll(roll, args.has("--fast")) start_roll(roll, args.has("--fast"))
_run_cli_extras(args) _run_cli_extras(args)
_run_test_board_cli(args)
var shot := _arg_value(args, "--screenshot") var shot := _arg_value(args, "--screenshot")
if shot == "": if shot == "":
return return
@ -2070,7 +2018,7 @@ func _run_group_cli(args: PackedStringArray) -> void:
# A card held over the first group's frame, to show the drop highlight. # A card held over the first group's frame, to show the drop highlight.
var g := data.groups[0] var g := data.groups[0]
for t in data.tables: for t in data.tables:
if not g.has(t.id) and card_for(t.id) and card_for(t.id).visible: if not g.has(t.id) and card_for(t.id).visible:
var c := card_for(t.id) var c := card_for(t.id)
c.get_parent().move_child(c, -1) c.get_parent().move_child(c, -1)
begin_card_drag(c) begin_card_drag(c)
@ -2425,9 +2373,6 @@ func _load_board_file(path: String) -> void:
func _run_cli_extras(args: PackedStringArray) -> void: func _run_cli_extras(args: PackedStringArray) -> void:
if args.has("--perf"):
_run_perf()
_run_nav_cli(args)
if args.has("--clear-result"): if args.has("--clear-result"):
# Keeps the board lit but empties the tray (a tall sheet result can fill it). # Keeps the board lit but empties the tray (a tall sheet result can fill it).
current = {} current = {}
@ -2459,477 +2404,3 @@ func _run_cli_extras(args: PackedStringArray) -> void:
await get_tree().process_frame await get_tree().process_frame
details().show_table(card, det) details().show_table(card, det)
details().pin(card.get_global_rect().position + Vector2(60, 46)) details().pin(card.get_global_rect().position + Vector2(60, 46))
# ---------- Test board ----------
## Build: opens the Test board dialog (core/board_tester.gd), which keeps its
## last report while the app is open.
func open_test_board() -> void:
_add_modal(TestBoardDialog.new(self))
# --test-board open the Test board dialog (shows the last report if any)
# --test-board-run=<runs> ... and start a test with that many runs (100, 500 or 1000)
func _run_test_board_cli(args: PackedStringArray) -> void:
var n := _arg_value(args, "--test-board-run")
if not args.has("--test-board") and n == "":
return
set_mode(Mode.BUILD)
var d := TestBoardDialog.new(self)
_add_modal(d)
if n != "":
d.runs = n.to_int()
d.run_test()
# ---------- Navigation: search, focus, minimap, pack, lazy cards ----------
## --perf: times a reload of the current board and the frame cost while idle
## and while panning (vsync off), then prints the numbers and quits.
func _run_perf() -> void:
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
Engine.max_fps = 0
var text := data.to_json()
for i in 10:
await get_tree().process_frame
var t0 := Time.get_ticks_usec()
data.load_json(text)
var tj := Time.get_ticks_usec()
_rebuild_cards()
var t1 := Time.get_ticks_usec()
_seed_session()
var t2 := Time.get_ticks_usec()
await get_tree().process_frame
await get_tree().process_frame
var t3 := Time.get_ticks_usec()
board.fit()
print("PERF load: parse %.1f ms, rebuild_cards %.1f ms, seed %.1f ms, first two frames %.1f ms, total %.1f ms" % [
(tj - t0) / 1000.0, (t1 - tj) / 1000.0, (t2 - t1) / 1000.0, (t3 - t2) / 1000.0, (t3 - t0) / 1000.0])
print("PERF nodes: %d, table cards built: %d of %d" % [Performance.get_monitor(Performance.OBJECT_NODE_COUNT), cards.size(), data.tables.size()])
for i in 30:
await get_tree().process_frame
print("PERF idle (fit view): %s" % await _perf_frames(240, Vector2.ZERO))
board.set_zoom(0.6)
print("PERF pan (zoom 0.6): %s" % await _perf_frames(240, Vector2(-6, -2)))
board.set_zoom(1.0)
print("PERF idle (zoom 1): %s" % await _perf_frames(240, Vector2.ZERO))
print("PERF pan (zoom 1): %s" % await _perf_frames(240, Vector2(-6, -2)))
if OS.get_cmdline_user_args().has("--perf-layers"):
board.fit()
print("PERF idle (fit view again): %s" % await _perf_frames(120, Vector2.ZERO))
board.pipes.visible = false
print("PERF idle, no pipes: %s" % await _perf_frames(120, Vector2.ZERO))
board.ports.visible = false
print("PERF idle, no pipes or ports: %s" % await _perf_frames(120, Vector2.ZERO))
board.cards.visible = false
print("PERF idle, no cards either: %s" % await _perf_frames(120, Vector2.ZERO))
board.set_process(false)
board.groups.set_process(false)
print("PERF idle, board and group processing off: %s" % await _perf_frames(120, Vector2.ZERO))
get_tree().quit()
func _perf_frames(n: int, pan: Vector2) -> String:
var times: Array[float] = []
var last := Time.get_ticks_usec()
for i in n:
if pan != Vector2.ZERO:
board.world.position += pan
await get_tree().process_frame
var now := Time.get_ticks_usec()
times.append((now - last) / 1000.0)
last = now
times.sort()
var total := 0.0
for t in times:
total += t
return "mean %.2f ms, median %.2f ms, p95 %.2f ms" % [total / n, times[n / 2], times[int(n * 0.95)]]
# ----- Search (top bar, Ctrl+F) -----
var _search_button: Button
var _search_panel: SearchPanel
var _map_toggle: Button
## focus_table zooms in to at least this, so the card can be read.
const READABLE_ZOOM := 0.85
## ...but zooms out as far as this to fit a tall card.
const MIN_FOCUS_ZOOM := 0.7
func _make_search_button() -> Button:
var b := Style.bar_button("Search")
b.tooltip_text = "Find a card by its name, results, prompt, variables or group (Ctrl+F)"
_bar_icon(b, func(c: Control) -> void:
c.draw_arc(Vector2(6.5, 6.5), 5.0, 0.0, TAU, 24, Style.ON_FELT, 1.8, true)
c.draw_line(Vector2(10.3, 10.3), Vector2(14.5, 14.5), Style.ON_FELT, 2.4, true))
b.pressed.connect(toggle_search)
return b
## Puts a 16 px drawn icon at the left of a top-bar button.
func _bar_icon(b: Button, paint: Callable) -> void:
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled"]:
var sb := b.get_theme_stylebox(n) as StyleBoxFlat
if sb:
sb.content_margin_left = 32
var icon := Control.new()
icon.mouse_filter = MOUSE_FILTER_IGNORE
icon.size = Vector2(16, 16)
icon.draw.connect(paint.bind(icon))
b.add_child(icon)
b.resized.connect(func() -> void: icon.position = Vector2(11, roundf((b.size.y - 16.0) / 2.0)))
func toggle_search() -> void:
if _search_panel and _search_panel.visible:
_search_panel.close()
else:
open_search()
## Opens the search pop-over (Ctrl+F), with its field focused.
func open_search() -> SearchPanel:
if _search_panel == null:
_search_panel = SearchPanel.new()
add_child(_search_panel)
_search_panel.setup(self)
_search_panel.open(_search_button)
return _search_panel
func _shortcut_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed or k.echo:
return
if k.keycode == KEY_F and (k.ctrl_pressed or k.meta_pressed) and not k.alt_pressed:
open_search()
get_viewport().set_input_as_handled()
elif k.keycode == KEY_M and not (k.ctrl_pressed or k.meta_pressed or k.alt_pressed or k.shift_pressed):
var f := get_viewport().gui_get_focus_owner()
if f is LineEdit or f is TextEdit:
return
set_minimap_visible(not board.minimap.visible, true)
get_viewport().set_input_as_handled()
# ----- Focus: jump to a card -----
## Shows a card: expands its group if that's collapsed (saved, with a toast),
## expands the card if it's collapsed and an entry was asked for, glides the
## view so the card sits in the middle at a readable zoom and flashes a ring
## around it. With `entry_id`, a long list scrolls to that result
## (TableCard.reveal) and its row flashes too. Unknown ids do nothing.
func focus_table(table_id: String, entry_id: String = "") -> void:
var t := data.get_table(table_id)
if t == null:
return
if entry_id != "" and t.find_entry(entry_id) == null:
entry_id = ""
var notes := PackedStringArray()
var snap := ""
var settle := false
var g := data.group_of(table_id)
if g and g.collapsed:
var info := _expand_group(g)
notes.append("Opened group %s" % Formatter.strip_tags(g.name))
if int(info["moved"]) > 0:
notes.append("moved %d %s to make room" % [info["moved"], "block" if int(info["moved"]) == 1 else "blocks"])
snap = info["snap"]
settle = true
if entry_id != "" and t.collapsed and t.kind != RollTable.KIND_VARIABLE and t.kind != RollTable.KIND_SHEET:
t.collapsed = false
var c0 := card_for(table_id)
if c0:
c0.rebuild()
mark_dirty()
settle = true
var card := card_for(table_id)
if card == null:
return
if settle or card.size.y <= 0.0:
# Let a card that was just built or expanded lay out before measuring it.
for i in 3:
await get_tree().process_frame
card = card_for(table_id)
if card == null:
return
# On top of any card it overlaps.
card.get_parent().move_child(card, -1)
if entry_id != "":
card.reveal(entry_id)
var r := Rect2(card.position, card.size)
board.animate_to(_focus_point(r), _focus_zoom(r))
board.cards.flash(card)
if not notes.is_empty():
toast(", ".join(notes), snap)
if entry_id != "":
# The list scrolls on the next layout pass; ring the row after it.
await get_tree().process_frame
if is_instance_valid(card):
board.cards.flash(card, entry_rect(card, entry_id))
## Centres a group: its frame, or its compact card when collapsed (which
## isn't expanded), and flashes it.
func focus_group(gid: String) -> void:
var g := data.get_group(gid)
var n := group_node(gid)
if g == null or n == null:
return
if g.collapsed:
n.get_parent().move_child(n, -1)
var r := Rect2(n.position, n.size)
var z := _focus_zoom(r) if g.collapsed else clampf(_fit_zoom(r), BoardView.MIN_ZOOM, READABLE_ZOOM)
board.animate_to(r.get_center() if not g.collapsed or r.size.y * z < board.size.y else _focus_point(r), z)
board.cards.flash(n)
## The world rect of an entry's row on a card (anchor_for geometry), or Rect2().
func entry_rect(card: TableCard, eid: String) -> Rect2:
var a := card.anchor_for(eid)
var row: Control = card.rows.get(eid)
if a.is_empty() or row == null:
return Rect2()
var p: Vector2 = a["pos"]
var h := row.size.y
return Rect2(card.position.x + 3.0, p.y - h / 2.0, card.size.x - 6.0, h)
func _fit_zoom(r: Rect2) -> float:
return minf((board.size.x - 80.0) / maxf(r.size.x, 1.0), (board.size.y - 80.0) / maxf(r.size.y, 1.0))
func _focus_zoom(r: Rect2) -> float:
var z := maxf(board.zoom, READABLE_ZOOM)
return clampf(minf(z, maxf(MIN_FOCUS_ZOOM, _fit_zoom(r))), BoardView.MIN_ZOOM, BoardView.MAX_ZOOM)
## The middle of a card, or a point that keeps its top in view when it's
## taller than the board at the zoom focus_table picks.
func _focus_point(r: Rect2) -> Vector2:
var z := _focus_zoom(r)
var c := r.get_center()
if r.size.y > (board.size.y - 80.0) / z:
c.y = r.position.y - 40.0 / z + board.size.y / 2.0 / z
return c
## Expands a collapsed group (saved) and makes room for it. Returns
## _make_room_for's {moved, snap}.
func _expand_group(g: TableGroup) -> Dictionary:
var n := group_node(g.id)
var compact := Rect2(n.position, n.size) if n else Rect2()
var blocks := _layout_blocks(g.id)
g.collapsed = false
details().hide_for()
_groups_changed()
mark_dirty()
return _make_room_for(g, compact, blocks)
# ----- Minimap -----
func _make_map_toggle() -> Button:
var b := Style.bar_button("Map")
b.toggle_mode = true
b.tooltip_text = "Show an overview of the board in the corner (M)"
var on := Style.bordered(Style.box(Color(Style.BRASS, 0.16), 8, [12, 6, 12, 6]), 1, Style.BRASS)
b.add_theme_stylebox_override("pressed", on)
b.add_theme_stylebox_override("hover_pressed", on)
_bar_icon(b, func(c: Control) -> void:
c.draw_rect(Rect2(1, 2, 14, 12), Style.ON_FELT, false, 1.5)
c.draw_rect(Rect2(4, 5, 4, 3), Style.ON_FELT)
c.draw_rect(Rect2(9, 8, 3, 3), Style.BRASS))
b.toggled.connect(func(pressed: bool) -> void: set_minimap_visible(pressed, true))
_nav_mode_changed.call_deferred()
return b
## Shows or hides the minimap; `remember` saves the choice for this mode.
func set_minimap_visible(on: bool, remember: bool = false) -> void:
if board == null:
return
board.minimap.visible = on
if _map_toggle:
_map_toggle.set_pressed_no_signal(on)
if remember and state:
state.set_setting(_minimap_key(), on)
state.save()
func _minimap_key() -> String:
return "minimap_build" if mode == Mode.BUILD else "minimap_play"
## Off by default in Play (which stays simple), on by default in Build;
## either is remembered once toggled.
func _minimap_default() -> bool:
var dflt := mode == Mode.BUILD
return bool(state.get_setting(_minimap_key(), dflt)) if state else dflt
## set_mode calls this after switching.
func _nav_mode_changed() -> void:
set_minimap_visible(_minimap_default())
# ----- Arrange: pack collapsed groups -----
const PACK_GAP := 60.0
const ARRANGE_PACK := 0
func _make_arrange_menu() -> MenuButton:
var mb := MenuButton.new()
mb.text = "Arrange ▾"
mb.tooltip_text = "Tidy the layout of the board"
mb.flat = false
var ref := Style.bar_button("")
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_font_size_override("font_size", 15)
mb.mouse_default_cursor_shape = CURSOR_POINTING_HAND
ref.free()
var pm := mb.get_popup()
ModalCard.style_popup(pm)
pm.add_item("Pack collapsed groups", ARRANGE_PACK)
pm.set_item_tooltip(0, "Move collapsed groups and the cards between them together, closing the gaps, in reading order")
pm.id_pressed.connect(func(id: int) -> void:
if id == ARRANGE_PACK:
pack_collapsed_groups())
return mb
## The blocks Pack and make-room move: every group (its compact card when
## collapsed, its frame when expanded) and every card in no group, as
## [{rect, group, table}] with one of group / table set. `skip` is a group id
## to leave out.
func _layout_blocks(skip: String = "") -> Array:
var out: Array = []
var grouped := {}
for g in data.groups:
for tid in g.members:
grouped[tid] = true
if g.id == skip:
continue
var r := g.rect()
if g.collapsed:
var n := group_node(g.id)
r = Rect2(n.position, n.size) if n else Rect2(g.position, Vector2(TableCard.WIDTH, 120))
out.append({"rect": r, "group": g.id, "table": ""})
for t in data.tables:
if grouped.has(t.id):
continue
var c := card_for(t.id)
var r := Rect2(c.position, c.size) if c else Rect2(t.position, Vector2(TableCard.WIDTH, 120))
out.append({"rect": r, "group": "", "table": t.id})
return out
func _move_block(b: Dictionary, delta: Vector2) -> void:
if delta == Vector2.ZERO:
return
if b["group"] != "":
move_group(str(b["group"]), delta)
else:
var t := data.get_table(str(b["table"]))
t.position += delta
var c := card_for(t.id)
if c:
c.position = t.position
## Build ▸ Arrange ▸ Pack collapsed groups: closes the gaps that collapsed
## blocks leave (BoardLayout.pack), keeping reading order, then fits the view.
## Saved, with undo. Returns how many blocks moved.
func pack_collapsed_groups() -> int:
var any := false
for g in data.groups:
if g.collapsed:
any = true
break
if not any:
toast("Collapse some groups first: Pack closes the gaps they leave")
return 0
var blocks := _layout_blocks()
var rects: Array = []
for b: Dictionary in blocks:
rects.append(b["rect"])
var offsets := BoardLayout.pack(rects, PACK_GAP, PACK_GAP)
var snap := _snapshot()
var moved := 0
for i in blocks.size():
var d := offsets[i].round()
if d != Vector2.ZERO:
_move_block(blocks[i], d)
moved += 1
if moved == 0:
toast("Already packed")
return 0
mark_dirty()
toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], snap)
await get_tree().process_frame
await get_tree().process_frame
board.fit()
return moved
## After a group expands in place: if its frame now covers other blocks, they
## shift right or down to clear it (BoardLayout.make_room). `blocks` are the
## other blocks (_layout_blocks) measured before the group expanded, while
## every group card was laid out. Returns {moved, snap}, snap being the board
## before the move (for an undo toast).
func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
if compact.size == Vector2.ZERO or blocks.is_empty():
return {"moved": 0, "snap": ""}
var grown := g.rect()
var rects: Array = []
var hits := false
for b: Dictionary in blocks:
var r: Rect2 = b["rect"]
rects.append(r)
if r.intersects(grown):
hits = true
if not hits:
return {"moved": 0, "snap": ""}
var snap := _snapshot()
var offsets := BoardLayout.make_room(rects, compact, grown, PACK_GAP)
var moved := 0
for i in blocks.size():
var d := offsets[i].round()
if d != Vector2.ZERO:
_move_block(blocks[i], d)
moved += 1
if moved > 0:
mark_dirty()
return {"moved": moved, "snap": snap}
# ----- Navigation screenshot flags -----
# --search=<text> open the search panel with that query
# --focus=<table id>[:<entry id>] jump to a card (and result)
# --minimap / --no-minimap show or hide the overview
# --pack Build ▸ Arrange ▸ Pack collapsed groups
# --perf print load and frame timings, then quit
func _run_nav_cli(args: PackedStringArray) -> void:
if args.has("--minimap"):
set_minimap_visible(true)
if args.has("--no-minimap"):
set_minimap_visible(false)
if args.has("--pack"):
await pack_collapsed_groups()
var f := _arg_value(args, "--focus")
if f != "":
await get_tree().process_frame
focus_table(f.get_slice(":", 0), f.get_slice(":", 1) if f.contains(":") else "")
var q := _arg_value(args, "--search")
if q != "":
await get_tree().process_frame
var p := open_search()
p.field.text = q
p.refresh()

View file

@ -1,164 +0,0 @@
class_name Minimap
extends Control
## A small overview of the whole board in the bottom-right corner: group
## frames and collapsed group cards as tinted blocks, cards as card-coloured
## rectangles (brass when they hold a lit result) and the part of the board
## in view as a rectangle. Click or drag on it to pan there.
##
## It only redraws when BoardView asks (the view moved, or the board's
## geometry changed), never every frame. The map's scale comes from the
## board's content, so it holds still while panning.
const MAX_SIZE := Vector2(232, 160)
const MARGIN := 14.0
const PAD := 8.0
var board: BoardView
var _bg: StyleBoxFlat
var _dragging := false
## World rect the map shows, and how it maps onto the map's inner rect.
var _world := Rect2()
var _scale := 1.0
var _offset := Vector2.ZERO
var _rev := -1
func setup(p_board: BoardView) -> void:
board = p_board
mouse_filter = MOUSE_FILTER_STOP
mouse_default_cursor_shape = CURSOR_POINTING_HAND
tooltip_text = "Overview: click or drag to move around (M)"
_bg = Style.bordered(Style.box(Color(Style.FELT_DEEP, 0.92), 10), 1, Color(1, 1, 1, 0.16))
_bg.shadow_color = Color(0, 0, 0, 0.35)
_bg.shadow_size = 12
_bg.shadow_offset = Vector2(0, 4)
visible = false
size = MAX_SIZE
board.resized.connect(place)
## Re-places and redraws the map (BoardView calls this when the view or the
## board's geometry changed). Does nothing while hidden.
func refresh() -> void:
if not visible:
return
place()
queue_redraw()
## Keeps the map in the board's bottom-right corner, sized to the content's shape.
func place() -> void:
if board == null:
return
_refresh_frame()
position = board.size - size - Vector2(MARGIN, MARGIN)
func _notification(what: int) -> void:
if what == NOTIFICATION_VISIBILITY_CHANGED and visible:
_rev = -1
refresh()
## Recomputes the world rect and scale from the board's content (only when
## the board's geometry changed).
func _refresh_frame() -> void:
if _rev == board.geometry_rev and _world.size != Vector2.ZERO:
return
_rev = board.geometry_rev
var b := board.content_bounds()
if b.size == Vector2.ZERO:
b = Rect2(Vector2.ZERO, Vector2(1000, 700))
b = b.grow(maxf(b.size.x, b.size.y) * 0.03 + 40.0)
set_world(b)
## Sets the world rect the map covers and resizes the map to its shape.
func set_world(b: Rect2) -> void:
_world = b
var inner := MAX_SIZE - Vector2(PAD, PAD) * 2.0
_scale = minf(inner.x / b.size.x, inner.y / b.size.y)
var used := b.size * _scale
size = Vector2(maxf(used.x, 90.0), maxf(used.y, 60.0)) + Vector2(PAD, PAD) * 2.0
_offset = (size - used) / 2.0
func world_to_map(p: Vector2) -> Vector2:
return _offset + (p - _world.position) * _scale
func map_to_world(p: Vector2) -> Vector2:
return _world.position + (p - _offset) / _scale
## The board's view as a rect on the map (map coordinates).
func view_rect_on_map() -> Rect2:
var v := board.view_rect()
return Rect2(world_to_map(v.position), v.size * _scale)
func _draw() -> void:
if board == null or board.main == null or board.main.data == null:
return
var main := board.main
draw_style_box(_bg, Rect2(Vector2.ZERO, size))
var inner := Rect2(Vector2(3, 3), size - Vector2(6, 6))
# Expanded group frames first, then cards and collapsed groups on top.
for g in main.data.groups:
if not g.collapsed:
_block(g.rect(), Color(0, 0, 0, 0.28), Color(1, 1, 1, 0.18), inner)
var hidden := main.hidden_groups()
var lit_tables := {}
for k: String in main.lit_entries:
lit_tables[k.substr(0, k.rfind(":"))] = true
for t in main.data.tables:
if hidden.has(t.id):
continue
var c := main.card_for(t.id)
var r := Rect2(c.position, c.size) if c else Rect2(t.position, Vector2(TableCard.WIDTH, 120))
var lit := lit_tables.has(t.id)
_block(r, Style.BRASS if lit else Color(Style.CARD, 0.85), Color(0, 0, 0, 0), inner)
for g in main.data.groups:
if g.collapsed:
var n := main.group_node(g.id)
var r := Rect2(n.position, n.size) if n else Rect2(g.position, Vector2(TableCard.WIDTH, 120))
var lit := false
for tid in g.members:
if lit_tables.has(tid):
lit = true
break
_block(r, Style.BRASS if lit else Color("#cfc6ae"), Style.COPPER_DARK, inner)
var v := view_rect_on_map().intersection(inner)
if v.size.x > 0.0 and v.size.y > 0.0:
draw_rect(v, Color(Style.ON_FELT, 0.08))
draw_rect(v, Style.ON_FELT, false, 1.5)
## One block on the map, at least 2 px so tiny cards still show.
func _block(r: Rect2, fill: Color, edge: Color, clip: Rect2) -> void:
var m := Rect2(world_to_map(r.position), (r.size * _scale).max(Vector2(2, 2))).intersection(clip)
if m.size.x <= 0.0 or m.size.y <= 0.0:
return
draw_rect(m, fill)
if edge.a > 0.0 and m.size.x > 4.0 and m.size.y > 4.0:
draw_rect(m, edge, false, 1.0)
func _gui_input(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb:
if mb.button_index == MOUSE_BUTTON_LEFT:
_dragging = mb.pressed
if mb.pressed:
pan_to_map_point(mb.position)
accept_event()
return
var mm := ev as InputEventMouseMotion
if mm and _dragging:
pan_to_map_point(mm.position)
accept_event()
## Centres the board's view on the world point under a map point.
func pan_to_map_point(p: Vector2) -> void:
board.center_on(map_to_world(p))

View file

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

View file

@ -6,10 +6,6 @@ extends Control
## [[References]] in an entry's text draw as thinner dashed pipes. They come from ## [[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. ## the text, so they can't be clicked or removed here.
## ##
## Conditional pipes (an "Only if" condition, or "otherwise") have a small
## diamond at their source end and a label ("if @str >= 8", "otherwise"), so
## the branches of an entry read at a glance.
##
## Pipes to or from tables hidden in a collapsed group attach to that group's ## Pipes to or from tables hidden in a collapsed group attach to that group's
## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so ## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so
## they still light up and carry the bead; pipes inside one collapsed group ## they still light up and carry the bead; pipes inside one collapsed group
@ -32,16 +28,6 @@ var _rerouted: Dictionary = {}
## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer. ## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer.
var group_ports: Dictionary = {} var group_ports: Dictionary = {}
var _label_box: StyleBoxFlat var _label_box: StyleBoxFlat
var _lit_label_box: StyleBoxFlat
## What the last redraw was drawn from (see _process).
var _drawn_state: Array = []
## Unlit pipes each go in a canvas item of their own (see _batch_item), so the
## renderer skips the ones out of view; lit pipes, labels and the bead are
## drawn by _draw on top. A pool reused between redraws.
var _items: Array[RID] = []
var _items_used := 0
## Zoomed far out (BoardView.FAR_ZOOM): unlit pipes draw as one coarse line.
var _far := false
func _init() -> void: func _init() -> void:
@ -50,99 +36,10 @@ func _init() -> void:
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
_label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2]) _label_box = Style.box(Style.CARD, 7, [6, 1, 6, 2])
Style.bordered(_label_box, 1, Style.COPPER_DARK) Style.bordered(_label_box, 1, Style.COPPER_DARK)
_lit_label_box = Style.box(Style.LIT, 7, [6, 1, 6, 2])
Style.bordered(_lit_label_box, 1, Style.BRASS_DARK)
## Redraws only when something it draws changed: the board's geometry
## (BoardView.geometry_rev: cards moved, resized, rebuilt or scrolled, lit
## results, edits), the hovered or selected pipe, or the travelling bead.
func _process(_delta: float) -> void: func _process(_delta: float) -> void:
if main == null or main.board == null: queue_redraw()
return
var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far]
if state != _drawn_state:
_drawn_state = state
queue_redraw()
# ---------- Batched unlit pipes (performance) ----------
func _begin_batch() -> void:
_far = main.board.cards.far
for i in _items_used:
RenderingServer.canvas_item_clear(_items[i])
_items_used = 0
## The next free canvas item for one pipe: a child of this layer's item drawn
## behind it, so lit pipes and labels stay on top. Its bounds come from what's
## drawn in it, so the renderer culls it when the pipe is out of view.
func _batch_item() -> RID:
if _items_used == _items.size():
var rid := RenderingServer.canvas_item_create()
RenderingServer.canvas_item_set_parent(rid, get_canvas_item())
RenderingServer.canvas_item_set_draw_behind_parent(rid, true)
_items.append(rid)
_items_used += 1
return _items[_items_used - 1]
func _line(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void:
RenderingServer.canvas_item_add_polyline(rid, pts, PackedColorArray([color]), width, true)
## Far out: one plain line through every fourth point.
func _coarse(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void:
var c := PackedVector2Array()
for i in range(0, pts.size(), 4):
c.append(pts[i])
if (pts.size() - 1) % 4 != 0:
c.append(pts[pts.size() - 1])
RenderingServer.canvas_item_add_polyline(rid, c, PackedColorArray([color]), width, false)
## An unlit pipe (as _draw_pipe draws it), in its own canvas item.
func _batch_pipe(pts: PackedVector2Array, hovered: bool) -> void:
var rid := _batch_item()
if _far:
_coarse(rid, pts, Style.COPPER, 10.0)
return
_line(rid, pts, Style.COPPER_DARK, 11.0)
_line(rid, pts, Style.COPPER.lightened(0.35) if hovered else Style.COPPER, 6.0)
RenderingServer.canvas_item_add_set_transform(rid, Transform2D(0.0, Vector2(0, -1.5)))
_line(rid, pts, Color(1.0, 0.886, 0.745, 0.4), 1.5)
RenderingServer.canvas_item_add_set_transform(rid, Transform2D.IDENTITY)
## An unlit pipe to or from a collapsed group (as _draw_bundle draws it).
func _batch_bundle(pts: PackedVector2Array) -> void:
var rid := _batch_item()
if _far:
_coarse(rid, pts, Color(Style.COPPER, 0.6), 6.0)
return
_line(rid, pts, Color(Style.COPPER_DARK, 0.55), 6.0)
_line(rid, pts, Color(Style.COPPER, 0.6), 3.0)
## An unlit reference pipe (as _draw_ref draws it).
func _batch_ref(pts: PackedVector2Array) -> void:
var rid := _batch_item()
if _far:
_coarse(rid, pts, Color(Style.COPPER, 0.7), 4.0)
return
var dashes := _dashes(pts, 12.0, 7.0)
for d in dashes:
_line(rid, d, Style.COPPER_DARK, 6.0)
for d in dashes:
_line(rid, d, Style.COPPER, 3.0)
func _notification(what: int) -> void:
if what == NOTIFICATION_PREDELETE:
for rid in _items:
RenderingServer.free_rid(rid)
_items.clear()
static func curve(a: Vector2, b: Vector2) -> PackedVector2Array: static func curve(a: Vector2, b: Vector2) -> PackedVector2Array:
@ -156,26 +53,22 @@ static func curve(a: Vector2, b: Vector2) -> PackedVector2Array:
func _draw() -> void: func _draw() -> void:
_begin_batch()
_paths.clear() _paths.clear()
_rerouted.clear() _rerouted.clear()
group_ports.clear() group_ports.clear()
var lit_list: Array = [] var lit_list: Array = []
var lit_refs: Array = [] var lit_refs: Array = []
var labels: Array = [] var labels: Array = []
var diamonds: Array = [] # [point, lit, otherwise]
var drawn := {} # endpoints of rerouted pipes already drawn (they overlap) var drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
var build := main.mode == Main.Mode.BUILD var build := main.mode == Main.Mode.BUILD
# Tables hidden in a collapsed group -> that group's card. Their pipes leave # Tables hidden in a collapsed group -> that group's card. Their pipes leave
# from the group card's right edge and arrive at its inlet. # from the group card's right edge and arrive at its inlet.
var hidden := main.hidden_groups() var hidden := main.hidden_groups()
for t in main.data.tables: for t in main.data.tables:
# Tables hidden in a collapsed group have no card (Main builds them
# lazily); their pipes leave from the group card.
var card := main.card_for(t.id) var card := main.card_for(t.id)
var src_g: GroupCard = hidden.get(t.id) if card == null:
if card == null and src_g == null:
continue continue
var src_g: GroupCard = hidden.get(t.id)
for e in t.entries: for e in t.entries:
var refs := main.ref_targets_for(e) var refs := main.ref_targets_for(e)
if e.pipes.is_empty() and refs.is_empty(): if e.pipes.is_empty() and refs.is_empty():
@ -191,9 +84,9 @@ func _draw() -> void:
var is_ref := i < refs.size() var is_ref := i < refs.size()
var to: String = refs[i] if is_ref else e.pipes[i - refs.size()] var to: String = refs[i] if is_ref else e.pipes[i - refs.size()]
var target := main.card_for(to) var target := main.card_for(to)
var dst_g: GroupCard = hidden.get(to) if target == null:
if target == null and dst_g == null:
continue continue
var dst_g: GroupCard = hidden.get(to)
if src_g != null and dst_g == src_g: if src_g != null and dst_g == src_g:
continue # inside one collapsed group continue # inside one collapsed group
var key := Roller.ref_key(t.id, e.id, to) if is_ref else Roller.pipe_key(t.id, e.id, to) var key := Roller.ref_key(t.id, e.id, to) if is_ref else Roller.pipe_key(t.id, e.id, to)
@ -207,14 +100,8 @@ func _draw() -> void:
if src_g: if src_g:
var pk := Vector2i(a["pos"]) var pk := Vector2i(a["pos"])
group_ports[pk] = bool(group_ports.get(pk, false)) or main.is_entry_lit(t.id, e.id) group_ports[pk] = bool(group_ports.get(pk, false)) or main.is_entry_lit(t.id, e.id)
if not is_ref and not rerouted and e.is_conditional(to):
diamonds.append([pts, lit, e.is_otherwise(to)])
if lit: if lit:
(lit_refs if is_ref else lit_list).append(pts) (lit_refs if is_ref else lit_list).append(pts)
if not is_ref and not rerouted and e.is_conditional(to):
var lt := _pipe_tag(e, to)
if lt != "":
labels.append([pts, lt, true])
continue continue
if rerouted: if rerouted:
var dk := "%s|%s|%s" % [Vector2i(a["pos"]), Vector2i(end), is_ref] var dk := "%s|%s|%s" % [Vector2i(a["pos"]), Vector2i(end), is_ref]
@ -222,24 +109,22 @@ func _draw() -> void:
continue continue
drawn[dk] = true drawn[dk] = true
if is_ref: if is_ref:
_batch_ref(pts) _draw_ref(pts, false)
elif rerouted: elif rerouted:
_batch_bundle(pts) _draw_bundle(pts)
else: else:
_batch_pipe(pts, build and (key == hover_key or key == select_key)) _draw_pipe(pts, false, build and (key == hover_key or key == select_key))
if not is_ref and not rerouted: if not is_ref and not rerouted:
var tag := _pipe_tag(e, to) var tag := _pipe_tag(e, to)
if tag != "": if tag != "":
labels.append([pts, tag, false]) labels.append([pts, tag])
# Lit pipes go on top so the path of the last roll reads clearly. # Lit pipes go on top so the path of the last roll reads clearly.
for pts in lit_refs: for pts in lit_refs:
_draw_ref(pts, true) _draw_ref(pts, true)
for pts in lit_list: for pts in lit_list:
_draw_pipe(pts, true, false) _draw_pipe(pts, true, false)
for d in diamonds:
_draw_diamond(d[0], d[1], d[2])
for l in labels: for l in labels:
_draw_tag(l[0], l[1], l[2]) _draw_tag(l[0], l[1])
if pulse_key != "" and _paths.has(pulse_key): if pulse_key != "" and _paths.has(pulse_key):
var p := point_along(_paths[pulse_key], pulse_t) var p := point_along(_paths[pulse_key], pulse_t)
var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0 var r := 0.75 if Roller.is_ref_key(pulse_key) else 1.0
@ -248,14 +133,9 @@ func _draw() -> void:
draw_circle(p, 7.0 * r, Style.PULSE) draw_circle(p, 7.0 * r, Style.PULSE)
## "if @str >= 8 ×2 → foe" / "otherwise" for a pipe with options, or "". ## "×2 → foe" for a pipe with options, or "".
static func _pipe_tag(e: TableEntry, to: String) -> String: static func _pipe_tag(e: TableEntry, to: String) -> String:
var parts := PackedStringArray() var parts := PackedStringArray()
var w := e.when_for(to)
if w != "":
parts.append("if " + (w if w.length() <= 24 else w.substr(0, 23) + "…"))
elif e.is_otherwise(to):
parts.append("otherwise")
if e.count_expr(to) != "": if e.count_expr(to) != "":
var ex := e.count_expr(to) var ex := e.count_expr(to)
parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…")) parts.append("×" + (ex if ex.length() <= 18 else ex.substr(0, 17) + "…"))
@ -266,31 +146,14 @@ static func _pipe_tag(e: TableEntry, to: String) -> String:
return " ".join(parts) return " ".join(parts)
func _draw_tag(pts: PackedVector2Array, text: String, lit: bool = false) -> void: func _draw_tag(pts: PackedVector2Array, text: String) -> void:
var font := Style.body_bold(true) var font := Style.body_bold(true)
var fs := 12 var fs := 12
var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x var w := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
var mid := point_along(pts, 0.5) 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)) var r := Rect2(mid - Vector2(w / 2.0 + 6.0, 10.0), Vector2(w + 12.0, 19.0))
draw_style_box(_lit_label_box if lit else _label_box, r) 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.INK if lit else Style.COPPER_DARK) draw_string(font, Vector2(r.position.x + 6.0, r.position.y + 14.0), text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.COPPER_DARK)
## The mark of a conditional pipe: a small diamond near its source end
## (hollow for "otherwise", filled for a condition), far enough along that
## the branches of one entry have started to fan out.
func _draw_diamond(pts: PackedVector2Array, lit: bool, otherwise: bool) -> void:
if pts.size() < 2:
return
var c := point_along(pts, 0.2)
var r := 7.5
var poly := PackedVector2Array([c + Vector2(0, -r), c + Vector2(r, 0), c + Vector2(0, r), c + Vector2(-r, 0)])
var edge := Style.BRASS_DARK if lit else Style.COPPER_DARK
draw_colored_polygon(poly, edge)
var inner_r := r - 2.5
var inner := PackedVector2Array([c + Vector2(0, -inner_r), c + Vector2(inner_r, 0), c + Vector2(0, inner_r), c + Vector2(-inner_r, 0)])
var fill := Style.CARD if otherwise else (Style.BRASS if lit else Style.COPPER.lightened(0.25))
draw_colored_polygon(inner, fill)
func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void: func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:

View file

@ -1,8 +1,7 @@
class_name PipePopover class_name PipePopover
extends PopupPanel extends PopupPanel
## Build mode: the options for one pipe, opened by clicking it. How many times ## Build mode: the options for one pipe, opened by clicking it. How many times
## it rolls, its condition ("Only if", or "Otherwise"), the variable it saves ## it rolls, the variable it saves its result as, and Remove.
## its result as, and Remove.
const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$" const SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
@ -14,10 +13,6 @@ var _title: RichTextLabel
var _count: LineEdit var _count: LineEdit
var _count_msg: Label var _count_msg: Label
var _save: LineEdit var _save: LineEdit
var _when: LineEdit
var _when_msg: Label
var _otherwise: CheckBox
var _field_focus: StyleBoxFlat
var _save_ok: StyleBoxFlat var _save_ok: StyleBoxFlat
var _save_bad: StyleBoxFlat var _save_bad: StyleBoxFlat
var _re := RegEx.new() var _re := RegEx.new()
@ -33,7 +28,6 @@ func setup(p_main: Main) -> void:
add_theme_stylebox_override("panel", sb) add_theme_stylebox_override("panel", sb)
popup_hide.connect(func() -> void: popup_hide.connect(func() -> void:
_commit_save() _commit_save()
_commit_when()
if main.board: if main.board:
main.board.pipes.select_key = "" main.board.pipes.select_key = ""
) )
@ -49,7 +43,6 @@ func setup(p_main: Main) -> void:
var field_focus := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.COPPER) var field_focus := Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.COPPER)
_save_ok = field_ok _save_ok = field_ok
_save_bad = Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.DANGER) _save_bad = Style.bordered(Style.box(Color.WHITE, 5, [7, 3, 7, 3]), 1, Style.DANGER)
_field_focus = field_focus
var count_row := HBoxContainer.new() var count_row := HBoxContainer.new()
count_row.add_theme_constant_override("separation", 6) count_row.add_theme_constant_override("separation", 6)
@ -88,55 +81,6 @@ func setup(p_main: Main) -> void:
_count_msg.hide() _count_msg.hide()
v.add_child(_count_msg) v.add_child(_count_msg)
var when_row := HBoxContainer.new()
when_row.add_theme_constant_override("separation", 6)
v.add_child(when_row)
var wl := Style.make_label("Only if", Style.body(), 14, Style.MUTED)
wl.custom_minimum_size = Vector2(62, 0)
when_row.add_child(wl)
_when = LineEdit.new()
_when.placeholder_text = "always (or e.g. @str >= 8)"
_when.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_when.max_length = 200
_when.tooltip_text = "The pipe runs only when this is true. Every condition on the entry is checked once, before any of its pipes run."
_when.add_theme_stylebox_override("normal", field_ok)
_when.add_theme_stylebox_override("focus", field_focus)
_when.text_changed.connect(func(_s: String) -> void: _check_when())
_when.text_submitted.connect(func(_s: String) -> void:
_commit_when()
hide()
)
_when.focus_exited.connect(_commit_when)
when_row.add_child(_when)
_when_msg = Style.make_label("", Style.body(), 12, Style.DANGER_INK)
_when_msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_when_msg.custom_minimum_size = Vector2(260, 0)
_when_msg.hide()
v.add_child(_when_msg)
var other_row := HBoxContainer.new()
other_row.add_theme_constant_override("separation", 6)
v.add_child(other_row)
var pad := Control.new()
pad.custom_minimum_size = Vector2(62, 0)
other_row.add_child(pad)
_otherwise = CheckBox.new()
_otherwise.text = "Otherwise"
_otherwise.tooltip_text = "Runs only when none of this result's \"Only if\" pipes is true"
_otherwise.add_theme_font_override("font", Style.body())
_otherwise.add_theme_font_size_override("font_size", 14)
_otherwise.add_theme_color_override("font_color", Style.INK)
_otherwise.add_theme_color_override("font_hover_color", Style.INK)
_otherwise.add_theme_color_override("font_pressed_color", Style.INK)
_otherwise.add_theme_color_override("font_hover_pressed_color", Style.INK)
_otherwise.add_theme_color_override("font_disabled_color", Style.MUTED)
_otherwise.toggled.connect(func(on: bool) -> void:
if _entry == null or on == _entry.is_otherwise(_to):
return
_entry.set_pipe_otherwise(_to, on)
main.mark_dirty()
)
other_row.add_child(_otherwise)
var save_row := HBoxContainer.new() var save_row := HBoxContainer.new()
save_row.add_theme_constant_override("separation", 6) save_row.add_theme_constant_override("separation", 6)
v.add_child(save_row) v.add_child(save_row)
@ -170,7 +114,6 @@ func setup(p_main: Main) -> void:
remove.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN remove.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
remove.pressed.connect(func() -> void: remove.pressed.connect(func() -> void:
var k := key var k := key
_commit_when()
_entry = null _entry = null
hide() hide()
main.remove_pipe(k) main.remove_pipe(k)
@ -205,9 +148,6 @@ func open(pipe_key: String, at: Vector2) -> void:
_count_msg.hide() _count_msg.hide()
_save.text = _entry.save_for(_to) _save.text = _entry.save_for(_to)
_save.add_theme_stylebox_override("normal", _save_ok) _save.add_theme_stylebox_override("normal", _save_ok)
_when.text = _entry.when_for(_to)
_otherwise.set_pressed_no_signal(_entry.is_otherwise(_to))
_check_when()
main.board.pipes.select_key = pipe_key main.board.pipes.select_key = pipe_key
reset_size() reset_size()
var view := main.get_viewport_rect().size var view := main.get_viewport_rect().size
@ -239,41 +179,6 @@ static func _count_error(text: String) -> String:
return "" if err == "" else "Not a number or expression: " + err return "" if err == "" else "Not a number or expression: " + err
## "" when `text` is a usable condition (empty means always), else why not.
static func when_error(text: String) -> String:
var s := text.strip_edges()
if s == "":
return ""
var err := Expr.check(TemplateKit.probe(s))
return "" if err == "" else "Not a valid condition: " + err
## Live validation of the Only if field; Otherwise is off while it's filled.
func _check_when() -> void:
var err := when_error(_when.text)
var ok := err == ""
_when.add_theme_stylebox_override("normal", _save_ok if ok else _save_bad)
_when.add_theme_stylebox_override("focus", _field_focus if ok else _save_bad)
_when_msg.text = err
_when_msg.visible = not ok
var filled := _when.text.strip_edges() != ""
_otherwise.disabled = filled
if filled:
_otherwise.set_pressed_no_signal(false)
elif _entry != null:
_otherwise.set_pressed_no_signal(_entry.is_otherwise(_to))
reset_size()
func _commit_when() -> void:
if _entry == null or when_error(_when.text) != "":
return
var s := _when.text.strip_edges()
if s != _entry.when_for(_to):
_entry.set_pipe_when(_to, s)
main.mark_dirty()
func _commit_save() -> void: func _commit_save() -> void:
if _entry == null: if _entry == null:
return return

View file

@ -11,10 +11,6 @@ var _grab: Array = [] # [{pos, tid, eid}] outlets that can start a pipe
var _linking := false var _linking := false
var _ghost_from := Vector2.ZERO var _ghost_from := Vector2.ZERO
var _ghost_to := Vector2.ZERO var _ghost_to := Vector2.ZERO
var _drawn_rev := -1
var _drawn_hover := -1
var _drawn_mode := -1
var _drawn_far := false
func _init() -> void: func _init() -> void:
@ -24,30 +20,8 @@ func _init() -> void:
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
## Redraws only when the board's geometry changed (BoardView.geometry_rev),
## the outlet under the mouse changed (Build), or while a pipe is being laid.
func _process(_delta: float) -> void: func _process(_delta: float) -> void:
if main == null or main.board == null: queue_redraw()
return
var hover := _hovered_grab()
var far := main.board.cards.far
if _linking or main.board.geometry_rev != _drawn_rev or hover != _drawn_hover or main.mode != _drawn_mode or far != _drawn_far:
_drawn_far = far
_drawn_rev = main.board.geometry_rev
_drawn_hover = hover
_drawn_mode = main.mode
queue_redraw()
## Index in _grab of the outlet under the mouse, or -1 (always -1 in Play).
func _hovered_grab() -> int:
if main.mode != Main.Mode.BUILD or _grab.is_empty():
return -1
var mouse := get_local_mouse_position()
for i in _grab.size():
if mouse.distance_to(_grab[i]["pos"]) <= GRAB_RADIUS:
return i
return -1
func _has_point(p: Vector2) -> bool: func _has_point(p: Vector2) -> bool:
@ -63,9 +37,6 @@ func _has_point(p: Vector2) -> bool:
func _draw() -> void: func _draw() -> void:
_grab.clear() _grab.clear()
# Zoomed far out (BoardView.FAR_ZOOM) the ports would be specks.
if main.board.cards.far and not _linking:
return
var build := main.mode == Main.Mode.BUILD var build := main.mode == Main.Mode.BUILD
var mouse := get_local_mouse_position() var mouse := get_local_mouse_position()
for t in main.data.tables: for t in main.data.tables:

View file

@ -437,9 +437,6 @@ static func caption_for(step: Dictionary) -> String:
caption += " · afterwards" caption += " · afterwards"
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
caption += " · sheet" caption += " · sheet"
RollTable.KIND_ROUTER:
if step.has("case"):
caption += " · case %d" % (int(step["case"]) + 1)
_: _:
if num != "": if num != "":
caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))] caption += " · rolled %s on %s" % [num, step.get("dice", "d%d" % int(step.get("die", 0)))]

View file

@ -1,284 +0,0 @@
class_name SearchPanel
extends PanelContainer
## The Search pop-over under the top bar's Search button (or Ctrl+F): a text
## field and a live list of matches (BoardSearch). Up/Down pick a result,
## Enter or a click jumps to it (Main.focus_table / focus_group), Esc or a
## click elsewhere closes it.
const WIDTH := 460.0
const LIST_HEIGHT := 400.0
const SHOWN := 40
signal closed
var main: Main
var field: LineEdit
## The matches shown, best first (BoardSearch results).
var results: Array[Dictionary] = []
var selected := -1
var _search: BoardSearch
var _search_rev := -1
var _anchor: Control
var _scroll: ScrollContainer
var _list: VBoxContainer
var _note: Label
var _rows: Array[PanelContainer] = []
var _row_normal: StyleBoxFlat
var _row_hover: StyleBoxFlat
var _row_selected: StyleBoxFlat
func setup(p_main: Main) -> void:
main = p_main
visible = false
mouse_filter = MOUSE_FILTER_STOP
top_level = true
theme = Style.card_theme()
var sb := Style.box(Style.CARD, 10, [12, 12, 12, 10])
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 18
sb.shadow_offset = Vector2(0, 8)
add_theme_stylebox_override("panel", sb)
custom_minimum_size = Vector2(WIDTH, 0)
_row_normal = Style.box(Color(0, 0, 0, 0), 7, [10, 6, 10, 7])
_row_hover = Style.box(Style.HOVER_ROW, 7, [10, 6, 10, 7])
_row_selected = Style.bordered(Style.box(Style.LIT, 7, [10, 6, 10, 7]), 1, Color(Style.BRASS_DARK, 0.35))
var col := VBoxContainer.new()
col.add_theme_constant_override("separation", 8)
add_child(col)
field = LineEdit.new()
field.placeholder_text = "Search names, results, prompts, variables, groups…"
field.add_theme_font_override("font", Style.body())
field.add_theme_font_size_override("font_size", 16)
field.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.RULE))
field.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 2, Style.COPPER))
field.clear_button_enabled = true
field.text_changed.connect(func(_t: String) -> void: refresh())
field.gui_input.connect(_on_field_input)
col.add_child(field)
_note = Style.make_label("", Style.body_italic(), 14, Style.MUTED)
_note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
col.add_child(_note)
_scroll = ScrollContainer.new()
_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
col.add_child(_scroll)
_list = VBoxContainer.new()
_list.add_theme_constant_override("separation", 2)
_list.size_flags_horizontal = SIZE_EXPAND_FILL
_scroll.add_child(_list)
## Opens under `anchor` (the Search button) with the field focused.
func open(anchor: Control = null) -> void:
_anchor = anchor
visible = true
_place()
field.grab_focus()
field.select_all()
refresh()
func close() -> void:
if not visible:
return
visible = false
if field.has_focus():
field.release_focus()
closed.emit()
func _place() -> void:
reset_size()
var vp := get_viewport_rect().size
var x := vp.x - size.x - 12.0
var y := 56.0
if is_instance_valid(_anchor) and _anchor.is_inside_tree():
var r := _anchor.get_global_rect()
x = r.end.x - size.x
y = r.end.y + 8.0
position = Vector2(clampf(x, 8.0, maxf(8.0, vp.x - size.x - 8.0)), y)
## The index, rebuilt when the board was edited since it was made.
func index() -> BoardSearch:
if _search == null or _search_rev != main.edit_rev:
_search = BoardSearch.new(main.data)
_search_rev = main.edit_rev
return _search
## Re-runs the query and rebuilds the list.
func refresh() -> void:
for c in _list.get_children():
_list.remove_child(c)
c.queue_free()
_rows.clear()
var q := field.text.strip_edges()
results = index().find(q, SHOWN + 1) if q != "" else ([] as Array[Dictionary])
var more := results.size() > SHOWN
if more:
results.resize(SHOWN)
for i in results.size():
_rows.append(_make_row(results[i], i))
_list.add_child(_rows[i])
if q == "":
_note.text = "Type to find a card by its name, results, details, prompt, variables or group."
elif results.is_empty():
_note.text = "Nothing matches “%s”." % q
elif more:
_note.text = "The first %d matches. Keep typing to narrow them down." % SHOWN
else:
_note.text = "%d %s · ↑↓ to pick, Enter to jump" % [results.size(), "match" if results.size() == 1 else "matches"]
_scroll.custom_minimum_size.y = 0.0 if results.is_empty() else minf(LIST_HEIGHT, results.size() * 62.0)
selected = 0 if not results.is_empty() else -1
_update_selected()
_place.call_deferred()
func _make_row(r: Dictionary, i: int) -> PanelContainer:
var row := PanelContainer.new()
row.add_theme_stylebox_override("panel", _row_normal)
row.mouse_filter = MOUSE_FILTER_STOP
row.mouse_default_cursor_shape = CURSOR_POINTING_HAND
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", 1)
v.mouse_filter = MOUSE_FILTER_IGNORE
row.add_child(v)
var top := HBoxContainer.new()
top.add_theme_constant_override("separation", 8)
top.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(top)
var name_field: bool = r["field"] == BoardSearch.FIELD_NAME or r["field"] == BoardSearch.FIELD_GROUP
var title := _rich(highlight(r["snippet"], r["hl_from"], r["hl_len"]) if name_field else _esc(str(r["name"])),
Style.body_bold(), 16)
title.size_flags_horizontal = SIZE_EXPAND_FILL
top.add_child(title)
var kind := Style.make_label(str(r["kind"]).to_upper(), Style.caps(), 10, Style.COPPER_DARK)
kind.size_flags_vertical = SIZE_SHRINK_CENTER
kind.mouse_filter = MOUSE_FILTER_IGNORE
top.add_child(kind)
var where := PackedStringArray()
if str(r["group"]) != "":
where.append("in " + str(r["group"]))
if not name_field:
where.append(_field_label(str(r["field"])))
if not where.is_empty():
var sub := Style.make_label(" · ".join(where), Style.body(), 13, Style.MUTED)
sub.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
sub.custom_minimum_size = Vector2(40, 0)
sub.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(sub)
if not name_field:
var snip := _rich(highlight(r["snippet"], r["hl_from"], r["hl_len"]), Style.body(), 14)
v.add_child(snip)
row.mouse_entered.connect(func() -> void:
if selected != i:
row.add_theme_stylebox_override("panel", _row_hover))
row.mouse_exited.connect(func() -> void: _update_selected())
row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT:
selected = i
activate()
row.accept_event())
return row
static func _field_label(field: String) -> String:
match field:
BoardSearch.FIELD_RESULT: return "result"
BoardSearch.FIELD_DETAILS: return "details"
BoardSearch.FIELD_PROMPT: return "prompt"
BoardSearch.FIELD_VARIABLE: return "variable"
BoardSearch.FIELD_EFFECTS: return "effects"
return field
func _rich(bb: String, font: Font, fs: int) -> RichTextLabel:
var l := RichTextLabel.new()
l.bbcode_enabled = true
l.fit_content = true
l.scroll_active = false
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
l.mouse_filter = MOUSE_FILTER_IGNORE
l.add_theme_font_override("normal_font", font)
l.add_theme_font_override("bold_font", Style.body_bold())
l.add_theme_font_size_override("normal_font_size", fs)
l.add_theme_font_size_override("bold_font_size", fs)
l.add_theme_color_override("default_color", Style.INK)
l.custom_minimum_size = Vector2(40, 0)
l.size_flags_horizontal = SIZE_EXPAND_FILL
l.text = bb
return l
static func _esc(s: String) -> String:
return s.replace("[", "[lb]")
## BBCode for plain `text` with [from, from + length) marked in brass.
static func highlight(text: String, from: int, length: int) -> String:
if from < 0 or length <= 0 or from >= text.length():
return _esc(text)
return "%s[bgcolor=#%s][b]%s[/b][/bgcolor]%s" % [_esc(text.substr(0, from)), Style.BRASS.to_html(false),
_esc(text.substr(from, length)), _esc(text.substr(from + length))]
func _update_selected() -> void:
for i in _rows.size():
_rows[i].add_theme_stylebox_override("panel", _row_selected if i == selected else _row_normal)
func move_selection(step: int) -> void:
if results.is_empty():
return
selected = wrapi(selected + step, 0, results.size())
_update_selected()
if selected < _rows.size():
_scroll.ensure_control_visible(_rows[selected])
## Jumps to the selected result and closes.
func activate() -> void:
if selected < 0 or selected >= results.size():
return
var r := results[selected]
close()
if str(r["group_id"]) != "":
main.focus_group(str(r["group_id"]))
else:
main.focus_table(str(r["table_id"]), str(r["entry_id"]))
func _on_field_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed:
return
match k.keycode:
KEY_DOWN:
move_selection(1)
KEY_UP:
move_selection(-1)
KEY_ENTER, KEY_KP_ENTER:
activate()
KEY_ESCAPE:
close()
_:
return
field.accept_event()
func _input(ev: InputEvent) -> void:
if not visible:
return
var mb := ev as InputEventMouseButton
if mb and mb.pressed and not get_global_rect().has_point(mb.global_position):
# A click elsewhere closes it (the Search button toggles it itself).
if not (is_instance_valid(_anchor) and _anchor.get_global_rect().has_point(mb.global_position)):
close()
var k := ev as InputEventKey
if k and k.pressed and k.keycode == KEY_ESCAPE:
close()
get_viewport().set_input_as_handled()

View file

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

View file

@ -8,9 +8,7 @@ extends PanelContainer
## badge, its question and its options (or one Answer row); a loop card shows ## badge, its question and its options (or one Answer row); a loop card shows
## its rule and the Each time / Afterwards rows; a variable card shows its ## its rule and the Each time / Afterwards rows; a variable card shows its
## live value and has no rows; a sheet card's one row is its rendered ## live value and has no rows; a sheet card's one row is its rendered
## template; a router card has a fork icon in place of the die and one row ## template. Live text (values, sheets, prompts) is only re-rendered by
## per case, showing its condition ("if @str >= 8", "Otherwise") with its
## outlet. Live text (values, sheets, prompts) is only re-rendered by
## refresh_live(), which Main calls after rolls and edits, never per frame. ## refresh_live(), which Main calls after rolls and edits, never per frame.
const WIDTH := 256.0 const WIDTH := 256.0
@ -173,8 +171,6 @@ func rebuild() -> void:
continue continue
if table.kind == RollTable.KIND_SHEET: if table.kind == RollTable.KIND_SHEET:
_list_box.add_child(_make_sheet_row(e, build)) _list_box.add_child(_make_sheet_row(e, build))
elif table.kind == RollTable.KIND_ROUTER and build:
_list_box.add_child(_make_case_row(e, i, numw))
else: else:
_list_box.add_child(_make_row(e, i, build, ranged, numw)) _list_box.add_child(_make_row(e, i, build, ranged, numw))
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL) _set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
@ -345,8 +341,6 @@ func _subtitle() -> String:
RollTable.KIND_CHOICE: RollTable.KIND_CHOICE:
if table.collapsed: if table.collapsed:
return "%d options" % table.entries.size() return "%d options" % table.entries.size()
RollTable.KIND_ROUTER:
return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"]
return "" return ""
@ -376,14 +370,6 @@ func _make_go_button() -> Button:
icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT) icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2)) icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2))
b.add_child(icon) b.add_child(icon)
RollTable.KIND_ROUTER:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Route %s: the first case that's true is chosen" % Formatter.strip_tags(table.name)
var fork := Control.new()
fork.mouse_filter = MOUSE_FILTER_IGNORE
fork.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
fork.draw.connect(func() -> void: draw_fork(fork, fork.size / 2.0 + Vector2(0, 0), 8.0, Style.BRASS, 2.2))
b.add_child(fork)
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
b.text = "Print" b.text = "Print"
b.add_theme_font_override("font", Style.body_bold(true)) b.add_theme_font_override("font", Style.body_bold(true))
@ -447,13 +433,6 @@ func _make_kind_header(_build: bool) -> Control:
chip.add_child(l) chip.add_child(l)
chip.tooltip_text = err chip.tooltip_text = err
return chip return chip
RollTable.KIND_ROUTER:
if not _build:
return null
var rl := Style.make_label("Router · the first true case is chosen", Style.body(true), 12, Style.MUTED)
rl.mouse_filter = MOUSE_FILTER_IGNORE
rl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
return rl
RollTable.KIND_VARIABLE: RollTable.KIND_VARIABLE:
var txt := "@%s · %s" % [table.var_name, table.var_type] var txt := "@%s · %s" % [table.var_name, table.var_type]
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED) var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
@ -462,30 +441,6 @@ func _make_kind_header(_build: bool) -> Control:
return null return null
## A fork: one stem splitting into two branches, each ending in a dot (the
## router card's go button). `r` is about half the icon's height.
static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void:
var base := c + Vector2(-r, 0)
var split := c + Vector2(-r * 0.15, 0)
ci.draw_line(base, split, color, width, true)
var up := c + Vector2(r * 0.85, -r * 0.75)
var down := c + Vector2(r * 0.85, r * 0.75)
for tip: Vector2 in [up, down]:
var pts := PackedVector2Array()
for k in 9:
var u := float(k) / 8.0
pts.append(split.bezier_interpolate(split + Vector2(r * 0.5, 0), tip - Vector2(r * 0.45, 0), tip, u))
ci.draw_polyline(pts, color, width, true)
ci.draw_circle(tip, width * 1.25, color)
ci.draw_circle(base, width * 0.9, color)
## A router case's condition as shown: "if @str >= 8", or "Otherwise".
static func case_label(e: TableEntry) -> String:
var w := e.when.strip_edges()
return "Otherwise" if w == "" else "if " + w
## "× @answer", "while @alive = 1", "until @done". ## "× @answer", "while @alive = 1", "until @done".
static func loop_rule(t: RollTable) -> String: static func loop_rule(t: RollTable) -> String:
var e := t.loop_expr.strip_edges() var e := t.loop_expr.strip_edges()
@ -554,7 +509,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
r.add_child(_range_edit(e, false)) r.add_child(_range_edit(e, false))
h.add_child(r) h.add_child(r)
else: else:
num = Style.make_label("" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index)), Style.display(true), 16, Style.MUTED) num = Style.make_label("" if fixed else table.num_label(e, index), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0) num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER num.size_flags_vertical = SIZE_SHRINK_CENTER
@ -626,123 +581,6 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
return row return row
## Build mode: one router case. The first line is its condition (empty means
## Otherwise), validated as you type, with move up / down and delete; the
## second is its result text with the effects and details toggles.
func _make_case_row(e: TableEntry, index: int, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var outer := _hbox(4)
row.add_child(outer)
var num := Style.make_label(str(index + 1), 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_BEGIN
outer.add_child(num)
var v := _vbox(3)
v.size_flags_horizontal = SIZE_EXPAND_FILL
outer.add_child(v)
var top := _hbox(4)
v.add_child(top)
var if_label := Style.make_label("if", Style.body_bold(true), 14, Style.COPPER_DARK)
if_label.size_flags_vertical = SIZE_SHRINK_CENTER
top.add_child(if_label)
var cond := LineEdit.new()
cond.text = e.when
cond.placeholder_text = "Otherwise"
cond.size_flags_horizontal = SIZE_EXPAND_FILL
cond.size_flags_vertical = SIZE_SHRINK_CENTER
cond.custom_minimum_size = Vector2(40, 0)
cond.add_theme_font_override("font", Style.body_bold(true))
cond.add_theme_font_size_override("font_size", 14)
cond.add_theme_color_override("font_color", Style.COPPER_DARK)
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK)
var check := func() -> void:
var src := TemplateKit.probe(cond.text.strip_edges())
var err := Expr.check(src) if src != "" else ""
cond.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box)
cond.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box)
cond.tooltip_text = ("⚠ " + err) if err != "" else "This case is chosen when this is true (cases are checked top to bottom). Leave it empty for Otherwise."
if_label.text = "if" if cond.text.strip_edges() != "" else "else"
cond.text_changed.connect(func(t: String) -> void:
e.when = t.strip_edges()
check.call()
_update_warning()
main.mark_dirty()
)
check.call()
top.add_child(cond)
top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1)))
top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1)))
top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id)))
var bottom := _hbox(4)
v.add_child(bottom)
var edit := LineEdit.new()
edit.text = e.text
edit.placeholder_text = "Result 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(t: String) -> void:
e.text = t
main.mark_dirty()
)
bottom.add_child(edit)
bottom.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this case is chosen",
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
bottom.add_child(_toggle_button("i", "Details shown when hovering this case",
_open_details, e.id, e.details.strip_edges() != "", false))
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index}
return row
func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button:
var b := Button.new()
b.text = glyph
b.tooltip_text = tip
b.disabled = not enabled
b.custom_minimum_size = Vector2(22, 22)
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_size_override("font_size", 16 if glyph == "×" else 13)
Style.skin_button(b, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK if glyph == "×" else Style.INK)
b.add_theme_color_override("font_disabled_color", Color(Style.MUTED, 0.35))
b.pressed.connect(on_press)
return b
## Moves router case `index` up (-1) or down (+1).
func _move_case(index: int, by: int) -> void:
var to := index + by
if to < 0 or to >= table.entries.size():
return
var e := table.entries[index]
table.entries.remove_at(index)
table.entries.insert(to, e)
rebuild()
main.mark_dirty()
## Adds a router case just before the Otherwise case (or at the end). It
## starts as "if false", so it never matches until its condition is written.
func add_case() -> void:
var e := TableEntry.new(TowerBoard.new_id("e"), "New case")
e.when = "false"
var at := table.otherwise_index()
if at < 0 or at != table.entries.size() - 1:
at = table.entries.size()
table.entries.insert(at, e)
table.collapsed = false
rebuild()
main.mark_dirty()
const LOOP_ROWS := ["Each time", "Afterwards"] const LOOP_ROWS := ["Each time", "Afterwards"]
## Longest effects summary shown on a Play-mode chip. ## Longest effects summary shown on a Play-mode chip.
const CHIP_CHARS := 30 const CHIP_CHARS := 30
@ -790,14 +628,6 @@ func _row_text(e: TableEntry) -> String:
s = "[b]%s[/b]" % cap s = "[b]%s[/b]" % cap
else: else:
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s] s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
elif table.kind == RollTable.KIND_ROUTER:
var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != ""
var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(case_label(e))]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == case_label(e) or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""):
s = cond
else:
s = "%s\n%s" % [cond, s]
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick": elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
if rolled != "": if rolled != "":
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)] s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
@ -1163,11 +993,6 @@ func _make_warning() -> Control:
func _update_warning() -> void: func _update_warning() -> void:
var problems := table.range_problems() var problems := table.range_problems()
var lines := PackedStringArray()
for item: Dictionary in Roller.lint_router(table):
lines.append(str(item["message"]))
if not lines.is_empty():
problems = ("%s\n" % problems if problems != "" else "") + "\n".join(lines)
_warn_label.text = problems _warn_label.text = problems
_warn_panel.visible = problems != "" _warn_panel.visible = problems != ""
@ -1186,11 +1011,6 @@ func _make_footer(ranged: bool) -> Control:
var add := _footer_button(label, Style.INK) var add := _footer_button(label, Style.INK)
add.pressed.connect(func() -> void: main.add_entry(table.id)) add.pressed.connect(func() -> void: main.add_entry(table.id))
h.add_child(add) h.add_child(add)
elif table.kind == RollTable.KIND_ROUTER:
var addc := _footer_button("+ Add case", Style.INK)
addc.tooltip_text = "Add a case before Otherwise"
addc.pressed.connect(add_case)
h.add_child(addc)
var det := _footer_button("Details", Style.INK) var det := _footer_button("Details", Style.INK)
det.tooltip_text = "Details shown when hovering the table's name" det.tooltip_text = "Details shown when hovering the table's name"
if table.details.strip_edges() != "": if table.details.strip_edges() != "":

View file

@ -89,8 +89,6 @@ static func kind_line(t: RollTable) -> String:
return "Variable card" return "Variable card"
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
return "Sheet card" return "Sheet card"
RollTable.KIND_ROUTER:
return "Router · if / else if / otherwise"
var s := "Roll table · " + t.dice_label() var s := "Roll table · " + t.dice_label()
return s + " · deck" if t.card_mode else s return s + " · deck" if t.card_mode else s
@ -117,8 +115,6 @@ static func summary_line(t: RollTable) -> String:
return "Repeats %s times" % (e if e != "" else "?") return "Repeats %s times" % (e if e != "" else "?")
RollTable.KIND_VARIABLE: RollTable.KIND_VARIABLE:
return "Holds @%s (%s)" % [t.var_name, t.var_type] return "Holds @%s (%s)" % [t.var_name, t.var_type]
RollTable.KIND_ROUTER:
return "Goes on with the first case that's true"
return "" return ""
@ -134,11 +130,6 @@ static func _row(t: RollTable, e: TableEntry, index: int) -> Control:
col.add_theme_constant_override("separation", 0) col.add_theme_constant_override("separation", 0)
col.size_flags_horizontal = Control.SIZE_EXPAND_FILL col.size_flags_horizontal = Control.SIZE_EXPAND_FILL
col.mouse_filter = Control.MOUSE_FILTER_IGNORE col.mouse_filter = Control.MOUSE_FILTER_IGNORE
if t.kind == RollTable.KIND_ROUTER:
var cond := _label(TableCard.case_label(e), 12, Style.COPPER_DARK, true, true)
cond.max_lines_visible = 2
cond.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
col.add_child(cond)
var tx := Formatter.strip_tags(e.text).strip_edges() var tx := Formatter.strip_tags(e.text).strip_edges()
var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true) var text := _label(tx if tx != "" else "(empty)", 13, Style.INK, false, true)
text.max_lines_visible = 2 text.max_lines_visible = 2
@ -164,8 +155,6 @@ static func row_label(t: RollTable, e: TableEntry, index: int) -> String:
return str(index + 1) if t.choice == "pick" else "Answer" return str(index + 1) if t.choice == "pick" else "Answer"
RollTable.KIND_LOOP: RollTable.KIND_LOOP:
return "Each" if index == 0 else "After" return "Each" if index == 0 else "After"
RollTable.KIND_ROUTER:
return str(index + 1)
return t.num_label(e, index) return t.num_label(e, index)

View file

@ -50,9 +50,6 @@ var _var_type := "number"
var _initial: LineEdit var _initial: LineEdit
var _template: TextEdit var _template: TextEdit
var _template_preview: RichTextLabel var _template_preview: RichTextLabel
## Router cards: one condition field per case, in order.
var _cases: Array[LineEdit] = []
var _case_note: Label
const TITLES := { const TITLES := {
RollTable.KIND_ROLL: "Table settings", RollTable.KIND_ROLL: "Table settings",
@ -60,7 +57,6 @@ const TITLES := {
RollTable.KIND_LOOP: "Loop settings", RollTable.KIND_LOOP: "Loop settings",
RollTable.KIND_VARIABLE: "Variable settings", RollTable.KIND_VARIABLE: "Variable settings",
RollTable.KIND_SHEET: "Sheet settings", RollTable.KIND_SHEET: "Sheet settings",
RollTable.KIND_ROUTER: "Router settings",
} }
const CHOICE_LABELS := ["Which option", "How many", "Open ended"] const CHOICE_LABELS := ["Which option", "How many", "Open ended"]
const LOOP_LABELS := ["Times", "While", "Until"] const LOOP_LABELS := ["Times", "While", "Until"]
@ -279,11 +275,6 @@ func settings() -> Dictionary:
s["initial"] = _initial.text.strip_edges() s["initial"] = _initial.text.strip_edges()
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
s["template"] = _template.text s["template"] = _template.text
RollTable.KIND_ROUTER:
var cases: Array = []
for le in _cases:
cases.append(le.text.strip_edges())
s["cases"] = cases
return s return s
@ -378,23 +369,6 @@ func _build_kind() -> void:
pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7])) pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
pbox.add_child(_template_preview) pbox.add_child(_template_preview)
box.add_child(pbox) box.add_child(pbox)
RollTable.KIND_ROUTER:
box.add_child(section("Cases (if / else if / otherwise)"))
box.add_child(note("Checked top to bottom when the chain arrives; the first true case is chosen, and its effects, text and pipes run like a rolled result. An empty condition is Otherwise: it always matches, so keep it last. Add, remove and reorder cases on the card."))
for i in table.entries.size():
var e := table.entries[i]
var le := LineEdit.new()
le.text = e.when
le.placeholder_text = "Otherwise (always)"
style_line_edit(le)
le.text_changed.connect(func(_t: String) -> void: _refresh())
_cases.append(le)
var label := Formatter.strip_tags(e.text).strip_edges()
box.add_child(field("Case %d%s" % [i + 1, (" · " + label) if label != "" else ""], le))
if table.entries.is_empty():
box.add_child(note("This router has no cases yet: add some on the card."))
_case_note = note("", Style.WARN_INK)
box.add_child(_case_note)
_: _:
box.free() # roll tables have no kind fields box.free() # roll tables have no kind fields
return return
@ -435,13 +409,6 @@ func _refresh_kind() -> void:
var ctx := Roller.live_context(table_board(), _live_vars()) var ctx := Roller.live_context(table_board(), _live_vars())
_template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \ _template_preview.text = RichText.decorate(TextExpander.render(_template.text, ctx)) if _template.text.strip_edges() != "" \
else "[color=#69726b]Preview appears here.[/color]" else "[color=#69726b]Preview appears here.[/color]"
RollTable.KIND_ROUTER:
var cases: Array = s["cases"]
for i in _cases.size():
_mark(_cases[i], when_error(str(cases[i])) == "")
var hint := router_hint(cases)
_case_note.text = hint
_case_note.visible = hint != ""
# The ranged/card-mode sections only apply to roll tables and pick choices. # The ranged/card-mode sections only apply to roll tables and pick choices.
var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick") var rolls := table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and _choice == "pick")
_type_box.visible = rolls _type_box.visible = rolls
@ -533,12 +500,6 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
out.append("The loop needs a count or a condition.") out.append("The loop needs a count or a condition.")
elif Expr.check(src) != "": elif Expr.check(src) != "":
out.append("Loop rule: " + Expr.check(src)) out.append("Loop rule: " + Expr.check(src))
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in cases.size():
var err := when_error(str(cases[i]))
if err != "":
out.append("Case %d: %s" % [i + 1, err])
RollTable.KIND_VARIABLE: RollTable.KIND_VARIABLE:
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")) var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
if _re(VAR_PATTERN).search(n) == null: if _re(VAR_PATTERN).search(n) == null:
@ -549,20 +510,6 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
return out return out
## "" when a router case condition is usable (empty is Otherwise), else why not.
static func when_error(src: String) -> String:
src = TemplateKit.probe(src.strip_edges())
return Expr.check(src) if src != "" else ""
## A hint about the order of router cases (an Otherwise that isn't last), or "".
static func router_hint(cases: Array) -> String:
for i in cases.size():
if str(cases[i]).strip_edges() == "" and i < cases.size() - 1:
return "Case %d is Otherwise, so the cases after it can never be chosen. Move it to the end." % (i + 1)
return ""
static func _initial_error(src: String, type: String) -> String: static func _initial_error(src: String, type: String) -> String:
src = TemplateKit.probe(src.strip_edges()) src = TemplateKit.probe(src.strip_edges())
if src == "": if src == "":
@ -626,10 +573,6 @@ static func _apply_kind(t: RollTable, s: Dictionary) -> void:
if RollTable.VAR_TYPES.has(vt): if RollTable.VAR_TYPES.has(vt):
t.var_type = vt t.var_type = vt
t.initial = str(s.get("initial", t.initial)).strip_edges() t.initial = str(s.get("initial", t.initial)).strip_edges()
RollTable.KIND_ROUTER:
var cases: Array = s.get("cases", [])
for i in mini(cases.size(), t.entries.size()):
t.entries[i].when = str(cases[i]).strip_edges()
RollTable.KIND_SHEET: RollTable.KIND_SHEET:
if s.has("template"): if s.has("template"):
if t.entries.is_empty(): if t.entries.is_empty():

View file

@ -1,401 +0,0 @@
class_name TestBoardDialog
extends ModalCard
## Build mode's "Test board": pick a start card, a number of runs and how the
## simulated player answers, run BoardTester in slices (a progress bar, and
## Cancel), then read the report: a summary line and collapsible sections for
## the static Problems, runtime Errors, Dead ends, tables Never reached and
## entries Never chosen. Every item jumps to its card. The last report is kept
## while the app is open and shown again when the dialog is reopened.
const RUN_CHOICES: Array[int] = [100, 500, 1000]
const SECTION_CAP := 60
## Roughly how long one slice of runs may take before the UI gets a frame.
const SLICE_MSEC := 25
## The last finished (or cancelled) test: {board, report, problems, text}.
static var last: Dictionary = {}
var main: Node
var board: TowerBoard
var start_pick: OptionButton
var prefer_edit: LineEdit
var run_button: Button
var copy_button: Button
var progress: ProgressBar
var status: Label
var summary: Label
var report_box: VBoxContainer
## Section name -> {"header": Button, "box": VBoxContainer, "count": int}
var sections: Dictionary = {}
var runs := 100
var use_prefer := false
var running := false
var tester: BoardTester = null
var _options_box: Control
var _progress_row: Control
var _report_text := ""
## `p_main` is the Main node (it has `data`, `card_for()`, `board` and, when
## present, `focus_table()`).
func _init(p_main: Node = null) -> void:
super._init("Test board", 640.0)
main = p_main
board = p_main.get("data") if p_main != null else null
_build()
func _ready() -> void:
super._ready()
if not last.is_empty() and last.get("board") == board:
_show_report(last["report"], last["problems"])
func _build() -> void:
_options_box = VBoxContainer.new()
(_options_box as VBoxContainer).add_theme_constant_override("separation", 10)
body.add_child(_options_box)
_options_box.add_child(note("Rolls a card many times, answering every choice at random, and reports problems, dead ends and what never came up. Your saved variables and decks are not touched."))
start_pick = OptionButton.new()
start_pick.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.DASH))
start_pick.add_theme_stylebox_override("hover", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
start_pick.add_theme_stylebox_override("pressed", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
start_pick.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
start_pick.add_theme_color_override(c, Style.INK)
start_pick.add_theme_font_size_override("font_size", 16)
start_pick.clip_text = true
start_pick.fit_to_longest_item = false
start_pick.size_flags_horizontal = SIZE_EXPAND_FILL
style_popup(start_pick.get_popup())
_fill_starts()
_options_box.add_child(field("Start from", start_pick))
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 18)
# Start on the run count of the last report, so the selector matches it.
var last_runs := int(last.get("report", {}).get("runs_planned", RUN_CHOICES[0])) if last.get("report") is Dictionary else RUN_CHOICES[0]
var runs_index := maxi(0, RUN_CHOICES.find(last_runs))
runs = RUN_CHOICES[runs_index]
row.add_child(field("Runs", segmented(RUN_CHOICES.map(func(n: int) -> String: return str(n)), runs_index,
func(i: int) -> void: runs = RUN_CHOICES[i])))
row.add_child(field("Answers", segmented(["Random", "Prefer options matching…"], 0, func(i: int) -> void:
use_prefer = i == 1
prefer_edit.visible = use_prefer
if use_prefer:
prefer_edit.grab_focus()
)))
_options_box.add_child(row)
prefer_edit = LineEdit.new()
prefer_edit.placeholder_text = "Regular expression, e.g. ^Continue|another career"
style_line_edit(prefer_edit)
prefer_edit.visible = false
_options_box.add_child(prefer_edit)
_progress_row = VBoxContainer.new()
_progress_row.visible = false
progress = ProgressBar.new()
progress.show_percentage = false
progress.custom_minimum_size = Vector2(0, 12)
progress.add_theme_stylebox_override("background", Style.box(Color(0, 0, 0, 0.12), 6))
progress.add_theme_stylebox_override("fill", Style.box(Style.FELT, 6))
_progress_row.add_child(progress)
status = note("")
_progress_row.add_child(status)
body.add_child(_progress_row)
summary = Style.make_label("", Style.body_bold(), 17, Style.INK)
summary.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
summary.visible = false
body.add_child(summary)
report_box = VBoxContainer.new()
report_box.add_theme_constant_override("separation", 6)
body.add_child(report_box)
add_button("Close", "plain", close)
copy_button = add_button("Copy report", "plain", copy_report)
copy_button.disabled = true
run_button = add_button("Run", "primary", _on_run_pressed)
func _fill_starts() -> void:
start_pick.clear()
if board == null:
return
var last_rolled := ""
if main != null and main.get("history") is Array and not (main.get("history") as Array).is_empty():
var rec: Variant = (main.get("history") as Array)[0]
if rec is Dictionary:
last_rolled = str((rec as Dictionary).get("root", ""))
var ids := BoardTester.start_candidates(board, last_rolled)
var roots := ids.size()
for t in board.tables:
if t.kind != RollTable.KIND_VARIABLE and not ids.has(t.id):
ids.append(t.id)
for k in ids.size():
var t := board.get_table(ids[k])
start_pick.add_item("%s (%s)%s" % [Formatter.strip_tags(t.name), t.id, "" if k < roots else " - piped into"])
start_pick.set_item_metadata(k, t.id)
if start_pick.item_count > 0:
start_pick.select(0)
func selected_start() -> String:
if start_pick.selected < 0:
return ""
return str(start_pick.get_item_metadata(start_pick.selected))
# ---------- Running ----------
func _on_run_pressed() -> void:
if running:
cancel_run()
else:
run_test()
func cancel_run() -> void:
if tester != null:
tester.cancel()
## Runs the test with the dialog's settings; returns when it is finished or
## cancelled. The UI stays responsive: runs happen in time slices.
func run_test() -> void:
if running or board == null or selected_start() == "":
return
running = true
run_button.text = "Cancel"
copy_button.disabled = true
_progress_row.visible = true
_clear_report()
var problems := BoardTester.static_checks(board)
tester = BoardTester.new(board, selected_start(), {
"runs": runs, "seed": randi(), "prefer": prefer_edit.text.strip_edges() if use_prefer else "",
})
progress.max_value = runs
progress.value = 0
var k := 1
while not tester.is_done():
var t0 := Time.get_ticks_msec()
await tester.run_batch(k)
var dt := maxi(1, Time.get_ticks_msec() - t0)
k = clampi(int(float(k) * SLICE_MSEC / dt), 1, 200) if dt < SLICE_MSEC else maxi(1, k / 2)
progress.value = tester.runs_done
status.text = "Run %d of %d" % [tester.runs_done, runs]
if not is_inside_tree():
return
await get_tree().process_frame
var report := tester.report()
tester = null
running = false
run_button.text = "Run again"
_progress_row.visible = false
last = {"board": board, "report": report, "problems": problems}
_show_report(report, problems)
# ---------- Report ----------
func _clear_report() -> void:
for c in report_box.get_children():
c.queue_free()
sections.clear()
summary.visible = false
_report_text = ""
func _table_label(tid: String) -> String:
var t := board.get_table(tid) if board != null else null
return "%s (%s)" % [Formatter.strip_tags(t.name), tid] if t != null else tid
## The one-line summary, e.g. "500 runs · 0 errors · 2 dead ends · 3 tables never reached".
static func summary_line(report: Dictionary, problems: Array) -> String:
var errs := (report["errors"] as Array).size() + (report["unset_markers"] as Array).size()
var parts := PackedStringArray()
parts.append("%d runs" % report["runs"])
parts.append("%d %s" % [errs, "error" if errs == 1 else "errors"])
var dead := (report["dead_ends"] as Array).size()
parts.append("%d dead %s" % [dead, "end" if dead == 1 else "ends"])
var un := (report["unreached"] as Array).size()
parts.append("%d %s never reached" % [un, "table" if un == 1 else "tables"])
if not problems.is_empty():
parts.append("%d %s" % [problems.size(), "problem" if problems.size() == 1 else "problems"])
return " · ".join(parts)
func _show_report(report: Dictionary, problems: Array) -> void:
_clear_report()
run_button.text = "Run again"
copy_button.disabled = false
var line := summary_line(report, problems)
if report.get("cancelled", false):
line = "Cancelled after %d of %d runs · %s" % [report["runs"], report["runs_planned"], line.trim_prefix("%d runs · " % report["runs"])]
summary.text = line
summary.visible = true
# Problems
var items: Array = []
for p: Dictionary in problems:
items.append({"table_id": p["table_id"], "entry_id": p["entry_id"],
"text": "%s%s: %s" % [_table_label(p["table_id"]) if board.get_table(p["table_id"]) != null else "Board",
"" if str(p["entry_id"]) == "" else ", entry " + str(p["entry_id"]), p["text"]]})
_add_section("Problems", "Static checks", items, true)
# Errors: effect / expression errors, unset markers and action-limit halts
items = []
for e: Dictionary in report["errors"]:
items.append({"table_id": e["table_id"], "entry_id": e["entry_id"],
"text": "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]]})
for e: Dictionary in report["unset_markers"]:
items.append({"table_id": e["table_id"], "entry_id": e["entry_id"],
"text": "%dx %s, entry \"%s\": %s" % [e["count"], e["table"], e["entry"], e["text"]]})
for why: String in report["halted"]:
var top: Array = (report["longest"] as Dictionary).get("top", [])
items.append({"table_id": str(top[0]["table"]) if not top.is_empty() else "", "entry_id": "",
"text": "%d runs stopped: %s%s" % [report["halted"][why], why,
" (busiest table: %s)" % _table_label(str(top[0]["table"])) if not top.is_empty() else ""]})
_add_section("Errors", "Runtime errors", items, true)
items = []
for e: Dictionary in report["dead_ends"]:
items.append({"table_id": e["table_id"], "entry_id": "", "text": "%dx %s: %s" % [e["count"], e["table"], e["text"]]})
_add_section("Dead ends", "Rolls that stopped", items, true)
items = []
for id: String in report["unreached"]:
items.append({"table_id": id, "entry_id": "", "text": _table_label(id)})
_add_section("Never reached", "Tables no run got to", items, false)
items = []
var uc: Dictionary = report["unchosen"]
for id: String in uc:
var texts: Array = uc[id]
var ids: Array = report["unchosen_ids"][id]
for k in texts.size():
items.append({"table_id": id, "entry_id": ids[k], "text": "%s: \"%s\"" % [_table_label(id), texts[k]]})
_add_section("Never chosen", "Entries no run picked", items, false)
if str(report["sample_sheet"]) != "":
var sheet := Style.make_label("Sample sheet", Style.caps(), 12, Style.MUTED)
report_box.add_child(sheet)
var rtl := note(str(report["sample_sheet"]), Style.INK)
report_box.add_child(rtl)
_report_text = _compose_text(report, problems)
_refit.call_deferred()
func _refit() -> void:
if is_inside_tree():
await get_tree().process_frame
_fit()
func _add_section(title: String, hint: String, items: Array, open: bool) -> void:
var box := VBoxContainer.new()
box.add_theme_constant_override("separation", 2)
var header := Button.new()
header.flat = true
header.alignment = HORIZONTAL_ALIGNMENT_LEFT
header.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
header.add_theme_font_override("font", Style.body_bold())
header.add_theme_font_size_override("font_size", 16)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
header.add_theme_color_override(c, Style.INK if not items.is_empty() else Style.MUTED)
header.add_theme_color_override("font_disabled_color", Style.MUTED)
header.tooltip_text = hint
var list := VBoxContainer.new()
list.add_theme_constant_override("separation", 0)
list.visible = open and not items.is_empty()
var refresh := func() -> void:
header.text = "%s %s (%d)" % ["▾" if list.visible else "▸", title, items.size()]
refresh.call()
header.disabled = items.is_empty()
header.pressed.connect(func() -> void:
list.visible = not list.visible
refresh.call()
_fit()
)
box.add_child(header)
for k in mini(SECTION_CAP, items.size()):
list.add_child(_item_button(items[k]))
if items.size() > SECTION_CAP:
var more := note("... and %d more (see Copy report)" % (items.size() - SECTION_CAP))
list.add_child(more)
box.add_child(list)
report_box.add_child(box)
sections[title] = {"header": header, "box": list, "count": items.size(), "items": items}
func _item_button(item: Dictionary) -> Button:
var b := Button.new()
b.flat = true
b.text = str(item["text"])
b.alignment = HORIZONTAL_ALIGNMENT_LEFT
b.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
b.clip_text = false
b.size_flags_horizontal = SIZE_EXPAND_FILL
b.add_theme_font_override("font", Style.body())
b.add_theme_font_size_override("font_size", 14)
for c in ["font_color", "font_hover_color", "font_pressed_color", "font_focus_color", "font_hover_pressed_color"]:
b.add_theme_color_override(c, Style.INK)
b.add_theme_stylebox_override("hover", Style.box(Style.HOVER_ROW, 5, [8, 3, 8, 3]))
b.add_theme_stylebox_override("pressed", Style.box(Style.HOVER_ROW, 5, [8, 3, 8, 3]))
b.add_theme_stylebox_override("normal", Style.box(Color(0, 0, 0, 0), 5, [8, 3, 8, 3]))
b.add_theme_stylebox_override("focus", Style.box(Color(0, 0, 0, 0), 5, [8, 3, 8, 3]))
b.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
var tid := str(item["table_id"])
b.disabled = tid == "" or board.get_table(tid) == null
b.tooltip_text = "Go to this card" if not b.disabled else ""
b.pressed.connect(click_item.bind(tid, str(item["entry_id"])))
return b
## Jumps to a card (and entry): through Main.focus_table() when it exists,
## otherwise by panning the board to the card. The dialog closes so the board
## is visible; reopening it shows the same report.
func click_item(table_id: String, entry_id: String = "") -> void:
if main == null or table_id == "":
return
if main.has_method("focus_table"):
main.call("focus_table", table_id, entry_id)
else:
_pan_to(table_id)
close()
func _pan_to(table_id: String) -> void:
var t := board.get_table(table_id)
var bv: Variant = main.get("board")
if t == null or bv == null:
return
var view: Control = bv
var card: Variant = main.call("card_for", table_id)
var size_of: Vector2 = (card as Control).size if card is Control else Vector2(260, 120)
var center := t.position + size_of / 2.0
var zoom: float = view.get("zoom")
view.get("world").position = view.size / 2.0 - center * zoom
# ---------- Copy ----------
func copy_report() -> void:
DisplayServer.clipboard_set(_report_text)
if main != null and main.has_method("toast"):
main.call("toast", "Report copied")
func report_text() -> String:
return _report_text
func _compose_text(report: Dictionary, problems: Array) -> String:
var out := PackedStringArray()
out.append("Test board: %s, starting from %s" % [board.name, _table_label(str(report.get("start", "")))])
out.append(summary.text)
out.append("")
out.append("\n".join(BoardTester.format_problems(problems, 1000)))
out.append("")
out.append(BoardTester.format_report(report, 1000))
return "\n".join(out)

View file

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