TableTower/io/json_io.gd
RobinFiredrake 85b8a99ef5 Logic cards engine: expressions, effects, choice/loop/variable/sheet cards, coroutine roller
- Expr: @vars, chain vars, dice tokens, dm/has/count, lone = as ==, errors as values, parse cache
- Effects: = += -= *= /= and reset (with prefix), number vs list semantics, logs, validation
- RollTable kinds and per-kind fields with factories; expression dice with end clamping
- TableEntry effects and expression pipe counts; JSON round trip through JsonIO
- TextExpander: {@prefix_*}, {= expr}, number display, expand_async and live render()
- Roller: coroutine with an explicit work stack, prompts for choice cards, loops,
  10,000-action limit, partial tree on ctx.root, iterative flatten/collect_lit
- Variables keep numbers as numbers through StateStore
- Main: awaits the roll with a default (headless) prompt hook, iterative playback,
  long chains show at once

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:38:42 -06:00

442 lines
16 KiB
GDScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class_name JsonIO
extends RefCounted
## JSON import and export of a collection, plus the shared helpers every other
## exporter uses. Everything works on plain collection Dictionaries (the JSON
## form), never on the model classes.
##
## Canonical collection form:
## {"format_version": 2, "id", "name", "tables": [table, ...]}
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
## entry: id, text, [details], [weight], [range], [effects], [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name}
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
## they have their default value.
const FORMAT_VERSION := 2
const _DICE_RE := "^\\s*(\\d+)\\s*[dD]\\s*(\\d+)\\s*$"
const _BBCODE_RE := "(?<!\\[)\\[/?[A-Za-z_]+(?:[= ][^\\]\\[]*)?\\](?!\\])"
const _REF_RE := "\\[\\[(.+?)\\]\\]"
# ---------------------------------------------------------------- export
## Pretty JSON text for a collection. Only known keys are written, so local
## state (card draws, variables, history) can never leak into an export.
static func export_json(collection: Dictionary) -> String:
return JSON.stringify(canonical(collection), " ", false)
## Returns {"ok": bool, "collection": Dictionary, "errors": Array[String],
## "warnings": Array[String]}. `sanitize` is called with every user-visible
## string (names, details, tags, entry text, variable names) and must return
## the cleaned string. The default leaves strings unchanged.
static func import_json(text: String, sanitize: Callable = Callable()) -> Dictionary:
var json := JSON.new()
var errors: Array[String] = []
var warnings: Array[String] = []
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
if not (json.data is Dictionary):
errors.append("The file is not a collection (expected a JSON object).")
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
return import_dict(json.data, sanitize)
## Validates and cleans an already-parsed collection (used by every importer).
## Gives tables and entries fresh ids where they are missing or collide, and
## keeps pipes pointing at the right tables. Same result shape as import_json.
static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Dictionary:
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
var fv: Variant = _num(data.get("format_version", 1), 1)
if (fv is int or fv is float) and fv > FORMAT_VERSION:
errors.append("format_version %s is newer than this version supports (%d)." % [str(fv), FORMAT_VERSION])
if not (data.get("tables") is Array):
errors.append("The collection has no \"tables\" list.")
return result
var raw_tables: Array = data["tables"]
for ti in raw_tables.size():
var rt: Variant = raw_tables[ti]
if not (rt is Dictionary):
errors.append("Table #%d is not an object." % (ti + 1))
continue
var re_list: Variant = rt.get("entries", [])
if not (re_list is Array):
errors.append("Table #%d: \"entries\" is not a list." % (ti + 1))
continue
for ei in (re_list as Array).size():
var re: Variant = re_list[ei]
if not (re is Dictionary or re is String):
errors.append("Table #%d, entry #%d is not an object or text." % [ti + 1, ei + 1])
if not errors.is_empty():
return result
var c := canonical(data)
var clean := func(s: String) -> String:
if sanitize.is_null():
return s
return str(sanitize.call(s))
c["name"] = clean.call(str(c["name"]))
if str(c["name"]) == "":
c["name"] = "Untitled collection"
warnings.append("The collection had no name; called it \"Untitled collection\".")
if str(c["id"]) == "":
c["id"] = slug(str(c["name"]), "collection")
var tables: Array = c["tables"]
# Reserve the first occurrence of every given table id, then hand out new ones.
var used := {}
var id_map := {} # original id -> final id
var needs_id: Array[int] = []
for i in tables.size():
var t: Dictionary = tables[i]
var tid: String = t["id"]
if tid != "" and not used.has(tid):
used[tid] = true
id_map[tid] = tid
else:
needs_id.append(i)
for i in needs_id:
var t2: Dictionary = tables[i]
var old: String = t2["id"]
var fresh := unique_id(slug(str(t2["name"]), "table"), used)
if old != "":
warnings.append("Table id \"%s\" was used twice; \"%s\" is now \"%s\"." % [old, str(t2["name"]), fresh])
t2["id"] = fresh
var by_name := {}
for t3 in tables:
var key := str(t3["name"]).to_lower()
if not by_name.has(key):
by_name[key] = t3["id"]
for t4 in tables:
var t5: Dictionary = t4
t5["name"] = clean.call(str(t5["name"]))
if t5.has("details"):
t5["details"] = clean.call(str(t5["details"]))
for key in ["prompt", "initial"]:
if t5.has(key):
t5[key] = clean.call(str(t5[key]))
if t5.has("tags"):
var tags: Array = []
for tag in t5["tags"]:
tags.append(clean.call(str(tag)))
t5["tags"] = tags
var elist: Array = t5["entries"]
# Entry ids only need to be unique within their table.
var seen := {}
var redo: Array[Dictionary] = []
for e in elist:
var eid: String = e["id"]
if eid == "" or seen.has(eid):
redo.append(e)
else:
seen[eid] = true
var enext := 1
for e1 in redo:
while seen.has("e%d" % enext):
enext += 1
e1["id"] = "e%d" % enext
seen[e1["id"]] = true
for e2 in elist:
var ed: Dictionary = e2
ed["text"] = clean.call(str(ed["text"]))
if ed.has("details"):
ed["details"] = clean.call(str(ed["details"]))
if ed.has("effects"):
ed["effects"] = clean.call(str(ed["effects"]))
if ed.has("range"):
var r: Array = ed["range"]
if int(r[0]) > int(r[1]):
warnings.append("\"%s\": range %d-%d is backwards; dropped." % [str(ed["text"]), int(r[0]), int(r[1])])
ed.erase("range")
if ed.has("pipes"):
var pipes: Array = []
for p in ed["pipes"]:
var info := pipe_info(p)
var target: String = info["table"]
if id_map.has(target):
target = id_map[target]
elif by_name.has(target.to_lower()):
target = by_name[target.to_lower()]
else:
warnings.append("\"%s\" pipes to unknown table \"%s\"." % [str(ed["text"]), target])
if p is Dictionary:
var np: Dictionary = (p as Dictionary).duplicate()
np["table"] = target
if np.has("save_as"):
np["save_as"] = clean.call(str(np["save_as"]))
pipes.append(np)
else:
pipes.append(target)
ed["pipes"] = pipes
result["ok"] = true
result["collection"] = c
return result
# ------------------------------------------------------------ canonical
## Normalizes a collection to format version 2: legacy keys are converted
## (`die` -> `dice`, `triggers` -> `pipes`, `collection` -> `name`), missing
## optional keys are tolerated and unknown keys are dropped.
static func canonical(src: Dictionary) -> Dictionary:
var tables: Array = []
var src_tables: Variant = src.get("tables", [])
if src_tables is Array:
for t in src_tables:
if t is Dictionary:
tables.append(_canon_table(t))
var cname := str(src.get("name", src.get("collection", "")))
return {"format_version": FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
static func _canon_table(td: Dictionary) -> Dictionary:
var t := {
"id": str(td.get("id", "")),
"name": str(td.get("name", "")),
"x": int(_num(td.get("x", 0), 0)),
"y": int(_num(td.get("y", 0), 0)),
}
if bool(td.get("collapsed", false)):
t["collapsed"] = true
var details := str(td.get("details", ""))
if details != "":
t["details"] = details
var tags: Array = []
var src_tags: Variant = td.get("tags", [])
if src_tags is Array:
for tag in src_tags:
tags.append(str(tag))
if not tags.is_empty():
t["tags"] = tags
var dice := str(td.get("dice", "")).strip_edges()
if dice == "" and td.has("die"):
var die: Variant = _num(td["die"], 0)
if (die is int or die is float) and die > 0:
dice = "1d%d" % int(die)
if dice != "":
t["dice"] = dice
for key in ["card_mode", "deck_empty"]:
var v: Variant = td.get(key)
if v != null and not (v is bool and not v) and not (v is String and v == ""):
t[key] = v
# Logic cards (docs/LOGIC.md §9). Defaults are left out.
var kind := str(td.get("kind", "roll"))
if RollTable.KINDS.has(kind) and kind != "roll":
t["kind"] = kind
var defaults := {"choice": "pick", "prompt": "", "save_as": "", "min": "0", "max": "99",
"loop": "times", "loop_expr": "", "var_name": "", "var_type": "number", "initial": ""}
for key: String in defaults:
if not td.has(key) or td[key] == null:
continue
var s := RollTable.expr_text(td[key], str(defaults[key]))
if s != str(defaults[key]):
t[key] = s
var entries: Array = []
var src_entries: Variant = td.get("entries", [])
if src_entries is Array:
for e in src_entries:
entries.append(_canon_entry(e))
t["entries"] = entries
return t
static func _canon_entry(ev: Variant) -> Dictionary:
if ev is String:
return {"id": "", "text": ev}
var ed: Dictionary = ev
var e := {"id": str(ed.get("id", "")), "text": str(ed.get("text", ""))}
var details := str(ed.get("details", ""))
if details != "":
e["details"] = details
var w: Variant = _num(ed.get("weight", 1), 1)
if (w is int or w is float) and w != 1:
e["weight"] = w
var r: Variant = ed.get("range")
if r is Array and (r as Array).size() == 2:
e["range"] = [int(_num(r[0], 0)), int(_num(r[1], 0))]
var effects := str(ed.get("effects", "")) if ed.get("effects") != null else ""
if effects.strip_edges() != "":
e["effects"] = effects
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = []
if src_pipes is Array:
for p in src_pipes:
if p is String and p != "":
pipes.append(p)
elif p is Dictionary and str(p.get("table", "")) != "":
var np := {"table": str(p["table"])}
if p.has("count"):
var cnt: Variant = _num(p["count"], null)
if cnt == null and p["count"] is String and (p["count"] as String).strip_edges() != "":
np["count"] = (p["count"] as String).strip_edges() # an expression
else:
np["count"] = int(cnt if cnt != null else 1)
if str(p.get("save_as", "")) != "":
np["save_as"] = str(p["save_as"])
pipes.append(np)
if not pipes.is_empty():
e["pipes"] = pipes
return e
# -------------------------------------------------------------- helpers
## Turns whole floats (as JSON parsing gives) into ints; returns `fallback`
## for anything that isn't a number.
static func _num(v: Variant, fallback: Variant) -> Variant:
if v is int:
return v
if v is float:
return int(v) if is_equal_approx(v, roundf(v)) else v
if v is String and (v as String).is_valid_float():
return _num((v as String).to_float(), fallback)
return fallback
## Lower-case identifier text: "Melee Weapons" -> "melee_weapons".
static func slug(text: String, fallback: String = "item") -> String:
var re := RegEx.create_from_string("[^a-z0-9]+")
var s := re.sub(text.to_lower(), "_", true)
s = s.trim_prefix("_").trim_suffix("_")
return s if s != "" else fallback
## `base`, or `base_2`, `base_3`... whichever isn't in `used`; marks it used.
static func unique_id(base: String, used: Dictionary) -> String:
var id := base
var n := 2
while used.has(id):
id = "%s_%d" % [base, n]
n += 1
used[id] = true
return id
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
## "count_expr"}. An expression count ("@terms") reads as count 1, with the
## expression in "count_expr" ("" otherwise).
static func pipe_info(p: Variant) -> Dictionary:
if p is Dictionary:
var c: Variant = p.get("count", 1)
var expr := ""
if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
expr = (c as String).strip_edges()
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr}
return {"table": str(p), "count": 1, "save_as": "", "count_expr": ""}
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
## ("×@terms" for an expression count).
static func pipe_label(info: Dictionary) -> String:
var parts: Array[String] = []
if str(info.get("count_expr", "")) != "":
parts.append("×" + str(info["count_expr"]))
elif int(info["count"]) != 1:
parts.append("×%d" % int(info["count"]))
if str(info["save_as"]) != "":
parts.append("→ " + str(info["save_as"]))
return " ".join(parts)
## Removes BBCode tags such as [b] or [color=red]. `[[Table]]` references stay.
static func strip_bbcode(text: String) -> String:
return RegEx.create_from_string(_BBCODE_RE).sub(text, "", true)
## Inline references in entry text: Array of {"name", "var"}.
static func find_refs(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for m in RegEx.create_from_string(_REF_RE).search_all(text):
var inner := m.get_string(1)
var parts := inner.split("->", true, 1)
var ref_name := parts[0].strip_edges()
if ref_name == "":
continue
out.append({"name": ref_name, "var": parts[1].strip_edges() if parts.size() > 1 else ""})
return out
## Highest value a dice string can roll ("1d100" -> 100, "2d6" -> 12); 0 if unparsable.
static func dice_max(dice: String) -> int:
var m := RegEx.create_from_string(_DICE_RE).search(dice)
if m == null:
return 0
return m.get_string(1).to_int() * m.get_string(2).to_int()
## Id of the table whose name matches (case-insensitive), or "".
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
var want := table_name.strip_edges().to_lower()
for t in collection.get("tables", []):
if str(t.get("name", "")).to_lower() == want:
return str(t.get("id", ""))
return ""
## Every connection in a collection, pipes and inline references, in
## table/entry order. Each item: kind ("pipe" or "ref"), table_index,
## entry_index, from_table, from_entry (ids), target (table id, or "" when the
## table is missing), target_name (as written), label, count, save_as,
## entry_text (BBCode stripped). Expects a canonical collection.
static func links(collection: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var tables: Array = collection.get("tables", [])
var ids := {}
for t in tables:
ids[str(t["id"])] = true
for ti in tables.size():
var t2: Dictionary = tables[ti]
var elist: Array = t2.get("entries", [])
for ei in elist.size():
var e: Dictionary = elist[ei]
for p in e.get("pipes", []):
var info := pipe_info(p)
var tgt: String = info["table"]
out.append({
"kind": "pipe", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": tgt if ids.has(tgt) else "", "target_name": tgt,
"label": pipe_label(info), "count": info["count"], "save_as": info["save_as"],
"entry_text": strip_bbcode(str(e["text"])),
})
for ref in find_refs(str(e["text"])):
var rid := table_id_by_name(collection, ref["name"])
out.append({
"kind": "ref", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": rid, "target_name": ref["name"],
"label": ("ref → " + ref["var"]) if ref["var"] != "" else "ref",
"count": 1, "save_as": ref["var"],
"entry_text": strip_bbcode(str(e["text"])),
})
return out
## Display label for a table number range, zero padded; the top of a d100 or
## d1000 reads as zeros ("96–00").
static func range_text(lo: int, hi: int, dmax: int) -> String:
return "%s–%s" % [_num_text(lo, dmax), _num_text(hi, dmax)]
static func _num_text(n: int, dmax: int) -> String:
if dmax >= 100 and _is_power_of_ten(dmax):
if n == dmax:
return "0".repeat(str(dmax - 1).length())
return str(n).pad_zeros(str(dmax - 1).length())
return str(n).pad_zeros(str(maxi(dmax, 1)).length())
static func _is_power_of_ten(n: int) -> bool:
while n >= 10 and n % 10 == 0:
n /= 10
return n == 1