TableTower/ui/main_rolling.gd
RobinFiredrake 781aaf1be8 Magic sparkles on the thread pulse and on landing results
Sparkles (CPU particles, mobile-safe) in the theme's GLOW colour: a trail
follows the pulse up each thread, and a short burst plays over a result as
it lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:26:02 -06:00

399 lines
14 KiB
GDScript

class_name MainRolling
extends RefCounted
## Main's rolling: starting a roll, choice questions, playback on the board
## and in the tray, the session seed and copying results.
## Chains longer than this show at once instead of animating.
const LONG_CHAIN := 40
## Copy-as-text indents by depth up to this many levels.
const MAX_INDENT := 8
var m: Main
var _token := 0
var _pulse_tween: Tween
var _choice: ChoiceDialog
func _init(p_main: Main) -> void:
m = p_main
## Rolls a table and plays the result down its pipes. A fast roll (Shift held
## while clicking, or `fast`) skips the flicker and the beads and shows the
## whole result at once. Choice cards still ask (docs/LOGIC.md §8): before a
## question opens, the steps so far light up; after the last answer the rest
## of the roll shows at once. Starting a roll while a question is open cancels
## the old roll.
func start_roll(tid: String, fast: bool = false) -> void:
var t := m.data.get_table(tid)
if t == null or t.kind == RollTable.KIND_VARIABLE:
return
# A minimized question keeps waiting; a new roll must not cancel it.
if _choice_waiting("Answer the waiting question first"):
return
fast = fast or Input.is_key_pressed(KEY_SHIFT)
_archive_current()
_token += 1
var my := _token
# A question left open by the previous roll answers Cancel; that roll then
# sees it has been replaced and stops quietly.
cancel_choice()
if _pulse_tween and _pulse_tween.is_valid():
_pulse_tween.kill()
m.board.pipes.pulse_key = ""
for c in m.cards.values():
(c as TableCard).set_rolling(false)
(c as TableCard).clear_flick()
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
ctx.prompt = _prompt_for.bind(my)
m.rolling_ctx = ctx
m.current = {"collection": m.data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(),
"steps": [], "all": [], "done": false, "pending": true}
var tree: Dictionary = await Roller.roll_async(m.data, tid, ctx)
if m.rolling_ctx == ctx:
m.rolling_ctx = null
if my != _token or not m.is_inside_tree():
# Another roll started while this one waited for an answer.
m.local_state._store_decks()
if ctx.persistent_changed:
m.local_state._store_variables()
return
var prompted: bool = m.current.get("prompted", false)
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
m.current = {"collection": m.data.id, "root": tid, "root_name": t.name, "time": m.current.get("time", Time.get_unix_time_from_system()),
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
if ctx.halted != "":
m.current["halted"] = ctx.halted
m.local_state._store_roll(ctx)
if fast or prompted or (m.current["all"] as Array).size() > LONG_CHAIN:
_finish_fast_roll()
return
m._refresh_lit()
m.tray.render()
await _play_node(tree, my)
if my == _token:
m.current["steps"] = m.current["all"]
m.current["done"] = true
m.tray.render()
m.refresh_live()
## The roll's prompt hook: lights the steps so far, then asks through
## prompt_hook (the pop-up, or a test's script). A reply for a roll that has
## been replaced in the meantime is turned into Cancel.
func _prompt_for(req: Dictionary, my: int) -> Variant:
if my != _token:
return null
m.current["prompted"] = true
m.current["asking"] = Formatter.strip_tags(str(req.get("title", "")))
show_progress()
var reply: Variant = await m.prompt_hook.call(req)
if my != _token:
return null
m.current.erase("asking")
return reply
## Lights the steps of the running roll so far (Roller.progress) on the board
## and in the tray, all at once. Used just before a question opens.
func show_progress() -> void:
if m.rolling_ctx == null:
return
var steps := Roller.progress(m.rolling_ctx)
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
_light_steps(steps)
m._refresh_lit()
_reveal_steps(steps)
m.current["steps"] = steps
m.current["all"] = steps
m.current["fast"] = true
m.refresh_live()
m.tray.render()
## The real prompt hook: opens the choice pop-up and waits for its answer
## (an index or -1 for a pick, an int, a String, or null for Cancel).
func _ask_player(req: Dictionary) -> Variant:
cancel_choice()
var d := ChoiceDialog.new(req)
_choice = d
var waiter := d.reply
m._add_modal(d)
var v: Variant = await waiter.done
if _choice == d:
_choice = null
return v
## True (after a toast with a Show button) while a question is minimized.
func _choice_waiting(message: String) -> bool:
var d := pending_choice()
if d == null or not d.minimized:
return false
d.nudge(message)
return true
## The open choice pop-up, or null.
func pending_choice() -> ChoiceDialog:
return _choice if is_instance_valid(_choice) else null
## Closes an open choice pop-up as Cancel (its roll stops with "Cancelled").
func cancel_choice() -> void:
var d := pending_choice()
_choice = null
if d != null:
d.answer(null)
## Plays a result tree step by step. Iterative (an explicit stack), so long
## chains don't recurse.
func _play_node(root_node: Dictionary, my: int) -> void:
var stack: Array = [[root_node, 0, ""]] # node, depth, pipe key that led to it
while not stack.is_empty():
var top: Array = stack.pop_back()
var n: Dictionary = top[0]
if my != _token or n.is_empty():
return
var key: String = top[2]
if key != "":
m.lit_pipes[key] = true
await _pulse(key, my)
if my != _token:
return
await _play_one(n, my, int(top[1]))
if my != _token:
return
if n.has("stop"):
continue
var kids: Array = n["children"]
var eid := (n["entry"] as TableEntry).id
var tid := (n["table"] as RollTable).id
for k in range(kids.size() - 1, -1, -1):
var c: Dictionary = kids[k]
var ck := "" if (c.has("pass") or c.has("after")) else Roller.link_key(tid, eid, c)
stack.append([c, int(top[1]) + 1, ck])
## Animates one node: the card tumbles (plain rolls only), then the result lights.
func _play_one(n: Dictionary, my: int, depth: int) -> void:
var t: RollTable = n["table"]
var stopped := n.has("stop")
var card := m.card_for(t.id)
var tumble: bool = not n.has("kind") or bool(n.get("random", false))
# A table hidden in a collapsed group rolls on the group's card.
var gcard: GroupCard = m.hidden_groups().get(t.id)
if not stopped and gcard and tumble:
gcard.set_rolling(true)
await m.get_tree().create_timer(0.35).timeout
if my != _token:
return
gcard = m.hidden_groups().get(t.id)
if gcard:
gcard.set_rolling(false)
elif not stopped and card and tumble:
card.set_rolling(true)
for k in 8:
card = m.card_for(t.id)
if card == null:
break
if t.collapsed:
card.set_more_text("Rolling… %s" % t.fmt(m.rng.randi_range(t.min_value(), maxi(t.min_value(), t.die_size()))))
else:
card.flick_random()
await m.get_tree().create_timer((40.0 + k * 16.0) / 1000.0).timeout
if my != _token:
return
card = m.card_for(t.id)
if card:
card.clear_flick()
card.set_rolling(false)
if not stopped:
var e: TableEntry = n["entry"]
var ek := Roller.entry_key(t.id, e.id)
m.lit_entries[ek] = true
m.lit_texts[ek] = str(n.get("summary", e.text))
m._refresh_lit()
if card:
card.reveal(e.id)
card.sparkle(e.id)
(m.current["steps"] as Array).append(Roller.step_of(n, depth))
m.tray.render()
## Shows the whole current roll at once: every result and pipe on its path lit,
## long lists scrolled to their result, and the full chain in the tray.
func _finish_fast_roll() -> void:
var all: Array = m.current["all"]
_light_steps(all)
m._refresh_lit()
_reveal_steps(all)
m.current["steps"] = all
m.current["done"] = true
m.current["fast"] = true
m.refresh_live()
m.tray.render()
## Scrolls long cards to the last result each table gave in `steps` (one
## reveal per table, so thousands of steps cost one pass).
func _reveal_steps(steps: Array) -> void:
var last := {}
for s: Dictionary in steps:
if s.has("entry_id") and not s.get("stop", false):
last[str(s.get("table_id", ""))] = str(s["entry_id"])
for tid: String in last:
var card := m.card_for(tid)
if card:
card.reveal(last[tid])
func _pulse(key: String, my: int) -> void:
var length := m.board.pipes.path_length(key)
if length <= 0.0 or my != _token:
return
m.board.pipes.pulse_key = key
m.board.pipes.pulse_t = 0.0
_pulse_tween = m.create_tween().set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_IN_OUT)
_pulse_tween.tween_property(m.board.pipes, "pulse_t", 1.0, clampf(length * 0.8, 260.0, 650.0) / 1000.0)
await _pulse_tween.finished
if m.board.pipes.pulse_key == key:
m.board.pipes.pulse_key = ""
## Moves the current roll to the Earlier list (it's already in the saved history).
func _archive_current() -> void:
# A roll still waiting for an answer is cancelled, not kept.
if m.current.is_empty() or m.current.get("archived", false) or m.current.get("pending", false):
return
m.current["archived"] = true
var rec := m.current.duplicate()
rec["steps"] = m.current["all"]
m.history.push_front(rec)
if m.history.size() > Main.HISTORY_SIZE:
m.history.resize(Main.HISTORY_SIZE)
## Opens the session: the collection's saved history, decks and variables. With
## no saved history (a fresh start, or --sample / --screenshot), it seeds a game
## already under way: a couple of earlier rolls, saved variables for the
## Variables tab, and a current roll that runs through the d100 travel table
## into the collapsed trinket table.
func _seed_session() -> void:
m.local_state.load_local_state()
if not m.current.is_empty():
_light_steps(m.current.get("all", []))
m._refresh_lit()
m.refresh_live()
m.tray.render()
return
var now := Time.get_unix_time_from_system()
# Seeded rolls draw from scratch decks so they don't use up real cards.
var scratch := {}
for seed_roll in [["monsters", 9], ["loot", 4]]:
if m.data.get_table(seed_roll[0]):
var tree := Roller.roll(m.data, seed_roll[0], m.rng, 0, scratch)
var steps := Roller.flatten(tree, [])
m.history.push_front({"collection": m.data.id, "root": seed_roll[0], "root_name": m.data.get_table(seed_roll[0]).name,
"time": now - seed_roll[1] * 60, "steps": steps, "all": steps, "archived": true})
# A quest-style chain earlier in the session saved who guides the party and
# the day's weather, so {@guide} and {@weather} have values.
if m.persistent_vars.is_empty():
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, scratch)
for pair in [["@guide", "names"], ["@weather", "weather"]]:
if m.data.get_table(pair[1]):
var n := Roller.roll(m.data, pair[1], m.rng, 0, scratch, ctx)
if not n.is_empty() and not n.has("stop"):
ctx.save(pair[0], Formatter.to_export_bbcode(str(n["summary"])), pair[1])
var start := "wilderness" if m.data.get_table("wilderness") else _first_rollable()
if start == "":
m.refresh_live()
m.tray.render()
return
var best: Dictionary
if m.data.get_table("trinkets"):
best = Roller.roll(m.data, start, m.rng, 0, scratch)
for i in 400:
if Roller.reaches(best, "trinkets"):
break
best = Roller.roll(m.data, start, m.rng, 0, scratch)
else:
# Any other board: one roll with the headless answers, through the real
# variables, so variable and sheet cards have values to show.
best = Roller.roll(m.data, start, m.rng, 0, scratch, Roller.new_context(m.data, m.rng, m.persistent_vars, scratch))
var all := Roller.flatten(best, [])
m.current = {"collection": m.data.id, "root": start, "root_name": m.data.get_table(start).name, "time": now - 60,
"steps": all, "all": all, "done": true, "chain_vars": {}}
Roller.collect_lit(best, m.lit_entries, m.lit_pipes, m.lit_texts)
m._refresh_lit()
m.refresh_live()
m.tray.render()
## The first table that can start a roll (not a variable card), or "".
func _first_rollable() -> String:
for t in m.data.tables:
if t.kind != RollTable.KIND_VARIABLE:
return t.id
return ""
## Lights the entries and pipes of a roll from its saved steps.
func _light_steps(steps: Array) -> void:
var stack: Array = []
for s: Dictionary in steps:
var d := int(s.get("depth", 0))
stack.resize(d)
stack.append(s)
if s.get("stop", false) or not s.has("entry_id"):
continue
var tid := str(s.get("table_id", ""))
var ek := Roller.entry_key(tid, str(s["entry_id"]))
m.lit_entries[ek] = true
m.lit_texts[ek] = str(s.get("text", ""))
if d > 0 and not (s.has("pass") or s.has("after")) and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"):
var p: Dictionary = stack[d - 1]
var ptid := str(p.get("table_id", ""))
var peid := str(p["entry_id"])
m.lit_pipes[Roller.ref_key(ptid, peid, tid) if s.get("inline", false) else Roller.pipe_key(ptid, peid, tid)] = true
# ----- Copy -----
## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS.
func copy_current(kind: int) -> void:
if m.current.is_empty():
return
var text := result_text(m.current.get("all", []), kind)
DisplayServer.clipboard_set(text)
m.toast(["Copied as text", "Copied as BBCode", "Copied with details"][clampi(kind, 0, 2)])
## One line per table rolled, indented by depth. Inline rolls are already part
## of their parent's text, so they don't get lines of their own.
func result_text(steps: Array, kind: int) -> String:
var lines := PackedStringArray()
for s: Dictionary in steps:
if s.get("inline", false):
continue
# Long pipe chains nest thousands deep; cap the indent so the text stays usable.
var indent := " ".repeat(mini(int(s.get("depth", 0)), MAX_INDENT))
var tname := str(s.get("table", ""))
var text := str(s.get("text", ""))
if kind == ResultTray.COPY_BBCODE:
lines.append(indent + "[b]%s:[/b] %s" % [Formatter.to_export_bbcode(tname), Formatter.to_export_bbcode(text)])
else:
lines.append(indent + "%s: %s" % [Formatter.strip_tags(tname), Formatter.strip_tags(text)])
if kind == ResultTray.COPY_DETAILS:
var t := m.data.get_table(str(s.get("table_id", "")))
var e := t.find_entry(str(s.get("entry_id", ""))) if t else null
if e and e.details.strip_edges() != "":
var pad := indent + " "
lines.append(pad + Formatter.strip_tags(e.details).strip_edges().replace("\n", "\n" + pad))
return "\n".join(lines)