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 var m: Main var _token := 0 var _pulse_tween: Tween ## True when _play_one lit nodes again (after a pause) without redrawing yet. var _relit := false var _choice: ChoiceDialog ## Rolls waiting at a paused thread. var pauses: RollPauses ## Deck-mode draws not shown yet in an animated roll. var deck_reveal: DeckReveal var _seed: MainRollingSeed var _copy: MainRollingCopy func _init(p_main: Main) -> void: m = p_main pauses = RollPauses.new(p_main) deck_reveal = DeckReveal.new(self) _seed = MainRollingSeed.new(p_main) _copy = MainRollingCopy.new(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 var back := RollRange.backwards(t) if back != "": m.toast("%s can't roll: its range %s runs backwards" % [Formatter.strip_tags(t.name), back]) 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 if m.sound: m.sound.play("roll") # The roll's token lives in a holder, so a paused roll set aside can be # made current again (RollPauses.answer). var run := {"token": _token, "fast": fast} # 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(run) 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 var my := int(run["token"]) 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 # Questions light the roll so far at once, so the rest shows at once too; # a pause (or a cost) animates up to itself and the rest animates after. var prompted: bool = run.get("other_prompt", false) m.lit_entries.clear() m.lit_pipes.clear() m.lit_texts.clear() m.lit_columns.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 deck_reveal.hold(m.current["all"], my) m._refresh_lit() m.tray.render() await _play_node(tree, my) if my == _token: deck_reveal.clear() for c in m.cards.values(): (c as TableCard).update_deck() 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, run: Dictionary) -> Variant: if int(run["token"]) != _token: return null m.current["prompted"] = true m.current["asking"] = Formatter.strip_tags(str(req.get("title", ""))) var reply: Variant if str(req.get("kind", "")) == "pause": if run.get("fast", false) or m.rolling_ctx == null: show_progress() else: # The roll so far animates (dice, lights, threads), then it waits. # Steps shown before an earlier pause are listed again as they replay, # and the previous roll's lights go out first. m.current["steps"] = [] m.lit_entries.clear() m.lit_pipes.clear() m.lit_texts.clear() m.lit_columns.clear() m._refresh_lit() await _play_node(m.rolling_ctx.root, int(run["token"])) if int(run["token"]) != _token: return null reply = await pauses.wait(req, run) else: run["other_prompt"] = true show_progress() reply = await m.prompt_hook.call(req) if int(run["token"]) != _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() m.lit_columns.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] var replay: bool = n.get("animated", false) if not replay and _relit: # Nodes shown before a pause were lit without redrawing; do it once. _relit = false m._refresh_lit() m.tray.render() if key != "": m.lit_pipes[key] = true if not replay: 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]) if _relit: _relit = false m._refresh_lit() m.tray.render() ## Animates one node: the card tumbles (plain rolls only), then the result ## lights. A node already animated (before a pause) only lights again, at once. 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 replay: bool = n.get("animated", false) n["animated"] = true var tumble: bool = (not n.has("kind") or bool(n.get("random", false))) and not replay # 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)) TableCardColumns.note_lit(m, ek, n) deck_reveal.release(t.id, e.id) if replay: _relit = true else: m._refresh_lit() if card and not replay: card.reveal(e.id) card.sparkle(e.id) (m.current["steps"] as Array).append(Roller.step_of(n, depth)) if not replay: 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"] deck_reveal.clear() _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]) if card.table.card_mode and m.sound: m.sound.play("card_turn") func _pulse(key: String, my: int) -> void: var length := m.board.pipes.path_length(key) if length <= 0.0 or my != _token: return if m.sound: m.sound.play("thread") 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 (MainRollingSeed.seed_session). func _seed_session() -> void: _seed.seed_session() ## 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", "")) TableCardColumns.note_lit(m, ek, s) 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: _copy.copy_current(kind) ## The steps of a roll as text, one line per table (MainRollingCopy.result_text). func result_text(steps: Array, kind: int) -> String: return _copy.result_text(steps, kind)