RollContext holds chain and persistent variables, depth and the
resolve/roll hooks for one top-level roll. TextExpander expands [[Table]],
[[Table -> var]], [[3x T]], [[1d4 T]], {var}, {@var} and {@var|Table} left to
right, wrapping inserted pieces in internal [url=table:/var:/missing:/unset:/deep:]
meta tags for hover pop-ups. Formatter closes open tags, strips tags for plain
text, exports BBCode without internal markers and filters imported tags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
259 lines
9.3 KiB
GDScript
259 lines
9.3 KiB
GDScript
class_name TextExpander
|
||
extends RefCounted
|
||
## Expands inline table references and variables in entry text.
|
||
##
|
||
## Syntax (expanded strictly left to right, so a chain variable must be saved
|
||
## before it's used):
|
||
## [[Table]] roll on Table and insert the result
|
||
## [[Table -> var]] ...and save it as chain variable "var"
|
||
## [[Table -> @var]] ...and save it as persistent variable "@var"
|
||
## [[3x Gems]] roll 3 times, joined with ", "
|
||
## [[1d4 Coins]] roll 1d4 for the count (NdM, NdM+K, NdM-K)
|
||
## {var} {@var} insert a saved value
|
||
## {@var|Table} use the saved value, else roll on Table, save, insert
|
||
##
|
||
## Inserted pieces are wrapped in internal url tags so the UI can show hover
|
||
## pop-ups through RichTextLabel's meta_hover_started signal:
|
||
## [url=table:<id>]<summary>[/url] one roll on a table
|
||
## [url=var:<name>]<value>[/url] a variable ("@town" for persistent ones)
|
||
## [url=missing:<name>]⚠ <name>[/url] a table that doesn't exist
|
||
## [url=unset:<name>]{<name>?}[/url] a variable that isn't set
|
||
## [url=deep:<id>]⚠ chain too deep[/url] the depth limit was reached
|
||
##
|
||
## BBCode is untouched: known tags (including ones with parameters such as
|
||
## [url={"a":1}]) are copied as-is, and ordinary bracket text like [x] stays text.
|
||
## A reference's name can't contain "[" or "]", so "[[b]x[/b]]" is not one.
|
||
## Use [lb] to write a literal "[[".
|
||
|
||
## Upper limit for [[Nx Table]] and [[NdM Table]] counts.
|
||
const MAX_REPEAT := 100
|
||
const DEEP_TEXT := "⚠ chain too deep"
|
||
|
||
const _VAR_PATTERN := "\\{(@?[A-Za-z_][A-Za-z0-9_]*)(?:\\|([^{}\\[\\]\\n]+))?\\}"
|
||
const _COUNT_PATTERN := "^(?:(\\d+)\\s*[x×]|(\\d*)[dD](\\d+)(?:\\s*([+-])\\s*(\\d+))?)\\s+(\\S.*)$"
|
||
const _SAVE_PATTERN := "^@?[A-Za-z_][A-Za-z0-9_]*$"
|
||
|
||
static var _res: Dictionary = {}
|
||
|
||
|
||
## Expands `text` and returns:
|
||
## text: String the expanded BBCode, with open tags closed at the end
|
||
## children: Array the result nodes rolled inline, in order (one per roll,
|
||
## so [[3x Gems]] adds three)
|
||
static func expand(text: String, ctx: RollContext) -> Dictionary:
|
||
var out: String = ""
|
||
var children: Array = []
|
||
var i: int = 0
|
||
var n: int = text.length()
|
||
while i < n:
|
||
var c: String = text[i]
|
||
if c == "[":
|
||
if i + 1 < n and text[i + 1] == "[":
|
||
var ref: Dictionary = _ref_at(text, i)
|
||
if not ref.is_empty():
|
||
out += _expand_ref(ref, ctx, children)
|
||
i = ref["end"]
|
||
continue
|
||
out += c
|
||
i += 1
|
||
continue
|
||
var tag: Dictionary = Formatter.tag_at(text, i)
|
||
if not tag.is_empty():
|
||
out += tag["raw"]
|
||
i += (tag["raw"] as String).length()
|
||
continue
|
||
elif c == "{":
|
||
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
|
||
if m != null and m.get_start() == i:
|
||
out += _expand_var(m.get_string(1), m.get_string(2).strip_edges(), ctx, children)
|
||
i = m.get_end()
|
||
continue
|
||
out += c
|
||
i += 1
|
||
return {"text": Formatter.close_open_tags(out), "children": children}
|
||
|
||
|
||
## Names of the tables referenced in `text`, without rolling, in order of first
|
||
## appearance and without duplicates. Covers [[...]] references (minus any count
|
||
## prefix and "-> var" part) and the table in {@var|Table}. With a resolver
|
||
## (func(name) -> id), a name like "3x Gems" that is itself a table name is kept
|
||
## whole, the same way expand() decides.
|
||
static func references(text: String, resolve: Callable = Callable()) -> Array[String]:
|
||
var out: Array[String] = []
|
||
var i: int = 0
|
||
var n: int = text.length()
|
||
while i < n:
|
||
var c: String = text[i]
|
||
var name: String = ""
|
||
if c == "[" and i + 1 < n and text[i + 1] == "[":
|
||
var ref: Dictionary = _ref_at(text, i)
|
||
if not ref.is_empty():
|
||
var whole: String = ref["name"]
|
||
name = whole
|
||
var count: Dictionary = _parse_count(whole)
|
||
if not count.is_empty():
|
||
var whole_ok: bool = resolve.is_valid() and str(resolve.call(whole)) != ""
|
||
if not whole_ok:
|
||
name = count["name"]
|
||
i = ref["end"]
|
||
elif c == "[":
|
||
var tag: Dictionary = Formatter.tag_at(text, i)
|
||
if not tag.is_empty():
|
||
i += (tag["raw"] as String).length()
|
||
continue
|
||
elif c == "{":
|
||
var m: RegExMatch = _re(_VAR_PATTERN).search(text, i)
|
||
if m != null and m.get_start() == i:
|
||
name = m.get_string(2).strip_edges()
|
||
i = m.get_end()
|
||
if name != "":
|
||
if not out.has(name):
|
||
out.append(name)
|
||
continue
|
||
i += 1
|
||
return out
|
||
|
||
|
||
## The marker for a reference to a table that doesn't exist.
|
||
static func missing_marker(name: String) -> String:
|
||
return "[url=missing:%s]⚠ %s[/url]" % [name, name]
|
||
|
||
|
||
## The marker for a variable that hasn't been saved. `name` includes any "@".
|
||
static func unset_marker(name: String) -> String:
|
||
return "[url=unset:%s]{%s?}[/url]" % [name, name]
|
||
|
||
|
||
## The marker for a reference past the depth limit. The roller can use it as the
|
||
## summary of a node it stopped for depth.
|
||
static func deep_marker(table_id: String) -> String:
|
||
return "[url=deep:%s]%s[/url]" % [table_id, DEEP_TEXT]
|
||
|
||
|
||
## Rolls an NdM+K expression ("1d4", "d6", "2d6+1", "3d8-2") with `rng`.
|
||
## Returns -1 when the expression isn't valid.
|
||
static func roll_dice(expr: String, rng: RandomNumberGenerator) -> int:
|
||
var m: RegExMatch = _re("^\\s*(\\d*)[dD](\\d+)\\s*(?:([+-])\\s*(\\d+))?\\s*$").search(expr)
|
||
if m == null:
|
||
return -1
|
||
return _roll_parts(m.get_string(1), m.get_string(2), m.get_string(3), m.get_string(4), rng)
|
||
|
||
|
||
static func _roll_parts(num: String, sides: String, op: String, mod: String, rng: RandomNumberGenerator) -> int:
|
||
var dice: int = int(num) if num != "" else 1
|
||
var faces: int = int(sides)
|
||
if faces < 1 or dice > MAX_REPEAT:
|
||
return -1
|
||
var total: int = 0
|
||
for _k in dice:
|
||
total += rng.randi_range(1, faces)
|
||
if mod != "":
|
||
total += int(mod) if op == "+" else -int(mod)
|
||
return total
|
||
|
||
|
||
## Parses "[[...]]" at `pos`. Returns {name, save, end} or {} if it isn't a
|
||
## valid reference (no closing "]]", empty, or containing "[", "]" or a newline).
|
||
static func _ref_at(text: String, pos: int) -> Dictionary:
|
||
var close: int = text.find("]]", pos + 2)
|
||
if close < 0:
|
||
return {}
|
||
var body: String = text.substr(pos + 2, close - pos - 2)
|
||
if body.strip_edges() == "" or body.contains("[") or body.contains("]") or body.contains("\n"):
|
||
return {}
|
||
var name: String = body
|
||
var save_as: String = ""
|
||
var arrow: int = body.rfind("->")
|
||
if arrow >= 0:
|
||
var target: String = body.substr(arrow + 2).strip_edges()
|
||
if _re(_SAVE_PATTERN).search(target) != null:
|
||
save_as = target
|
||
name = body.substr(0, arrow)
|
||
name = name.strip_edges()
|
||
if name == "":
|
||
return {}
|
||
return {"name": name, "save": save_as, "end": close + 2}
|
||
|
||
|
||
## Splits "3x Gems" / "1d4+1 Coins" into {kind: "times"|"dice", ...parts, name}.
|
||
static func _parse_count(name: String) -> Dictionary:
|
||
var m: RegExMatch = _re(_COUNT_PATTERN).search(name)
|
||
if m == null:
|
||
return {}
|
||
if m.get_string(1) != "":
|
||
return {"kind": "times", "times": int(m.get_string(1)), "name": m.get_string(6).strip_edges()}
|
||
return {
|
||
"kind": "dice", "num": m.get_string(2), "sides": m.get_string(3),
|
||
"sign": m.get_string(4), "mod": m.get_string(5), "name": m.get_string(6).strip_edges(),
|
||
}
|
||
|
||
|
||
static func _expand_ref(ref: Dictionary, ctx: RollContext, children: Array) -> String:
|
||
var name: String = ref["name"]
|
||
var times: int = 1
|
||
var id: String = ctx.resolve(name)
|
||
if id == "":
|
||
var count: Dictionary = _parse_count(name)
|
||
if not count.is_empty():
|
||
name = count["name"]
|
||
id = ctx.resolve(name)
|
||
if count["kind"] == "times":
|
||
times = count["times"]
|
||
else:
|
||
times = _roll_parts(count["num"], count["sides"], count["sign"], count["mod"], ctx.rng)
|
||
times = clampi(times, 0, MAX_REPEAT)
|
||
if id == "":
|
||
return missing_marker(name)
|
||
var pieces: PackedStringArray = []
|
||
var plain: PackedStringArray = []
|
||
for _k in times:
|
||
var piece: Dictionary = _roll_one(id, ctx, children)
|
||
pieces.append(piece["text"])
|
||
plain.append(piece["value"])
|
||
var save_as: String = ref["save"]
|
||
if save_as != "":
|
||
ctx.save(save_as, ", ".join(plain), id)
|
||
return ", ".join(pieces)
|
||
|
||
|
||
static func _expand_var(name: String, table: String, ctx: RollContext, children: Array) -> String:
|
||
var value: Variant = ctx.lookup(name)
|
||
if value != null:
|
||
return "[url=var:%s]%s[/url]" % [name, Formatter.close_open_tags(str(value))]
|
||
if table == "":
|
||
return unset_marker(name)
|
||
var id: String = ctx.resolve(table)
|
||
if id == "":
|
||
return missing_marker(table)
|
||
var piece: Dictionary = _roll_one(id, ctx, children)
|
||
if not piece["rolled"]:
|
||
return piece["text"]
|
||
ctx.save(name, piece["value"], id)
|
||
return "[url=var:%s]%s[/url]" % [name, piece["value"]]
|
||
|
||
|
||
## One roll on a resolved table. Returns {text (wrapped for display), value
|
||
## (export BBCode, for saving), rolled (false for depth/missing markers)}.
|
||
static func _roll_one(id: String, ctx: RollContext, children: Array) -> Dictionary:
|
||
if ctx.depth > ctx.max_depth:
|
||
var deep: String = deep_marker(id)
|
||
return {"text": deep, "value": DEEP_TEXT, "rolled": false}
|
||
var node: Dictionary = ctx.roll(id)
|
||
if node.is_empty():
|
||
var missing: String = missing_marker(id)
|
||
return {"text": missing, "value": "", "rolled": false}
|
||
children.append(node)
|
||
var summary: String = Formatter.close_open_tags(str(node.get("summary", "")))
|
||
return {
|
||
"text": "[url=table:%s]%s[/url]" % [id, summary],
|
||
"value": Formatter.to_export_bbcode(summary),
|
||
"rolled": true,
|
||
}
|
||
|
||
|
||
static func _re(pattern: String) -> RegEx:
|
||
if not _res.has(pattern):
|
||
var re := RegEx.new()
|
||
re.compile(pattern)
|
||
_res[pattern] = re
|
||
return _res[pattern]
|