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