TableTower/core/roll_pipes.gd
RobinFiredrake 1735ed09fd Card threads, Morgan's welcome, and typing/scroll/wheel papercuts
- Card threads: a port on each card's bottom edge. Plain runs after any
  result (once the result's own threads finish); Otherwise runs only when
  no thread of the result ran. Saved as card_threads (LOGIC.md 3g).
- Typing on long cards no longer rebuilds the inspector or the card per
  key (~175 ms -> ~7 ms). Timing tool: tests/perf_typing.gd.
- "+ Add result" scrolls to the new row and focuses it.
- Mouse wheel zooms; Shift+wheel pans sideways; scrolling lists keep it.
- "SPREAD" caption over the switcher; Morgan's first-run welcome.
- docs/MECHANICS.md: checklist of table mechanics for planning.

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

225 lines
9.5 KiB
GDScript

class_name RollPipes
extends RefCounted
## Pipe snapshots and card inputs for the Roller: what an entry's pipes do
## (pipe_plan()), the values they pass, binding a card's inputs for the
## subtree it runs, and the pipe and pause frames on the Roller's work stack.
## 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, "with": {name: value}} ("with"
## only on a pipe that runs and passes input values; a value whose expression
## fails is left out, so the target's default applies, with an error line).
## - 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. `why` gets the trace
## facts: {"type": "when", "to", "expr", "values": {name: value}, "result":
## bool, "error"?} per conditional pipe and {"type": "otherwise", "to",
## "result"} per otherwise pipe.
## `others_ran` (card threads, CardThreads): a thread of the result ran, so
## an otherwise card thread doesn't.
static func pipe_plan(e: TableEntry, ctx: RollContext, log: Array = [], why: Array = [], others_ran: bool = false) -> Array:
var plan: Array = []
var any_true := others_ran
for p in e.pipes:
var w := e.when_for(p)
var run := true
if w != "":
var r := Expr.evaluate(w, ctx)
var fact := {"type": "when", "to": p, "expr": w, "values": Expr.values_read(w, ctx), "result": false}
if r["error"] != "":
log.append({"text": "Thread condition %s: %s" % [w, r["error"]], "error": true})
run = false
fact["error"] = str(r["error"])
else:
run = Expr.truthy(r["value"])
fact["result"] = run
why.append(fact)
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
why.append({"type": "otherwise", "to": item["to"], "result": item["run"]})
item.erase("otherwise")
if item["run"]:
item["count"] = e.count_value(str(item["to"]), ctx, log)
if not e.pipe_with.is_empty() and e.pipe_with.has(item["to"]):
item["with"] = with_values(e, str(item["to"]), ctx, log)
return plan
## The input values a pipe passes, worked out now: {name: value}. A value
## whose expression fails is left out (the target's default applies) and adds
## an error line to `log`.
static func with_values(e: TableEntry, target: String, ctx: RollContext, log: Array = []) -> Dictionary:
var out := {}
var w: Variant = e.pipe_with.get(target)
if not (w is Dictionary):
return out
for nm: String in w:
var src := str(w[nm])
var r := Expr.evaluate(src, ctx)
if r["error"] != "":
log.append({"text": "Thread input %s = %s: %s" % [nm, src, r["error"]], "error": true})
else:
out[nm] = Expr.normalize(r["value"])
return out
# ---------- Card inputs ----------
## Binds a card's inputs as chain values for the subtree about to run: the
## pipe's "with" values (f["with"]), and each declared input's default for the
## rest. Pushes a Roller.OP_RESTORE frame first, so the previous values come
## back when the subtree ends. The trace facts and error lines go on the node
## via Roller._attach().
static func bind_inputs(t: RollTable, f: Dictionary, ctx: RollContext, stack: Array) -> void:
var given: Dictionary = f.get("with", {})
if t.inputs.is_empty() and given.is_empty():
return
var values := {}
var facts: Array = []
var log: Array = []
for inp: Dictionary in t.inputs:
var nm := str(inp.get("name", ""))
if nm == "" or values.has(nm):
continue
if given.has(nm):
values[nm] = given[nm]
facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"})
continue
var def := str(inp.get("default", "")).strip_edges()
var v: Variant = 0
if def != "":
var r := Expr.evaluate(def, ctx)
if r["error"] != "":
log.append({"text": "Input %s default %s: %s" % [nm, def, r["error"]], "error": true})
else:
v = Expr.normalize(r["value"])
values[nm] = v
facts.append({"type": "input", "name": nm, "value": v, "from": "default"})
for nm: String in given:
if not values.has(nm):
values[nm] = given[nm]
facts.append({"type": "input", "name": nm, "value": given[nm], "from": "pipe"})
var saved := {}
for nm: String in values:
saved[nm] = [ctx.chain_vars.has(nm), ctx.chain_vars.get(nm)]
ctx.chain_vars[nm] = values[nm]
stack.append({"op": Roller.OP_RESTORE, "saved": saved})
f["inputs"] = values
f["pre_why"] = facts
f["pre_log"] = log
## Puts back the chain values a card's inputs hid.
static func restore(f: Dictionary, ctx: RollContext) -> void:
var saved: Dictionary = f["saved"]
for nm: String in saved:
var pair: Array = saved[nm]
if pair[0]:
ctx.chain_vars[nm] = pair[1]
else:
ctx.chain_vars.erase(nm)
# ---------- Pipe frames on the Roller's work stack ----------
## Snapshots a result's threads (pipe_plan) and queues the ones that run,
## last first so they run in order.
## The card's own threads (CardThreads) wait under them, so they run after
## the result's threads and their whole chains.
static func queue_pipes(node: Dictionary, ctx: RollContext, stack: Array, depth: int) -> void:
var entry: TableEntry = node["entry"]
var log: Array = []
var why: Array = []
var plan := pipe_plan(entry, ctx, log, why)
Roller._log(node, log)
Roller._why(node, why)
if CardThreads.follows(node["table"], node):
var ran := false
for item: Dictionary in plan:
ran = ran or (item["run"] and int(item["count"]) > 0)
stack.append({"op": Roller.OP_CARD, "node": node, "ran": ran, "depth": depth})
push_plan(node, entry, plan, stack, depth)
## Queues the threads of `plan` that run (from `entry`, a result or the card's
## outlet), last first so they run in order. `card`: card threads.
static func push_plan(node: Dictionary, entry: TableEntry, plan: Array, stack: Array, depth: int, card: bool = false) -> void:
for k in range(plan.size() - 1, -1, -1):
var item: Dictionary = plan[k]
if not item["run"]:
continue
var target: String = item["to"]
var frame := {"op": Roller.OP_PIPE, "node": node, "entry": entry, "to": target, "left": int(item["count"]),
"save": entry.save_for(target), "depth": depth}
if card:
frame["card"] = true
if item.has("with"):
frame["with"] = item["with"]
if entry.dice_for(target) != "":
frame["dice"] = entry.dice_for(target)
if not entry.reroll_for(target).is_empty():
frame["reroll"] = entry.reroll_for(target)
if entry.pipe_distinct.has(target) and int(item["count"]) > 1:
frame["distinct_from"] = (node["children"] as Array).size()
var mode := entry.combine_for(target)
if mode != "all" and int(item["count"]) > 1:
# Runs after every repeat: combines them (RollCombine).
stack.append({"op": Roller.OP_COMBINE, "node": node, "to": target, "mode": mode, "save": frame["save"],
"start": (node["children"] as Array).size(), "depth": depth})
frame["no_follow"] = true
frame["save"] = ""
stack.append(frame)
if entry.pipe_pause.has(target):
# Runs first: waits for the player before the thread above it.
stack.append({"op": Roller.OP_PAUSE, "node": node, "to": target, "depth": depth})
## A paused thread: asks the player (kind "pause") whether to go on. Stopping
## drops the thread waiting under this frame and marks the result.
static func do_pause(board: TowerBoard, frame: Dictionary, ctx: RollContext, stack: Array) -> void:
var table := board.get_table(str(frame["to"]))
var node: Dictionary = frame["node"]
var request := {"kind": "pause", "table_id": str(frame["to"]), "title": table.name if table else str(frame["to"]),
"prompt": "Continue to %s?" % Formatter.strip_tags(table.name if table else str(frame["to"])),
"from": Formatter.strip_tags((node["table"] as RollTable).name)}
var reply: Variant = await RollChoice.ask(ctx, request)
if reply == true:
return
if not stack.is_empty() and int((stack.back() as Dictionary)["op"]) == Roller.OP_PIPE:
stack.pop_back()
node["stopped_before"] = str(frame["to"])
## One run of a pipe: pushes itself back (while runs are left) and then a
## roll frame for the target table, so the target rolls first.
static func do_pipe(board: TowerBoard, frame: Dictionary, stack: Array) -> void:
if int(frame["left"]) <= 0:
return
var table := board.get_table(str(frame["to"]))
if table == null or table.kind == RollTable.KIND_VARIABLE:
return
frame["left"] = int(frame["left"]) - 1
stack.append(frame)
var roll_frame := {"op": Roller.OP_ROLL, "id": frame["to"], "parent": frame["node"], "save": frame["save"], "depth": frame["depth"]}
for key in ["with", "dice", "reroll", "card"]:
if frame.has(key):
roll_frame[key] = frame[key]
if frame.has("distinct_from"):
# No repeats: this roll also skips every result this thread already gave.
var skip: Array = (frame.get("reroll", []) as Array).duplicate()
var children: Array = (frame["node"] as Dictionary)["children"]
for i in range(int(frame["distinct_from"]), children.size()):
var child: Dictionary = children[i]
if child.get("entry") is TableEntry and (child["table"] as RollTable).id == str(frame["to"]) and not skip.has((child["entry"] as TableEntry).id):
skip.append((child["entry"] as TableEntry).id)
roll_frame["reroll"] = skip
if frame.get("no_follow", false):
roll_frame["no_follow"] = true
stack.append(roll_frame)