TableTower/ui/table_card.gd
RobinFiredrake 86d1b214c3 Dynamic pick options, show_if and indirect @[expr] names
Pick choice cards can take their options from variables (options_from:
@prefix_* or a @list, filtered by options_where with option, option_label
and option_value bound). A Chosen entry runs for whichever dynamic option
is picked; fixed entries stay as extras, listed first. Random weighs each
dynamic option as the Chosen entry and fixed ones by weight. Any pick
option can have show_if, which hides it from the pop-up and from Random;
with nothing offered the node stops with "No options available".

@[expr] reads or writes the variable named by expr in expressions,
effects (including reset) and text ({@[expr]}); bad computed names are
effect errors. JSON round trip, lint_options in lint_pipes, choice
pop-up value badges and previews, card and settings UI, docs, demo board
(Spend a find) and tests/test_options.gd.

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

1549 lines
60 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 TableCard
extends PanelContainer
## One table on the board: a header with the collapse toggle, name and die
## button, then its numbered results. Rebuilt from the RollTable whenever the
## mode, the table's shape, or (when collapsed) the lit result changes.
##
## Logic cards (docs/LOGIC.md) share the layout: a choice card has a "?"
## badge, its question and its options (or one Answer row); a loop card shows
## its rule and the Each time / Afterwards rows; a variable card shows its
## live value and has no rows; a sheet card's one row is its rendered
## template; a router card has a fork icon in place of the die and one row
## per case, showing its condition ("if @str >= 8", "Otherwise") with its
## outlet. Live text (values, sheets, prompts) is only re-rendered by
## refresh_live(), which Main calls after rolls and edits, never per frame.
## A pick card whose options come from variables (docs/LOGIC.md §2a) says
## "Options from @skill_* · where …" (in Play with how many are available
## now) and has a Chosen row first; any pick option can have a Show only if
## condition, edited under its row (the "if" toggle) in Build.
const WIDTH := 256.0
## Build mode has more controls per row, so cards are a little wider there.
const BUILD_WIDTH := 300.0
const LONG_LIST := 12
const LIST_HEIGHT := 432.0
const INLET_Y := 30.0
enum RowState { NORMAL, FLICK, LIT }
var main: Main
var table: RollTable
## entry id -> row PanelContainer, for the rows currently shown.
var rows: Dictionary = {}
var more_row: PanelContainer
var list_scroll: ScrollContainer
var _row_parts: Dictionary = {}
var _row_styles: Array[StyleBoxFlat] = []
var _list_box: VBoxContainer
var _more_label: Label
var _warn_panel: Control
var _warn_label: Label
var _die_icon: DieIcon
var _rolling := false
var _dragging := false
var _drop_target := false
var _drag_offset := Vector2.ZERO
var _flick_id := ""
var _style_normal: StyleBoxFlat
var _style_rolling: StyleBoxFlat
var _style_dragging: StyleBoxFlat
var _style_drop: StyleBoxFlat
var _style_selected: StyleBoxFlat
var _selected := false
var _deck_row: Control
var _deck_label: Label
## Entry ids whose details editor is open (Build mode).
var _open_details: Dictionary = {}
## Entry ids whose effects editor is open (Build mode).
var _open_effects: Dictionary = {}
## Entry ids whose Show only if editor is open (Build mode, pick choices).
var _open_show_if: Dictionary = {}
## Play mode: "3 available now" on a dynamic pick card.
var _options_label: Label
var _table_details_open := false
## Live parts, updated by refresh_live().
var _prompt_label: RichTextLabel
var _var_value: Label
var _var_hint: Label
var _sheet_label: RichTextLabel
var _live_cache: Dictionary = {}
func setup(p_main: Main, p_table: RollTable) -> void:
main = p_main
table = p_table
custom_minimum_size = Vector2(WIDTH, 0)
mouse_filter = MOUSE_FILTER_PASS
theme = Style.card_theme()
position = table.position
_style_normal = Style.box(Style.CARD, 10)
_style_normal.shadow_color = Color(0, 0, 0, 0.32)
_style_normal.shadow_size = 16
_style_normal.shadow_offset = Vector2(0, 8)
_style_rolling = _style_normal.duplicate() as StyleBoxFlat
Style.bordered(_style_rolling, 3, Style.BRASS)
_style_rolling.set_expand_margin_all(3)
_style_rolling.shadow_color = Color(Style.BRASS, 0.45)
_style_rolling.shadow_size = 26
_style_rolling.shadow_offset = Vector2.ZERO
_style_drop = _style_rolling.duplicate() as StyleBoxFlat
_style_drop.shadow_color = Color(0, 0, 0, 0.32)
_style_drop.shadow_size = 16
_style_drop.shadow_offset = Vector2(0, 8)
_style_selected = _style_normal.duplicate() as StyleBoxFlat
Style.bordered(_style_selected, 3, Style.COPPER)
_style_selected.set_expand_margin_all(4)
_style_selected.shadow_color = Color(Style.COPPER, 0.5)
_style_selected.shadow_size = 14
_style_selected.shadow_offset = Vector2.ZERO
_style_dragging = _style_normal.duplicate() as StyleBoxFlat
_style_dragging.shadow_color = Color(0, 0, 0, 0.4)
_style_dragging.shadow_size = 26
_style_dragging.shadow_offset = Vector2(0, 16)
for c in [Color(0, 0, 0, 0), Style.FLICK, Style.LIT]:
_row_styles.append(Style.box(c, 0, [12, 6, 22, 6]))
minimum_size_changed.connect(func() -> void: _shrink.call_deferred())
rebuild()
func rebuild() -> void:
for c in get_children():
remove_child(c)
c.queue_free()
rows.clear()
_row_parts.clear()
more_row = null
_more_label = null
list_scroll = null
_flick_id = ""
_deck_row = null
_deck_label = null
_prompt_label = null
_var_value = null
_var_hint = null
_sheet_label = null
_options_label = null
_live_cache.clear()
var build := main.mode == Main.Mode.BUILD
custom_minimum_size = Vector2(card_width(), 0)
_shrink.call_deferred()
var ranged := table.is_ranged()
var collapsed := is_collapsed()
var col := _vbox(0)
add_child(col)
col.add_child(_make_header(build, ranged))
if build and _table_details_open:
var ted := _details_editor(table.details, "Details for this table (BBCode)", 12.0,
func(s: String) -> void:
table.details = s
main.mark_dirty())
ted.add_theme_constant_override("margin_top", 8)
col.add_child(ted)
if table.kind == RollTable.KIND_VARIABLE:
col.add_child(_make_variable_body(build))
_warn_panel = _make_warning()
col.add_child(_warn_panel)
_update_warning()
if build:
col.add_child(_make_footer(ranged))
_apply_style()
refresh_live()
return
var pad := MarginContainer.new()
pad.mouse_filter = MOUSE_FILTER_PASS
pad.add_theme_constant_override("margin_top", 6)
pad.add_theme_constant_override("margin_bottom", 8)
_list_box = _vbox(0)
pad.add_child(_list_box)
if not collapsed and table.entries.size() > LONG_LIST:
list_scroll = ScrollContainer.new()
list_scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
list_scroll.custom_minimum_size = Vector2(0, LIST_HEIGHT)
list_scroll.mouse_filter = MOUSE_FILTER_PASS
_skin_scrollbar(list_scroll.get_v_scroll_bar())
pad.size_flags_horizontal = SIZE_EXPAND_FILL
list_scroll.add_child(pad)
col.add_child(list_scroll)
else:
col.add_child(pad)
var numw := _num_width(build, ranged)
for i in table.entries.size():
var e := table.entries[i]
var lit := main.is_entry_lit(table.id, e.id)
if collapsed and not lit:
continue
if table.kind == RollTable.KIND_SHEET:
_list_box.add_child(_make_sheet_row(e, build))
elif table.kind == RollTable.KIND_ROUTER and build:
_list_box.add_child(_make_case_row(e, i, numw))
else:
_list_box.add_child(_make_row(e, i, build, ranged, numw))
_set_row_state(e.id, RowState.LIT if lit else RowState.NORMAL)
if build and _open_show_if.has(e.id) and _is_pick():
_list_box.add_child(_show_if_editor(e, 12.0 + numw + 4.0))
if build and _open_effects.has(e.id):
_list_box.add_child(_effects_editor(e, 12.0 + numw + 4.0))
if build and _open_details.has(e.id):
_list_box.add_child(_details_editor(e.details, "Details for this result (BBCode)", 12.0 + numw + 4.0,
func(s: String) -> void:
e.details = s
main.mark_dirty()))
if collapsed:
_list_box.add_child(_make_more_row(numw))
_warn_panel = _make_warning()
col.add_child(_warn_panel)
_update_warning()
if build:
col.add_child(_make_footer(ranged))
_apply_style()
refresh_live()
if list_scroll != null:
for eid in rows:
if main.is_entry_lit(table.id, eid):
_reveal_when_laid_out.call_deferred(eid)
break
## Variable and sheet cards always show everything; other cards collapse.
func is_collapsed() -> bool:
return table.collapsed and can_collapse()
func can_collapse() -> bool:
return table.kind != RollTable.KIND_VARIABLE and table.kind != RollTable.KIND_SHEET
func _reveal_when_laid_out(eid: String) -> void:
await get_tree().process_frame
if is_instance_valid(list_scroll):
reveal(eid)
# ---------- Building blocks ----------
func _vbox(sep: int) -> VBoxContainer:
var v := VBoxContainer.new()
v.add_theme_constant_override("separation", sep)
v.mouse_filter = MOUSE_FILTER_PASS
return v
func _hbox(sep: int) -> HBoxContainer:
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", sep)
h.mouse_filter = MOUSE_FILTER_PASS
return h
func _num_width(build: bool, ranged: bool) -> float:
var wide := table.die_size() >= 100
if build and ranged:
return 90.0
if ranged:
return 52.0 if wide else 40.0
return 24.0 if wide else 22.0
func _make_header(build: bool, ranged: bool) -> Control:
var header := PanelContainer.new()
var hs := Style.box(Color(0, 0, 0, 0), 0, [12, 10, 10, 9])
hs.border_width_bottom = 1
hs.border_color = Style.RULE
header.add_theme_stylebox_override("panel", hs)
header.mouse_filter = MOUSE_FILTER_PASS
header.mouse_default_cursor_shape = CURSOR_MOVE
header.gui_input.connect(_on_header_input.bind(header))
var row := _hbox(8)
var head_box := _vbox(4)
header.add_child(head_box)
head_box.add_child(row)
if can_collapse():
var chevron := ChevronButton.new()
chevron.open = not table.collapsed
chevron.tooltip_text = ("Expand " if table.collapsed else "Collapse ") + table.name
chevron.size_flags_vertical = SIZE_SHRINK_CENTER
chevron.pressed.connect(func() -> void: main.toggle_collapse(table.id))
row.add_child(chevron)
header.mouse_entered.connect(func() -> void:
if not _dragging and main.mode == Main.Mode.PLAY:
main.details().show_table(header, table.id, true)
)
if build:
var name_edit := LineEdit.new()
name_edit.text = table.name
name_edit.size_flags_horizontal = SIZE_EXPAND_FILL
name_edit.size_flags_vertical = SIZE_SHRINK_CENTER
name_edit.custom_minimum_size = Vector2(40, 0)
name_edit.add_theme_font_override("font", Style.display(true))
name_edit.add_theme_font_size_override("font_size", 18)
name_edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 6, [7, 3, 7, 3]), 1, Style.RULE))
name_edit.text_changed.connect(func(s: String) -> void:
table.name = s
main.mark_dirty()
)
row.add_child(name_edit)
var gear := Button.new()
gear.text = "⚙"
gear.tooltip_text = "Table settings"
gear.custom_minimum_size = Vector2(26, 26)
gear.size_flags_vertical = SIZE_SHRINK_CENTER
gear.add_theme_font_size_override("font_size", 16)
Style.skin_button(gear, Style.box(Color(0, 0, 0, 0), 6), Style.box(Color("#e6dfcd"), 6), Style.box(Color("#e6dfcd"), 6), Style.MUTED, Style.INK)
gear.pressed.connect(func() -> void: main.request_table_settings(table.id))
row.add_child(gear)
else:
var titles := _vbox(3)
titles.size_flags_horizontal = SIZE_EXPAND_FILL
titles.size_flags_vertical = SIZE_SHRINK_CENTER
titles.mouse_filter = MOUSE_FILTER_IGNORE
var title := Style.make_label(Formatter.strip_tags(table.name), Style.display(true), 20, Style.INK)
title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
if table.details.strip_edges() != "":
# A small ⓘ after the name says hovering shows the table's details.
var name_row := _hbox(4)
name_row.mouse_filter = MOUSE_FILTER_IGNORE
title.size_flags_horizontal = SIZE_EXPAND_FILL
name_row.add_child(title)
var mark := Style.make_label(RichText.INFO_MARK, Style.body(true), 12, Color("#9a9483"))
mark.size_flags_vertical = SIZE_SHRINK_CENTER
name_row.add_child(mark)
titles.add_child(name_row)
else:
titles.add_child(title)
var sub := _subtitle()
if sub != "":
var cl := Style.make_label(sub, Style.body(true), 12, Style.MUTED)
cl.mouse_filter = MOUSE_FILTER_IGNORE
cl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
titles.add_child(cl)
row.add_child(titles)
if table.card_mode:
_deck_row = _make_deck_row()
var go := _make_go_button()
if go != null:
row.add_child(go)
if _deck_row != null:
head_box.add_child(_deck_row)
var extra := _make_kind_header(build)
if extra != null:
head_box.add_child(extra)
return header
## The small line under the title in Play mode ("2d6 + dm(@end) · 2 ranges").
func _subtitle() -> String:
match table.kind:
RollTable.KIND_ROLL:
if table.is_ranged():
var n := "%d ranges" % table.entries.size()
return "%s · %s" % [table.dice_label(), n] if table.is_expr_dice() else n
if table.collapsed:
return "%d results" % table.entries.size()
RollTable.KIND_CHOICE:
if table.collapsed:
return "%d options" % table.entries.size()
RollTable.KIND_ROUTER:
return "if / else if / otherwise · %d %s" % [table.entries.size(), "case" if table.entries.size() == 1 else "cases"]
return ""
## The header button that starts a roll: the die on roll tables, a "?" badge on
## choice cards, a loop arrow on loop cards and "Print" on sheets. Variable
## cards have none.
func _make_go_button() -> Button:
_die_icon = null
if table.kind == RollTable.KIND_VARIABLE:
return null
var b := Button.new()
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_override("font", Style.display(true))
b.add_theme_font_size_override("font_size", 17)
var left := 10
match table.kind:
RollTable.KIND_CHOICE:
b.text = "?"
b.add_theme_font_size_override("font_size", 20)
b.custom_minimum_size = Vector2(36, 0)
b.tooltip_text = "Ask: %s" % Formatter.strip_tags(table.prompt if table.prompt != "" else table.name)
RollTable.KIND_LOOP:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Run %s" % Formatter.strip_tags(table.name)
var icon := Control.new()
icon.mouse_filter = MOUSE_FILTER_IGNORE
icon.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
icon.draw.connect(func() -> void: Icons.draw_loop(icon, icon.size / 2.0 + Vector2(0, -1), 7.0, Style.BRASS, 2.2))
b.add_child(icon)
RollTable.KIND_ROUTER:
b.custom_minimum_size = Vector2(38, 32)
b.tooltip_text = "Route %s: the first case that's true is chosen" % Formatter.strip_tags(table.name)
var fork := Control.new()
fork.mouse_filter = MOUSE_FILTER_IGNORE
fork.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
fork.draw.connect(func() -> void: draw_fork(fork, fork.size / 2.0 + Vector2(0, 0), 8.0, Style.BRASS, 2.2))
b.add_child(fork)
RollTable.KIND_SHEET:
b.text = "Print"
b.add_theme_font_override("font", Style.body_bold(true))
b.add_theme_font_size_override("font_size", 14)
b.tooltip_text = "Print this sheet in the tray"
_:
left = 34
var label := "d%d" % table.die_size()
if table.is_expr_dice():
label = table.dice_label() if table.dice_label().length() <= 5 else "Roll"
b.text = label
b.tooltip_text = "Roll %s on %s\nShift-click to skip the animation" % [table.dice_label(), table.name]
var rn := Style.box(Style.FELT, 8, [left, 6, 10, 6])
rn.border_width_bottom = 2
rn.border_color = Style.FELT_DEEP
var rh := rn.duplicate() as StyleBoxFlat
rh.bg_color = Style.FELT_HOVER
var rp := rn.duplicate() as StyleBoxFlat
rp.border_width_bottom = 1
rp.content_margin_top = 7
rp.content_margin_bottom = 5
Style.skin_button(b, rn, rh, rp, Style.BRASS)
if table.kind == RollTable.KIND_ROLL:
var die := DieIcon.new()
die.spinning = _rolling
_die_icon = die
b.add_child(die)
b.resized.connect(func() -> void: die.position = Vector2(8, (b.size.y - 20.0) / 2.0 - 1.0))
b.pressed.connect(func() -> void: main.start_roll(table.id))
return b
## Kind-specific lines under the header: a choice card's question, a loop's
## rule, a variable's name.
func _make_kind_header(_build: bool) -> Control:
match table.kind:
RollTable.KIND_CHOICE:
var v := _vbox(3)
_prompt_label = RichText.label("", 15, Style.INK, true)
_prompt_label.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_prompt_label)
var kinds := {"pick": "Pick one", "number": "A number", "text": "Your words"}
var info := str(kinds.get(table.choice, ""))
if table.choice == "number":
info += " · %s to %s" % [table.min_expr, table.max_expr]
if table.save_as != "":
info += " · saves %s" % table.save_as
var l := Style.make_label(info, Style.body(true), 12, Style.MUTED)
l.mouse_filter = MOUSE_FILTER_IGNORE
l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
v.add_child(l)
if table.is_dynamic():
var bad := not Roller.lint_options(table).is_empty()
var ol := Style.make_label(options_line(table), Style.body_bold(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
ol.mouse_filter = MOUSE_FILTER_PASS
ol.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
ol.tooltip_text = "One option per %s; the Chosen row runs for whichever is picked (option, option_label and option_value hold it)" % table.options_description()
v.add_child(ol)
if not _build:
_options_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_options_label.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_options_label)
return v
RollTable.KIND_LOOP:
var chip := PanelContainer.new()
chip.mouse_filter = MOUSE_FILTER_PASS
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.16), 6, [8, 1, 8, 2]), 1, Color(Style.BRASS_DARK, 0.35)))
var err := Expr.check(table.loop_expr) if table.loop_expr.strip_edges() != "" else "No rule yet"
var l := Style.make_label(loop_rule(table), Style.display(true), 16, Style.DANGER_INK if err != "" else Style.COPPER_DARK)
l.mouse_filter = MOUSE_FILTER_IGNORE
chip.add_child(l)
chip.tooltip_text = err
return chip
RollTable.KIND_ROUTER:
if not _build:
return null
var rl := Style.make_label("Router · the first true case is chosen", Style.body(true), 12, Style.MUTED)
rl.mouse_filter = MOUSE_FILTER_IGNORE
rl.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
return rl
RollTable.KIND_VARIABLE:
var txt := "@%s · %s" % [table.var_name, table.var_type]
var l := Style.make_label(txt, Style.body(true), 12, Style.MUTED)
l.mouse_filter = MOUSE_FILTER_IGNORE
return l
return null
## A fork: one stem splitting into two branches, each ending in a dot (the
## router card's go button). `r` is about half the icon's height.
static func draw_fork(ci: CanvasItem, c: Vector2, r: float, color: Color, width: float = 2.0) -> void:
var base := c + Vector2(-r, 0)
var split := c + Vector2(-r * 0.15, 0)
ci.draw_line(base, split, color, width, true)
var up := c + Vector2(r * 0.85, -r * 0.75)
var down := c + Vector2(r * 0.85, r * 0.75)
for tip: Vector2 in [up, down]:
var pts := PackedVector2Array()
for k in 9:
var u := float(k) / 8.0
pts.append(split.bezier_interpolate(split + Vector2(r * 0.5, 0), tip - Vector2(r * 0.45, 0), tip, u))
ci.draw_polyline(pts, color, width, true)
ci.draw_circle(tip, width * 1.25, color)
ci.draw_circle(base, width * 0.9, color)
## "Options from @skill_* · where option_value >= 1" for a dynamic pick card.
static func options_line(t: RollTable) -> String:
var s := "Options from " + t.options_from.strip_edges()
if t.options_where.strip_edges() != "":
s += " · where " + t.options_where.strip_edges()
return s
func _is_pick() -> bool:
return table.kind == RollTable.KIND_CHOICE and table.choice == "pick"
## True for the Chosen row of a dynamic pick card.
func _is_chosen_row(index: int) -> bool:
return index == 0 and table.is_dynamic()
## A router case's condition as shown: "if @str >= 8", or "Otherwise".
static func case_label(e: TableEntry) -> String:
var w := e.when.strip_edges()
return "Otherwise" if w == "" else "if " + w
## "× @answer", "while @alive = 1", "until @done".
static func loop_rule(t: RollTable) -> String:
var e := t.loop_expr.strip_edges()
if e == "":
e = "?"
match t.loop_mode:
"while":
return "while " + e
"until":
return "until " + e
return "× " + e
## Card mode: "4 / 6 left" and a small Reshuffle link under the title.
func _make_deck_row() -> Control:
var h := _hbox(6)
var pad := Control.new()
pad.custom_minimum_size = Vector2(26, 0)
pad.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(pad)
_deck_label = Style.make_label("", Style.body(true), 12, Style.MUTED)
_deck_label.size_flags_vertical = SIZE_SHRINK_CENTER
_deck_label.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(_deck_label)
var b := Button.new()
b.text = "↻ Reshuffle"
b.tooltip_text = "Put every card back in the deck"
b.add_theme_font_override("font", Style.body(true))
b.add_theme_font_size_override("font_size", 12)
b.size_flags_vertical = SIZE_SHRINK_CENTER
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(b, n, hv, hv, Style.COPPER, Style.INK)
b.pressed.connect(func() -> void: main.reshuffle_table(table.id))
h.add_child(b)
update_deck()
return h
## Refreshes the cards-left count of a card-mode table.
func update_deck() -> void:
if _deck_label == null or not is_instance_valid(_deck_label):
return
var left := main.cards_left(table.id)
_deck_label.text = "%d / %d left" % [left.x, left.y]
_deck_label.add_theme_color_override("font_color", Style.DANGER_INK if left.x == 0 else Style.MUTED)
func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var h := _hbox(8)
row.add_child(h)
# Loop rows and the Answer row of number/text choices are fixed: no number,
# weight or delete.
var fixed := table.kind == RollTable.KIND_LOOP or (table.kind == RollTable.KIND_CHOICE and table.choice != "pick")
var chosen := _is_chosen_row(index)
var num: Label = null
if build and ranged:
var r := _hbox(2)
r.custom_minimum_size = Vector2(numw, 0)
r.size_flags_vertical = SIZE_SHRINK_CENTER
r.add_child(_range_edit(e, true))
r.add_child(Style.make_label("–", Style.display(true), 15, Style.MUTED))
r.add_child(_range_edit(e, false))
h.add_child(r)
else:
var nl := "" if fixed else (str(index + 1) if table.kind == RollTable.KIND_ROUTER else table.num_label(e, index))
if table.is_dynamic() and not ranged:
nl = "★" if chosen else str(index)
num = Style.make_label(nl, Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_CENTER
if fixed:
num.text = "↻" if table.kind == RollTable.KIND_LOOP and index == 0 else "→"
num.add_theme_font_override("font", Style.body_bold(true))
num.add_theme_font_size_override("font_size", 14)
h.add_child(num)
var text: RichTextLabel = null
if build:
h.add_theme_constant_override("separation", 4)
if table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
var al := Style.make_label("Answer", Style.body_italic(true), 15, Style.MUTED)
al.size_flags_horizontal = SIZE_EXPAND_FILL
al.size_flags_vertical = SIZE_SHRINK_CENTER
al.tooltip_text = "Its effects and pipes run after the player answers ({answer} holds the answer)"
h.add_child(al)
else:
var cbox: VBoxContainer = null
if chosen:
# A caption over the text field, so the field keeps its width.
cbox = _vbox(0)
cbox.size_flags_horizontal = SIZE_EXPAND_FILL
var cl := Style.make_label("Chosen · runs for the picked option", Style.body_italic(true), 11, Style.COPPER_DARK)
cl.mouse_filter = MOUSE_FILTER_PASS
cl.tooltip_text = "Runs for whichever option from %s is picked: option, option_label and option_value hold it" % table.options_from.strip_edges()
cbox.add_child(cl)
h.add_child(cbox)
var edit := LineEdit.new()
edit.text = e.text
if chosen:
edit.placeholder_text = "(the option's name)"
edit.tooltip_text = "The result text. Leave it as Chosen (or empty) to show the picked option's name; {option_label}, {option_value} and {@[option]} work"
edit.size_flags_horizontal = SIZE_EXPAND_FILL
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
edit.add_theme_font_size_override("font_size", 15)
if table.kind == RollTable.KIND_LOOP:
edit.placeholder_text = LOOP_ROWS[clampi(index, 0, 1)]
edit.tooltip_text = "%s: shown each pass ({i} is the pass number)" % LOOP_ROWS[0] if index == 0 else "%s: runs once when the loop ends" % LOOP_ROWS[1]
edit.text_changed.connect(func(s: String) -> void:
e.text = s
main.mark_dirty()
)
if cbox != null:
cbox.add_child(edit)
else:
h.add_child(edit)
if not ranged and not fixed:
h.add_child(_weight_edit(e))
if _is_pick():
var sbad := e.show_if.strip_edges() != "" and Expr.check(TemplateKit.probe(e.show_if.strip_edges())) != ""
var sb := _toggle_button("if", "Show only if: hide this option unless a condition is true when the card is reached",
_open_show_if, e.id, e.show_if.strip_edges() != "", sbad)
sb.add_theme_font_size_override("font_size", 11)
h.add_child(sb)
h.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this comes up",
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
h.add_child(_toggle_button("i", "Details shown when hovering this result",
_open_details, e.id, e.details.strip_edges() != "", false))
if not fixed and not chosen:
var x := Button.new()
x.text = "×"
x.tooltip_text = "Delete this result"
x.custom_minimum_size = Vector2(22, 22)
x.size_flags_vertical = SIZE_SHRINK_CENTER
x.add_theme_font_size_override("font_size", 18)
Style.skin_button(x, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK)
x.pressed.connect(func() -> void: main.delete_entry(table.id, e.id))
h.add_child(x)
else:
var col := _vbox(3)
col.size_flags_horizontal = SIZE_EXPAND_FILL
col.size_flags_vertical = SIZE_SHRINK_CENTER
text = RichText.label(_row_text(e), 16, Style.INK, true)
text.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(text, main)
col.add_child(text)
if _is_pick() and e.show_if.strip_edges() != "":
var si := Style.make_label("only if " + e.show_if.strip_edges(), Style.body_bold(true), 12, Style.COPPER_DARK)
si.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
si.mouse_filter = MOUSE_FILTER_IGNORE
col.add_child(si)
if e.effects.strip_edges() != "":
col.add_child(_effects_chip(e))
h.add_child(col)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
if ranged and table.has_chances():
var pct := Style.make_label("%d%%" % roundi(table.chance(e) * 100.0), Style.body(true), 12, Style.MUTED)
pct.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(pct)
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": text, "entry": e, "index": index}
return row
## Build mode: one router case. The first line is its condition (empty means
## Otherwise), validated as you type, with move up / down and delete; the
## second is its result text with the effects and details toggles.
func _make_case_row(e: TableEntry, index: int, numw: float) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var outer := _hbox(4)
row.add_child(outer)
var num := Style.make_label(str(index + 1), Style.display(true), 16, Style.MUTED)
num.custom_minimum_size = Vector2(numw, 0)
num.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
num.size_flags_vertical = SIZE_SHRINK_BEGIN
outer.add_child(num)
var v := _vbox(3)
v.size_flags_horizontal = SIZE_EXPAND_FILL
outer.add_child(v)
var top := _hbox(4)
v.add_child(top)
var if_label := Style.make_label("if", Style.body_bold(true), 14, Style.COPPER_DARK)
if_label.size_flags_vertical = SIZE_SHRINK_CENTER
top.add_child(if_label)
var cond := LineEdit.new()
cond.text = e.when
cond.placeholder_text = "Otherwise"
cond.size_flags_horizontal = SIZE_EXPAND_FILL
cond.size_flags_vertical = SIZE_SHRINK_CENTER
cond.custom_minimum_size = Vector2(40, 0)
cond.add_theme_font_override("font", Style.body_bold(true))
cond.add_theme_font_size_override("font_size", 14)
cond.add_theme_color_override("font_color", Style.COPPER_DARK)
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK)
var check := func() -> void:
var src := TemplateKit.probe(cond.text.strip_edges())
var err := Expr.check(src) if src != "" else ""
cond.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box)
cond.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box)
cond.tooltip_text = ("⚠ " + err) if err != "" else "This case is chosen when this is true (cases are checked top to bottom). Leave it empty for Otherwise."
if_label.text = "if" if cond.text.strip_edges() != "" else "else"
cond.text_changed.connect(func(t: String) -> void:
e.when = t.strip_edges()
check.call()
_update_warning()
main.mark_dirty()
)
check.call()
top.add_child(cond)
top.add_child(_mini_button("↑", "Move this case up", index > 0, func() -> void: _move_case(index, -1)))
top.add_child(_mini_button("↓", "Move this case down", index < table.entries.size() - 1, func() -> void: _move_case(index, 1)))
top.add_child(_mini_button("×", "Delete this case", true, func() -> void: main.delete_entry(table.id, e.id)))
var bottom := _hbox(4)
v.add_child(bottom)
var edit := LineEdit.new()
edit.text = e.text
edit.placeholder_text = "Result text"
edit.size_flags_horizontal = SIZE_EXPAND_FILL
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.custom_minimum_size = Vector2(40, 0)
edit.add_theme_font_size_override("font_size", 15)
edit.text_changed.connect(func(t: String) -> void:
e.text = t
main.mark_dirty()
)
bottom.add_child(edit)
bottom.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this case is chosen",
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
bottom.add_child(_toggle_button("i", "Details shown when hovering this case",
_open_details, e.id, e.details.strip_edges() != "", false))
rows[e.id] = row
_row_parts[e.id] = {"num": num, "text": null, "entry": e, "index": index}
return row
func _mini_button(glyph: String, tip: String, enabled: bool, on_press: Callable) -> Button:
var b := Button.new()
b.text = glyph
b.tooltip_text = tip
b.disabled = not enabled
b.custom_minimum_size = Vector2(22, 22)
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_size_override("font_size", 16 if glyph == "×" else 13)
Style.skin_button(b, Style.box(Color(0, 0, 0, 0), 5), Style.box(Color("#e6dfcd"), 5), Style.box(Color("#e6dfcd"), 5), Style.MUTED, Style.DANGER_INK if glyph == "×" else Style.INK)
b.add_theme_color_override("font_disabled_color", Color(Style.MUTED, 0.35))
b.pressed.connect(on_press)
return b
## Moves router case `index` up (-1) or down (+1).
func _move_case(index: int, by: int) -> void:
var to := index + by
if to < 0 or to >= table.entries.size():
return
var e := table.entries[index]
table.entries.remove_at(index)
table.entries.insert(to, e)
rebuild()
main.mark_dirty()
## Adds a router case just before the Otherwise case (or at the end). It
## starts as "if false", so it never matches until its condition is written.
func add_case() -> void:
var e := TableEntry.new(TowerBoard.new_id("e"), "New case")
e.when = "false"
var at := table.otherwise_index()
if at < 0 or at != table.entries.size() - 1:
at = table.entries.size()
table.entries.insert(at, e)
table.collapsed = false
rebuild()
main.mark_dirty()
const LOOP_ROWS := ["Each time", "Afterwards"]
## Longest effects summary shown on a Play-mode chip.
const CHIP_CHARS := 30
## A small round toggle in a Build row ("i" details, "ƒ" effects). `open` is
## the dictionary of entry ids whose editor is shown.
func _toggle_button(glyph: String, tip: String, open: Dictionary, eid: String, has: bool, bad: bool) -> Button:
var b := Button.new()
b.text = glyph
b.toggle_mode = true
b.button_pressed = open.has(eid)
b.tooltip_text = tip
b.custom_minimum_size = Vector2(22, 22)
b.size_flags_vertical = SIZE_SHRINK_CENTER
b.add_theme_font_override("font", Style.body_bold(true))
b.add_theme_font_size_override("font_size", 13)
var ring := Style.DANGER_INK if bad else (Style.COPPER if has else Style.DASH)
var inn := Style.bordered(Style.box(Color(0, 0, 0, 0), 11), 1, ring)
var inh := Style.bordered(Style.box(Color("#e6dfcd"), 11), 1, Style.COPPER)
var inp := Style.bordered(Style.box(Style.LIT, 11), 1, Style.COPPER)
Style.skin_button(b, inn, inh, inp, ring if (has or bad) else Style.MUTED, Style.INK)
b.toggled.connect(func(on: bool) -> void:
if on:
open[eid] = true
else:
open.erase(eid)
rebuild()
)
return b
## Play-mode text of a row: the last rolled (expanded) text when the row is
## lit, otherwise the entry as written with its references shown readably.
## Loop rows read "Each time · …"; a number/text choice's row is its answer.
func _row_text(e: TableEntry) -> String:
var rolled := main.lit_text(table.id, e.id)
var s := RichText.decorate(rolled) if rolled != "" else RichText.preview(e.text, main.data)
var muted := Style.MUTED.to_html(false)
if table.kind == RollTable.KIND_LOOP:
var index := table.entries.find(e)
var cap: String = LOOP_ROWS[clampi(index, 0, 1)]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == cap:
s = "[b]%s[/b]" % cap
else:
s = "[color=#%s]%s ·[/color] %s" % [muted, cap, s]
elif table.kind == RollTable.KIND_ROUTER:
var bad := e.when.strip_edges() != "" and Expr.check(e.when.strip_edges()) != ""
var cond := "[color=#%s][b]%s[/b][/color]" % [(Style.DANGER_INK if bad else Style.COPPER_DARK).to_html(false), RichText.plain(case_label(e))]
var plain_text := Formatter.strip_tags(e.text).strip_edges()
if plain_text == "" or plain_text == case_label(e) or plain_text == "if …" or (plain_text == "Otherwise" and e.when.strip_edges() == ""):
s = cond
else:
s = "%s\n%s" % [cond, s]
elif table.is_dynamic() and table.entries.find(e) == 0:
var own := Formatter.strip_tags(e.text).strip_edges()
if rolled != "":
s = "[color=#%s]Chosen ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
elif own == "" or own == Roller.CHOSEN:
s = "[i][color=#%s]Chosen: the picked option[/color][/i]" % muted
else:
s = "[color=#%s]Chosen ·[/color] %s" % [muted, s]
elif table.kind == RollTable.KIND_CHOICE and table.choice != "pick":
if rolled != "":
s = "[color=#%s]Answer ·[/color] [b]%s[/b]" % [muted, RichText.decorate(rolled)]
else:
s = "[i][color=#%s]Answer[/color][/i]" % muted
if e.details.strip_edges() != "":
s += RichText.info_mark()
return s
## Play mode: a subtle brass chip summarising an entry's effects ("STR = 2d6").
func _effects_chip(e: TableEntry) -> Control:
var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty()
var chip := PanelContainer.new()
chip.mouse_filter = MOUSE_FILTER_PASS
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
var bg := Color(Style.DANGER_INK, 0.1) if bad else Color(Style.BRASS, 0.2)
var line := Color(Style.DANGER_INK, 0.4) if bad else Color(Style.BRASS_DARK, 0.3)
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(bg, 5, [6, 0, 6, 1]), 1, line))
var summary := effect_summary(e.effects, main.data)
# Cut long summaries by hand: a clipped Label would collapse to nothing.
if summary.length() > CHIP_CHARS:
summary = summary.substr(0, CHIP_CHARS - 1).strip_edges() + "…"
var l := Style.make_label(summary, Style.body(true), 12, Style.DANGER_INK if bad else Style.COPPER_DARK)
l.mouse_filter = MOUSE_FILTER_IGNORE
chip.add_child(l)
chip.tooltip_text = "\n".join(Effects.split(e.effects))
return chip
## A short summary of effect text: the first two statements, with declared
## variables by their card's name ("STR = 2d6 · Terms += 1 · +3").
static func effect_summary(text: String, board: TowerBoard) -> String:
var list := Effects.split(text)
var parts := PackedStringArray()
for k in mini(2, list.size()):
var st := Effects.parse_statement(list[k])
if st.has("error"):
parts.append("⚠ " + list[k])
continue
var target: String = st["target"]
var shown := target
if board != null and target.begins_with("@") and not target.ends_with("*"):
for t in board.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == target.substr(1):
shown = Formatter.strip_tags(t.name).strip_edges()
break
if st["op"] == "reset":
parts.append("reset " + shown)
else:
parts.append("%s %s %s" % [shown, st["op"], st["expr"]])
if list.size() > 2:
parts.append("+%d" % (list.size() - 2))
return " · ".join(parts)
## Build mode: the Show only if editor under a pick option, validated as you
## type (like a router case's condition).
func _show_if_editor(e: TableEntry, left: float) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var h := _hbox(6)
wrap.add_child(h)
var lbl := Style.make_label("Show only if", Style.body_bold(true), 12, Style.COPPER_DARK)
lbl.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(lbl)
var le := LineEdit.new()
le.text = e.show_if
le.placeholder_text = "always" if not _is_chosen_row(table.entries.find(e)) else "always (hides every option from variables when false)"
le.size_flags_horizontal = SIZE_EXPAND_FILL
le.custom_minimum_size = Vector2(40, 0)
le.add_theme_font_override("font", Style.body_bold(true))
le.add_theme_font_size_override("font_size", 13)
le.add_theme_color_override("font_color", Style.COPPER_DARK)
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 3, 7, 3]), 1, Style.DANGER_INK)
var check := func() -> void:
var src := TemplateKit.probe(le.text.strip_edges())
var err := Expr.check(src) if src != "" else ""
le.add_theme_stylebox_override("normal", bad_box if err != "" else ok_box)
le.add_theme_stylebox_override("focus", bad_box if err != "" else focus_box)
le.tooltip_text = ("⚠ " + err) if err != "" else "Checked when the card is reached: when it's false this option isn't offered, not even to Random. e.g. @commissioned, @last_career != \"Army\""
le.text_changed.connect(func(t: String) -> void:
e.show_if = t.strip_edges()
check.call()
main.mark_dirty()
)
check.call()
h.add_child(le)
return wrap
## Build mode: the effects editor under a row, validated as you type.
func _effects_editor(e: TableEntry, left: float) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var v := _vbox(3)
wrap.add_child(v)
var te := TextEdit.new()
te.text = e.effects
te.placeholder_text = "@hp -= 1\n@gold += 2d6\nreset @loot"
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 58)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 13)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
var ok_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Color(Style.BRASS_DARK, 0.4))
var focus_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.COPPER)
var bad_box := Style.bordered(Style.box(Color("#fbf6e6"), 5, [7, 4, 7, 4]), 1, Style.DANGER_INK)
v.add_child(te)
var msg := Style.make_label("", Style.body(true), 12, Style.DANGER_INK)
msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
v.add_child(msg)
var check := func() -> void:
var problems := Effects.validate(TemplateKit.probe(te.text))
var lines := PackedStringArray()
for p: Dictionary in problems:
lines.append("⚠ %s: %s" % [p["src"], p["error"]])
msg.text = "\n".join(lines)
msg.visible = not lines.is_empty()
te.add_theme_stylebox_override("normal", bad_box if not lines.is_empty() else ok_box)
te.add_theme_stylebox_override("focus", bad_box if not lines.is_empty() else focus_box)
te.text_changed.connect(func() -> void:
e.effects = te.text
check.call()
main.mark_dirty()
)
check.call()
return wrap
## A sheet card's one row: the rendered template in Play, its editor in Build.
func _make_sheet_row(e: TableEntry, build: bool) -> Control:
var row := PanelContainer.new()
row.mouse_filter = MOUSE_FILTER_PASS
row.custom_minimum_size = Vector2(0, 36)
var v := _vbox(6)
row.add_child(v)
if build:
var te := TextEdit.new()
te.text = e.text
te.placeholder_text = "[b]Name[/b] {@name}\nHP {@hp} · Skills {@skill_*}"
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 90)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 14)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
te.tooltip_text = "The sheet's template: BBCode with {@var}, {@prefix_*} and {= expr}"
te.text_changed.connect(func() -> void:
e.text = te.text
main.mark_dirty()
)
v.add_child(te)
var tools := _hbox(4)
tools.add_child(_toggle_button("ƒ", "Effects that run when the chain reaches this sheet",
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
tools.add_child(_toggle_button("i", "Details shown when hovering the sheet",
_open_details, e.id, e.details.strip_edges() != "", false))
var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED)
pv.size_flags_vertical = SIZE_SHRINK_CENTER
tools.add_child(pv)
v.add_child(tools)
_sheet_label = null
else:
_sheet_label = RichText.label("", 15, Style.INK, true)
_sheet_label.size_flags_horizontal = SIZE_EXPAND_FILL
RichText.hook_hover(_sheet_label, main)
v.add_child(_sheet_label)
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, table.id, e.id))
rows[e.id] = row
_row_parts[e.id] = {"num": null, "text": null, "entry": e, "index": 0}
return row
## A variable card's body: its live value, big, and in Build its starting value
## and a reset button.
func _make_variable_body(build: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 14)
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 6)
wrap.add_theme_constant_override("margin_bottom", 10)
var v := _vbox(2)
wrap.add_child(v)
_var_value = Style.make_label("", Style.display(true), 34, Style.INK)
_var_value.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_var_value.mouse_filter = MOUSE_FILTER_PASS
v.add_child(_var_value)
_var_hint = Style.make_label("", Style.body(true), 12, Style.MUTED)
_var_hint.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
_var_hint.mouse_filter = MOUSE_FILTER_IGNORE
v.add_child(_var_hint)
if build:
var h := _hbox(8)
var start := Style.make_label("Starts at %s" % (table.initial if table.initial.strip_edges() != "" else ("0" if table.var_type == "number" else "nothing")),
Style.body(true), 12, Style.MUTED)
start.size_flags_horizontal = SIZE_EXPAND_FILL
start.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(start)
var reset := Button.new()
reset.text = "↺ Reset"
reset.tooltip_text = "Set @%s back to its starting value" % table.var_name
reset.add_theme_font_override("font", Style.body(true))
reset.add_theme_font_size_override("font_size", 12)
var n := Style.box(Color(0, 0, 0, 0), 5, [5, 0, 5, 1])
var hv := Style.box(Color("#e6dfcd"), 5, [5, 0, 5, 1])
Style.skin_button(reset, n, hv, hv, Style.COPPER, Style.INK)
reset.pressed.connect(func() -> void: main.reset_variable(table.var_name))
h.add_child(reset)
v.add_child(h)
return wrap
## Re-renders the live parts (a variable's value, a sheet, a choice's
## question) from the current variables. Only touches labels whose text
## changed. Main calls it after rolls and edits, never per frame.
func refresh_live() -> void:
if is_instance_valid(_var_value):
var d := Roller.variable_display(main.data, main.persistent_vars, table)
var shown := str(d["text"]) if str(d["text"]) != "" else "—"
if _var_value.text != shown:
_var_value.text = shown
var size_px := 34 if shown.length() <= 8 else (24 if shown.length() <= 18 else 17)
_var_value.add_theme_font_size_override("font_size", size_px)
_var_value.add_theme_color_override("font_color", Style.INK if d["set"] else Style.MUTED)
var hint := ""
if str(d["error"]) != "":
hint = "⚠ " + str(d["error"])
elif not d["set"]:
hint = "Not set yet · starts at this"
_var_hint.text = hint
_var_hint.add_theme_color_override("font_color", Style.DANGER_INK if str(d["error"]) != "" else Style.MUTED)
_var_hint.visible = hint != ""
if is_instance_valid(_sheet_label):
var s := RichText.decorate(Roller.render_sheet(main.data, main.persistent_vars, table))
if _sheet_label.text != s:
_sheet_label.text = s
if is_instance_valid(_options_label):
var n := Roller.available_count(table, Roller.live_context(main.data, main.persistent_vars))
var txt := "No options available now" if n == 0 else ("1 option available now" if n == 1 else "%d options available now" % n)
if _options_label.text != txt:
_options_label.text = txt
if is_instance_valid(_prompt_label):
var p: String
if main.mode == Main.Mode.BUILD:
p = RichText.preview(table.prompt, main.data)
else:
p = RichText.decorate(TextExpander.render(table.prompt, Roller.live_context(main.data, main.persistent_vars)))
if _prompt_label.text != p:
_prompt_label.text = p
_prompt_label.visible = table.prompt.strip_edges() != ""
## Weight on a plain table, shown as ×N. Also the number of copies in card mode.
func _weight_edit(e: TableEntry) -> LineEdit:
var edit := LineEdit.new()
edit.text = "×%d" % e.weight
edit.custom_minimum_size = Vector2(34, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 4
edit.tooltip_text = "Weight: how likely this result is, relative to the others (0 = never)"
edit.size_flags_vertical = SIZE_SHRINK_CENTER
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 14)
edit.add_theme_color_override("font_color", Style.MUTED)
var commit := func() -> void:
var digits := ""
for ch in edit.text:
if ch >= "0" and ch <= "9":
digits += ch
var w := clampi(digits.to_int(), 0, 999) if digits != "" else e.weight
edit.text = "×%d" % w
if w != e.weight:
e.weight = w
update_deck()
main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
## A multi-line details editor (BBCode), shown under a row or the header.
func _details_editor(initial: String, placeholder: String, left: float, on_change: Callable) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", int(left))
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_top", 2)
wrap.add_theme_constant_override("margin_bottom", 6)
var te := TextEdit.new()
te.text = initial
te.placeholder_text = placeholder
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 66)
te.scroll_fit_content_height = true
te.add_theme_font_override("font", Style.body(true))
te.add_theme_font_size_override("font_size", 13)
te.add_theme_color_override("font_color", Style.INK)
te.add_theme_color_override("font_placeholder_color", Style.MUTED)
te.add_theme_color_override("caret_color", Style.INK)
te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.RULE))
te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 5, [7, 4, 7, 4]), 1, Style.COPPER))
te.text_changed.connect(func() -> void: on_change.call(te.text))
wrap.add_child(te)
return wrap
func _range_edit(e: TableEntry, is_lo: bool) -> LineEdit:
var edit := LineEdit.new()
edit.text = str(e.range_lo if is_lo else e.range_hi)
edit.custom_minimum_size = Vector2(40, 0)
edit.alignment = HORIZONTAL_ALIGNMENT_CENTER
edit.max_length = 3
edit.tooltip_text = "Range start" if is_lo else "Range end"
edit.add_theme_font_override("font", Style.display(true))
edit.add_theme_font_size_override("font_size", 15)
edit.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.RULE))
edit.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 4, [2, 2, 2, 2]), 1, Style.COPPER))
var commit := func() -> void:
var v := clampi(edit.text.to_int(), table.min_value(), table.die_size())
if is_lo:
e.range_lo = v
else:
e.range_hi = v
if e.range_lo > e.range_hi:
var tmp := e.range_lo
e.range_lo = e.range_hi
e.range_hi = tmp
edit.text = str(e.range_lo if is_lo else e.range_hi)
_update_warning()
main.mark_dirty()
edit.text_submitted.connect(func(_t: String) -> void: commit.call())
edit.focus_exited.connect(commit)
return edit
func _make_more_row(numw: float) -> Control:
more_row = PanelContainer.new()
var normal := Style.box(Color(0, 0, 0, 0), 0, [12, 6, 22, 6])
var hover := Style.box(Style.HOVER_ROW, 0, [12, 6, 22, 6])
more_row.add_theme_stylebox_override("panel", normal)
more_row.custom_minimum_size = Vector2(0, 36)
more_row.mouse_filter = MOUSE_FILTER_STOP
more_row.mouse_default_cursor_shape = CURSOR_POINTING_HAND
more_row.tooltip_text = "Show every result"
more_row.mouse_entered.connect(func() -> void: more_row.add_theme_stylebox_override("panel", hover))
more_row.mouse_exited.connect(func() -> void: more_row.add_theme_stylebox_override("panel", normal))
more_row.gui_input.connect(func(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT and not mb.pressed:
main.toggle_collapse.call_deferred(table.id)
)
var h := _hbox(8)
more_row.add_child(h)
var dots := Style.make_label("…", Style.display(true), 16, Style.MUTED)
dots.custom_minimum_size = Vector2(numw, 0)
dots.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT
h.add_child(dots)
_more_label = Style.make_label(_more_text(), Style.body_italic(true), 14, Style.MUTED)
_more_label.size_flags_horizontal = SIZE_EXPAND_FILL
_more_label.size_flags_vertical = SIZE_SHRINK_CENTER
h.add_child(_more_label)
return more_row
func _more_text() -> String:
var hidden := table.entries.size() - rows.size()
if rows.size() > 0:
return "%d more · show all" % hidden
return "%d %s · show all" % [table.entries.size(), "ranges" if table.is_ranged() else "results"]
func _make_warning() -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 12)
wrap.add_theme_constant_override("margin_bottom", 10)
var panel := PanelContainer.new()
panel.add_theme_stylebox_override("panel", Style.box(Style.WARN_BG, 6, [9, 6, 9, 6]))
panel.mouse_filter = MOUSE_FILTER_PASS
_warn_label = Style.make_label("", Style.body(true), 13, Style.WARN_INK)
_warn_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
panel.add_child(_warn_label)
wrap.add_child(panel)
return wrap
func _update_warning() -> void:
var problems := table.range_problems()
var lines := PackedStringArray()
for item: Dictionary in Roller.lint_router(table):
lines.append(str(item["message"]))
for item: Dictionary in Roller.lint_options(table):
lines.append(str(item["message"]))
if not lines.is_empty():
problems = ("%s\n" % problems if problems != "" else "") + "\n".join(lines)
_warn_label.text = problems
_warn_panel.visible = problems != ""
func _make_footer(ranged: bool) -> Control:
var wrap := MarginContainer.new()
wrap.mouse_filter = MOUSE_FILTER_PASS
wrap.add_theme_constant_override("margin_left", 12)
wrap.add_theme_constant_override("margin_right", 10)
wrap.add_theme_constant_override("margin_bottom", 10)
var h := _hbox(8)
wrap.add_child(h)
# Loops, sheets, variables and number/text choices have fixed rows.
if table.kind == RollTable.KIND_ROLL or (table.kind == RollTable.KIND_CHOICE and table.choice == "pick"):
var label := "+ Add range" if ranged else ("+ Add option" if table.kind == RollTable.KIND_CHOICE else "+ Add result")
var add := _footer_button(label, Style.INK)
add.pressed.connect(func() -> void: main.add_entry(table.id))
h.add_child(add)
elif table.kind == RollTable.KIND_ROUTER:
var addc := _footer_button("+ Add case", Style.INK)
addc.tooltip_text = "Add a case before Otherwise"
addc.pressed.connect(add_case)
h.add_child(addc)
var det := _footer_button("Details", Style.INK)
det.tooltip_text = "Details shown when hovering the table's name"
if table.details.strip_edges() != "":
det.add_theme_color_override("font_color", Style.COPPER)
det.pressed.connect(func() -> void:
_table_details_open = not _table_details_open
rebuild()
)
h.add_child(det)
var spacer := Control.new()
spacer.size_flags_horizontal = SIZE_EXPAND_FILL
spacer.mouse_filter = MOUSE_FILTER_IGNORE
h.add_child(spacer)
var del := _footer_button("Delete", Style.DANGER_INK)
del.tooltip_text = "Delete this table"
del.pressed.connect(func() -> void: main.delete_table(table.id))
h.add_child(del)
return wrap
func _footer_button(text: String, hover_color: Color) -> Button:
var b := Button.new()
b.text = text
b.add_theme_font_size_override("font_size", 14)
var normal := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, Style.DASH)
var hover := Style.bordered(Style.box(Color(0, 0, 0, 0), 6, [10, 4, 10, 4]), 1, hover_color if hover_color != Style.INK else Style.MUTED)
Style.skin_button(b, normal, hover, hover, Style.MUTED, hover_color)
return b
func _skin_scrollbar(bar: VScrollBar) -> void:
var track := Style.box(Color(0, 0, 0, 0), 3, [3, 0, 3, 0])
var grab := Style.box(Color(0, 0, 0, 0.22), 3, [3, 0, 3, 0])
var grab_hi := Style.box(Color(0, 0, 0, 0.35), 3, [3, 0, 3, 0])
bar.add_theme_stylebox_override("scroll", track)
bar.add_theme_stylebox_override("scroll_focus", track)
bar.add_theme_stylebox_override("grabber", grab)
bar.add_theme_stylebox_override("grabber_highlight", grab_hi)
bar.add_theme_stylebox_override("grabber_pressed", grab_hi)
# ---------- State ----------
func _set_row_state(eid: String, state: RowState) -> void:
if not rows.has(eid):
return
(rows[eid] as PanelContainer).add_theme_stylebox_override("panel", _row_styles[state])
var parts: Dictionary = _row_parts[eid]
var num: Label = parts["num"]
if num:
num.add_theme_color_override("font_color", Style.INK if state == RowState.LIT else Style.MUTED)
var text: RichTextLabel = parts["text"]
if text:
RichText.set_fonts(text, 16, true, state == RowState.LIT)
## Re-renders a Play-mode row's text (it shows the rolled text while lit).
func _update_row_text(eid: String) -> void:
var parts: Dictionary = _row_parts.get(eid, {})
var text: RichTextLabel = parts.get("text")
if text:
var want := _row_text(parts["entry"])
if text.text != want:
text.text = want
func _apply_style() -> void:
var s := _style_normal
if _drop_target:
s = _style_drop
elif _rolling:
s = _style_rolling
elif _selected:
s = _style_selected
elif _dragging:
s = _style_dragging
add_theme_stylebox_override("panel", s)
## Build-mode selection (Main.selection): a copper ring around the card.
func set_selected(on: bool) -> void:
if _selected != on:
_selected = on
_apply_style()
func is_selected() -> bool:
return _selected
func _shrink() -> void:
size = Vector2(card_width(), 0)
func card_width() -> float:
return BUILD_WIDTH if main.mode == Main.Mode.BUILD else WIDTH
func set_rolling(on: bool) -> void:
_rolling = on
if is_instance_valid(_die_icon):
_die_icon.spinning = on
_apply_style()
func set_drop_target(on: bool) -> void:
_drop_target = on
_apply_style()
func flick_random() -> void:
clear_flick()
if rows.is_empty():
return
var keys := rows.keys()
_flick_id = keys[main.rng.randi_range(0, keys.size() - 1)]
_set_row_state(_flick_id, RowState.FLICK)
func clear_flick() -> void:
if _flick_id != "":
_set_row_state(_flick_id, RowState.LIT if main.is_entry_lit(table.id, _flick_id) else RowState.NORMAL)
_flick_id = ""
func set_more_text(text: String) -> void:
if _more_label:
_more_label.text = text
## Updates highlights after a roll. Collapsed cards rebuild so the rolled result shows.
func refresh_lit() -> void:
update_deck()
if is_collapsed():
var want: Array = []
for e in table.entries:
if main.is_entry_lit(table.id, e.id):
want.append(e.id)
if want != rows.keys():
rebuild()
elif _more_label:
_more_label.text = _more_text()
return
for eid in rows:
_update_row_text(eid)
_set_row_state(eid, RowState.LIT if main.is_entry_lit(table.id, eid) else RowState.NORMAL)
## Scrolls a long list so the given result sits in the middle.
func reveal(eid: String) -> void:
if list_scroll == null or not rows.has(eid):
return
var row: Control = rows[eid]
list_scroll.scroll_vertical = int(row.position.y + 6.0 - list_scroll.size.y / 2.0 + row.size.y / 2.0)
func hidden_has_pipes() -> bool:
for e in table.entries:
if not rows.has(e.id) and (not e.pipes.is_empty() or not main.ref_targets_for(e).is_empty()):
return true
return false
# ---------- Geometry (world coordinates) ----------
func inlet_point() -> Vector2:
return Vector2(position.x, position.y + INLET_Y)
## Where a pipe leaves this card for an entry: its row, or the "more" row when the
## entry is hidden in a collapsed card. Rows scrolled out of a long list clamp to
## its edge. Returns {} if there's nowhere to anchor.
func anchor_for(eid: String) -> Dictionary:
var row: Control = rows.get(eid, more_row)
if row == null or not row.is_inside_tree():
return {}
var to_world := main.board.world.get_global_transform().affine_inverse()
var r := row.get_global_rect()
var y := (to_world * (r.position + Vector2(0, r.size.y / 2.0))).y
var shown := true
if list_scroll != null and rows.has(eid):
var sr := list_scroll.get_global_rect()
var top := (to_world * sr.position).y + 14.0
var bottom := (to_world * sr.end).y - 14.0
shown = y >= top - 4.0 and y <= bottom + 4.0
y = clampf(y, top, bottom)
return {"pos": Vector2(position.x + size.x, y), "visible": shown}
# ---------- Input ----------
func _gui_input(ev: InputEvent) -> void:
# Clicks on the card body shouldn't pan the board; the wheel still passes through.
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
accept_event()
## Dragging the header moves the card (and, in Build, every selected card).
## In Build, Ctrl- or Shift-click adds the card to the selection or takes it
## out; dropping a card into a group frame adds it to that group (Main).
func _on_header_input(ev: InputEvent, header: Control) -> void:
var mb := ev as InputEventMouseButton
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
if mb.pressed:
main.details().hide_for()
var build := main.mode == Main.Mode.BUILD
if build and (mb.ctrl_pressed or mb.shift_pressed or mb.meta_pressed):
main.toggle_selected(table.id)
header.accept_event()
return
if build and not main.is_selected(table.id):
main.clear_selection()
_dragging = true
_drag_offset = main.board.world_mouse() - position
get_parent().move_child(self, -1)
main.begin_card_drag(self)
elif _dragging:
_dragging = false
main.end_card_drag(self)
else:
main.mark_dirty()
_apply_style()
header.accept_event()
return
var mm := ev as InputEventMouseMotion
if mm and _dragging:
var p := main.board.world_mouse() - _drag_offset
main.drag_card(self, Vector2(maxf(10.0, roundf(p.x)), maxf(10.0, roundf(p.y))))
header.accept_event()