diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b060bc1..2989680 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -261,6 +261,14 @@ Each original file keeps one-line delegators, so callers are unchanged. `InspectorSync.sync_texts` and `TableCardEditing.sync_text` / `text_fields` update them in place. Timing tool: `tests/perf_typing.gd` (SPREAD=… CARD=…; not in the suite). +## 3i. Modules added 2026-11-25 (speed round 1) +- `ui/card_refresh_queue.gd` `CardRefreshQueue` (`Main.card_refresh`): after a mode switch, rebuilds + cards in view at once and the rest within a time budget per frame; `ensure(tid)` rebuilds a + waiting card now (Inspector.select, focusing a card); `finish()` before layout work + (`MainNavigation._layout_blocks`); `holds_redraw()` lets `BoardView` skip thread redraws while + only off-screen cards change. Tests set `frame_usec` very high (AppTestBase). +- `tests/perf_actions.gd`: times everyday actions on a real spread (see its header). + ## 4. Data and storage - **Collections:** `user://collections/.json`, format_version 2 (`{format_version, id, name, tables, groups?}`). On Linux that's `~/.local/share/godot/app_userdata/TableTower/`. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 3feb791..76841e5 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -243,15 +243,25 @@ that works on any theme (solid background, stronger text, thicker borders, no ef Now rows/cells skip restyling when their look is unchanged, and Earlier reuses its rows: ~240 ms per roll, flat (most of it is the 2–3 questions, each relighting ~70 ms first). Timing tool: `tests/perf_roll.gd` (SPREAD=… CARD=…; not in the suite). -- **Test budget and audit: done 2026-11-25** (branch `test-budget`, not merged). 51 suites in ~12 s +- **Test budget and audit: done 2026-11-25** (merged to `main`). 51 suites in ~12 s (was 45 s). Cut coverage: fewer repeats in `test_roller`, `test_logic_ui` (chain of 321, above the cap of 300), `test_undo` (320 cards), `test_navigation` (20 rows); the 10,000-action limit stays in `test_logic` and `test_check_inputs` only, so nothing checks that message in the tray. App crash fixed: a roll still animating went on after `Main` was freed (`Main._exit_tree`). -- **Next: the app is sluggish.** The user has a second request about this; ask what it is first. - Measured headless 2026-11-25 on the demo cut to 12-row tables (~1,200 nodes): start ~400 ms, - to Build 330–370 ms, to Play ~200 ms plus an ~85 ms frame, `_rebuild_cards` ~190 ms. Suspect: - `MainLayout.set_mode` rebuilds every card. Logic demo: roll logic ~1 ms, app roll 130–170 ms. +- **Sluggish app: round 1 done 2026-11-25** (merged to `main` and pushed with `test-budget`; + not hand-tested). The user first asked to port the heaviest code to C#; profiling showed the time + is in Godot's own calls, not GDScript, so C# was dropped (the user agreed). Fixed: right-click + format menus are made on first right-click (`FormatMenu`); dashed reference threads draw in one + call (`PipeGeometry.dash_segments`); inspector rebuilds keep closed sections (`InspectorList`); + card rows are styled before they join the card; a mode switch rebuilds cards in view at once and + the rest a few per frame (`CardRefreshQueue`; threads redraw only now and then meanwhile). + Windowed timings, Perilous Void (152 cards), before → after: one key 359 → 53 ms, add a result + 945 → 178 ms, connect a thread 1,009 → 200 ms, card drag 374 → 53 ms per move, to Build + 6.7 s frozen → 0.35 s, then the rest catches up over ~2.6 s while the app keeps running. + Timing tool: `tests/perf_actions.gd` (SPREAD=… STATE_DIR=…; not in the suite). Left: every + thread still redraws when anything moves (~26 ms on Perilous Void); a card rebuild is ~40 ms; + roll animation timing is deliberate (the user: keep it; Skip animations exists). + `board_view.gd` is at 422 lines, over the limit (size audit). - Known gaps: ARCHITECTURE.md §7. ## 5. Working on it diff --git a/tests/app_testbase.gd b/tests/app_testbase.gd index ef529a9..bdd73b1 100644 --- a/tests/app_testbase.gd +++ b/tests/app_testbase.gd @@ -42,6 +42,7 @@ func start_main(with_demo: bool = true) -> bool: if main.data == null: main.data = _short_demo() if with_demo else _empty_spread() root.add_child(main) + main.card_refresh.frame_usec = 1 << 40 await _frames(5) if main._saving_enabled: abort("Saving is enabled; refusing to run.") diff --git a/tests/perf_actions.gd b/tests/perf_actions.gd new file mode 100644 index 0000000..eea23b9 --- /dev/null +++ b/tests/perf_actions.gd @@ -0,0 +1,177 @@ +extends AppTestBase +## Times everyday actions on one spread: rolling, typing, adding a result, +## connecting a thread, dragging a card, switching modes and saving. Each line +## is the median of a few runs: the call itself, then the slowest of the next +## four frames. Not part of the suite (the name doesn't start with test_). Run: +## SPREAD=/path/to/spread.json STATE_DIR=/folder/holding/a/copy/of/state/ \ +## SUITES=perf_actions godot --headless --path . -s res://tests/run_suites.gd -- --sample +## STATE_DIR must be a copy: the tool saves into it. + +const RUNS := 5 +const FRAMES_AFTER := 4 + +var card_id := "" + + +func run() -> void: + if not await start_main(false): + return + DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) + Engine.max_fps = 0 + main.card_refresh.frame_usec = CardRefreshQueue.FRAME_USEC + main.prompt_hook = func(req: Dictionary) -> Variant: + return 0 if not (req.get("options", []) as Array).is_empty() else req.get("default", 1) + main.data.load_json(FileAccess.get_file_as_string(OS.get_environment("SPREAD"))) + main._rebuild_cards() + await _frames(20) + card_id = _longest_card() + var table := main.data.get_table(card_id) + print("PERF spread %s: %d cards, %d built, %d nodes; timing card %s (%d results)" % [main.data.name, + main.data.tables.size(), main.cards.size(), Performance.get_monitor(Performance.OBJECT_NODE_COUNT), + table.name, table.entries.size()]) + await _time("idle frame", func() -> void: pass) + await _play_timings() + await _build_timings() + _save_timings() + finish() + + +## The expanded card on the board with the most results. +func _longest_card() -> String: + var best := "" + var most := 0 + for tid: String in main.cards: + var table := main.data.get_table(tid) + if table.kind == RollTable.KIND_ROLL and not table.has_columns() and table.entries.size() > most: + best = tid + most = table.entries.size() + return best + + +func _play_timings() -> void: + await _time("fast roll", func() -> void: await main.rolling.start_roll(card_id, true)) + var started := Time.get_ticks_usec() + await main.rolling.start_roll(card_id) + print("PERF animated roll, whole: %.0f ms, %d steps" % [_ms(started), (main.current["all"] as Array).size()]) + _part(" part: relight all cards", main._refresh_lit) + _part(" part: live cards", main.refresh_live) + _part(" part: results tray", main.tray.render) + _part(" part: board changed", main._board_changed) + await _time_switch("to Build", Main.Mode.BUILD) + + +func _build_timings() -> void: + var table := main.data.get_table(card_id) + table.collapsed = false + main.select_card(card_id) + await _frames(20) + main.card_for(card_id).rebuild() + await _frames(5) + var first_id := table.entries[0].id + await _time("type one key", func() -> void: + var edit: LineEdit = main.card_for(card_id).edit_ui.text_fields[first_id] + edit.grab_focus() + edit.text += "x" + edit.text_changed.emit(edit.text)) + await _time("undo step after typing", func() -> void: main.undo_redo._commit_edits()) + main.get_viewport().gui_release_focus() + await _frames(5) + await _time("add a result", func() -> void: main.add_entry(card_id)) + await _time("connect a thread", _connect_thread) + await _time("drag a card (one move)", func() -> void: main.card_for(card_id).position += Vector2(7, 3)) + await _time("select another card", _select_next) + await _time("add a card", func() -> void: main.editing.add_table()) + _part(" part: rebuild that card", main.card_for(card_id).rebuild) + _part(" part: rebuild inspector", main.inspector.rebuild) + _part(" part: board changed", main._board_changed) + _part(" part: undo snapshot", func() -> void: EditHistory.capture(main.data)) + _part(" part: inspector signature", func() -> void: main.inspector._signature()) + _part(" part: board signature (every frame)", main.board._signature) + await _time("redraw all threads", func() -> void: main.board.pipes.queue_redraw()) + await _time_switch("to Play", Main.Mode.PLAY) + + +func _save_timings() -> void: + _part(" part: spread to JSON", func() -> void: main.data.to_json()) + var dir := OS.get_environment("STATE_DIR") + if dir == "": + return + var store := StateStore.new(dir) + store.get_history() + _part("save state after a roll (history file)", func() -> void: + store.add_history({"collection": main.data.id, "root": card_id, "root_name": "x", "time": 1.0, "steps": main.current["all"], "chain_vars": {}}) + store.save()) + + +## A mode switch: the call, the slowest frame until every card is rebuilt, and +## how long that takes. +func _time_switch(label: String, mode: Main.Mode) -> void: + var started := Time.get_ticks_usec() + main.set_mode(mode) + var call_ms := _ms(started) + var frames: Array[float] = [] + while not main.card_refresh.is_idle() or frames.size() < FRAMES_AFTER: + var frame_started := Time.get_ticks_usec() + await process_frame + frames.append(_ms(frame_started)) + print("PERF %s: call %.1f ms, slowest frame %.1f, median frame %.1f, all cards ready after %.0f ms (%d frames)" % [label, + call_ms, frames.max(), _median(frames.duplicate()), _ms(started), frames.size()]) + + +var _thread_row := 0 +func _connect_thread() -> void: + var table := main.data.get_table(card_id) + for target: RollTable in main.data.tables: + var entry := table.entries[_thread_row % table.entries.size()] + if target.kind != RollTable.KIND_VARIABLE and target.id != card_id and main.card_for(target.id) and not entry.pipes.has(target.id): + main.editing._card_under_mouse_override = main.card_for(target.id) + main.editing.start_link(card_id, entry.id) + main.editing.finish_link() + main.editing._card_under_mouse_override = null + _thread_row += 1 + return + _thread_row += 1 + + +var _pick := 0 +func _select_next() -> void: + var ids: Array = main.cards.keys() + main.select_card(ids[_pick % ids.size()]) + _pick += 1 + + +## Runs an action a few times and prints the median call time and the median +## of the slowest frame after it. +func _time(label: String, action: Callable) -> void: + var calls: Array[float] = [] + var slowest: Array[float] = [] + for i in RUNS: + var started := Time.get_ticks_usec() + await action.call() + calls.append(_ms(started)) + var worst := 0.0 + for frame in FRAMES_AFTER: + started = Time.get_ticks_usec() + await process_frame + worst = maxf(worst, _ms(started)) + slowest.append(worst) + await _frames(3) + print("PERF %s: call %.1f ms, slowest frame after %.1f ms" % [label, _median(calls), _median(slowest)]) + + +func _part(label: String, action: Callable) -> void: + var times: Array[float] = [] + for i in RUNS: + var started := Time.get_ticks_usec() + action.call() + times.append(_ms(started)) + print("PERF %s: %.1f ms" % [label, _median(times)]) + + +func _ms(started: int) -> float: + return (Time.get_ticks_usec() - started) / 1000.0 + + +func _median(values: Array[float]) -> float: + values.sort() + return values[values.size() / 2] diff --git a/tests/perf_actions.gd.uid b/tests/perf_actions.gd.uid new file mode 100644 index 0000000..818cb02 --- /dev/null +++ b/tests/perf_actions.gd.uid @@ -0,0 +1 @@ +uid://clf7kk0xpqpom diff --git a/tests/run_suites.gd.uid b/tests/run_suites.gd.uid new file mode 100644 index 0000000..7f792ff --- /dev/null +++ b/tests/run_suites.gd.uid @@ -0,0 +1 @@ +uid://07ee6hcw84gf diff --git a/tests/test_inspector_list.gd b/tests/test_inspector_list.gd index 8413da4..fba3403 100644 --- a/tests/test_inspector_list.gd +++ b/tests/test_inspector_list.gd @@ -27,8 +27,10 @@ func run() -> void: await _frames(4) await _test_sections() await _test_open_by_hand() + await _test_closed_sections_stay() await _test_position_and_weight() await _test_lore_tab() + await _test_mode_switch_queue() finish() @@ -78,6 +80,28 @@ func _test_open_by_hand() -> void: _eq(_open_keys(), ["d"], "a click on the spread closes the rest again") +## A rebuild keeps closed sections (and refreshes their titles) but not open ones. +func _test_closed_sections_stay() -> void: + main.select_result("work", "b") + await _frames() + var closed: Control = insp.section_boxes["c"] + var open: Control = insp.section_boxes["b"] + main.add_entry("work") + await _frames() + var added := _t().entries[-1].id + _eq(insp.section_parts.keys(), ["card", "a", "b", "c", "d", added], "a new result gets its section, last") + _check(insp.section_boxes["c"] == closed and insp.section_boxes["b"] != open, "closed sections stay, the open one is built again") + _eq(insp.section_list.get_children(), insp.section_boxes.values(), "the sections are in the results' order, with none left over") + _t().find_entry("c").text = "Joan" + insp.rebuild() + _eq((insp.section_parts["c"]["title"] as Label).text, "Joan", "a kept section shows its new title") + _check(insp.section_boxes["c"] == closed, "and is the same one") + main.delete_entry("work", added) + await _frames() + _eq(insp.section_list.get_children(), insp.section_boxes.values(), "a deleted result's section goes") + _t().find_entry("c").text = "Joe" + + func _test_position_and_weight() -> void: var t := _t() InspectorRange.set_weight(insp, t, t.find_entry("a"), 10) @@ -104,3 +128,19 @@ func _test_lore_tab() -> void: main.book.toggle() main.set_mode(Main.Mode.BUILD) _check(insp.visible, "back in Build the inspector shows") + + +## A mode switch rebuilds the cards in view now and the rest afterwards. +func _test_mode_switch_queue() -> void: + main.set_mode(Main.Mode.PLAY) + var far_card := main.editing.add_table(RollTable.KIND_ROLL, "", Vector2(9000, 9000)) + await _frames() + main.set_mode(Main.Mode.BUILD) + _check(main.card_refresh.is_waiting(far_card.id) and not main.card_refresh.is_waiting("work"), "only the card out of view waits") + main.select_card(far_card.id) + _check(not main.card_refresh.is_waiting(far_card.id), "selecting a waiting card rebuilds it at once") + main.set_mode(Main.Mode.PLAY) + main.set_mode(Main.Mode.BUILD) + await _frames() + _check(not main.card_refresh.is_waiting(far_card.id), "a waiting card is rebuilt soon after") + _eq(main.card_for(far_card.id).edit_ui.text_fields.size(), far_card.entries.size(), "with Build's text fields") diff --git a/tests/test_text.gd b/tests/test_text.gd index bc3c579..4b42cbe 100644 --- a/tests/test_text.gd +++ b/tests/test_text.gd @@ -213,7 +213,14 @@ func _test_format_menu() -> void: var line := LineEdit.new() line.text = "A legendary sword" FormatMenu.attach(line) + var right_click := InputEventMouseButton.new() + right_click.button_index = MOUSE_BUTTON_RIGHT + right_click.pressed = true + line.gui_input.emit(right_click) var menu := line.get_menu() + var item_count := menu.item_count + line.gui_input.emit(right_click) + _eq(menu.item_count, item_count, "a second right-click doesn't add the items again") var labels: Array[String] = [] for i in menu.item_count: labels.append(menu.get_item_text(i)) diff --git a/ui/board_view.gd b/ui/board_view.gd index 355b419..bf1b7a8 100644 --- a/ui/board_view.gd +++ b/ui/board_view.gd @@ -92,6 +92,7 @@ func setup(p_main: Main) -> void: func _process(_delta: float) -> void: if main == null or main.data == null: return + main.card_refresh.step() _signature() var v := PackedFloat32Array([world.position.x, world.position.y, zoom, size.x, size.y]) if v != _view_sig or _culled_rev != geometry_rev: @@ -155,7 +156,9 @@ func _signature() -> void: elif _settle > 0: _settle -= 1 changed = true - if changed: + if changed and main.card_refresh.holds_redraw(): + _settle = 2 + elif changed: geometry_rev += 1 cards.queue_redraw() if cards.far: diff --git a/ui/card_refresh_queue.gd b/ui/card_refresh_queue.gd new file mode 100644 index 0000000..6139af0 --- /dev/null +++ b/ui/card_refresh_queue.gd @@ -0,0 +1,94 @@ +class_name CardRefreshQueue +extends RefCounted +## Rebuilds cards after a switch between Play and Build without stopping the +## app: cards in view at once, the rest a few per frame, the ones that have +## come into view first. Until its turn, a card out of view keeps its old +## layout. Cards are held by id, so a deleted card just drops out. + +## How long one frame may spend on waiting cards (at least one is rebuilt). +const FRAME_USEC := 6000 +## While cards wait, threads redraw in the first frames after a switch (the +## cards in view settle) and then only every so many frames. +const SETTLE_FRAMES := 4 +const REDRAW_EVERY := 12 + +var m: Main +## FRAME_USEC; tests raise it so they don't depend on the machine's speed. +var frame_usec := FRAME_USEC +## Waiting card ids (id -> true). TableCard.rebuild takes its card out. +var _waiting: Dictionary = {} +var _frames_since_switch := 0 + + +func _init(p_main: Main) -> void: + m = p_main + + +## Rebuilds every card: now when it's in view, soon when it isn't. +func rebuild_all() -> void: + var view := m.board.view_rect() + _waiting.clear() + _frames_since_switch = 0 + for tid: String in m.cards: + var card: TableCard = m.cards[tid] + if _in_view(card, view): + card.rebuild() + else: + _waiting[tid] = true + + +## Rebuilds the card now if it was waiting. +func ensure(tid: String) -> void: + if _waiting.has(tid) and m.cards.has(tid): + (m.cards[tid] as TableCard).rebuild() + + +func forget(tid: String) -> void: + _waiting.erase(tid) + + +func is_waiting(tid: String) -> bool: + return _waiting.has(tid) + + +func is_idle() -> bool: + return _waiting.is_empty() + + +## Rebuilds everything still waiting. +func finish() -> void: + for tid: String in _waiting.keys(): + ensure(tid) + _waiting.clear() + + +## True when a redraw of the threads can wait: only cards out of view are +## changing (nothing is being dragged) and more of them are to come. +func holds_redraw() -> bool: + return not _waiting.is_empty() and _frames_since_switch > SETTLE_FRAMES \ + and _frames_since_switch % REDRAW_EVERY != 0 and not Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT) + + +## Called every frame. +func step() -> void: + if _waiting.is_empty(): + return + _frames_since_switch += 1 + var view := m.board.view_rect() + var later: Array[String] = [] + var started := Time.get_ticks_usec() + for tid: String in _waiting.keys(): + if not m.cards.has(tid): + _waiting.erase(tid) + elif _in_view(m.cards[tid], view): + ensure(tid) + else: + later.append(tid) + for tid in later: + if Time.get_ticks_usec() - started >= frame_usec: + return + ensure(tid) + + +func _in_view(card: TableCard, view: Rect2) -> bool: + return card.visible and view.intersects(Rect2(card.position, card.size).grow(TableCard.INLET_Y)) diff --git a/ui/card_refresh_queue.gd.uid b/ui/card_refresh_queue.gd.uid new file mode 100644 index 0000000..043f4d5 --- /dev/null +++ b/ui/card_refresh_queue.gd.uid @@ -0,0 +1 @@ +uid://cqreee6o6l6l3 diff --git a/ui/format_menu.gd b/ui/format_menu.gd index 324c7cf..165b226 100644 --- a/ui/format_menu.gd +++ b/ui/format_menu.gd @@ -30,8 +30,21 @@ const SIZES := [["Small", "[font_size=12]", "[/font_size]"], ["Big", "[font_size const FIRST_ID := 2000 -## Adds the formatting items to `field`'s right-click menu. +## Gives `field` the formatting items, added the first time its menu is about +## to open: a menu with three submenus per field made long cards slow to build. static func attach(field: Control) -> void: + field.gui_input.connect(_add_before_opening.bind(field)) + + +## Runs before the field's own input handling, which opens the menu. +static func _add_before_opening(event: InputEvent, field: Control) -> void: + var click := event as InputEventMouseButton + var right_click := click != null and click.pressed and click.button_index == MOUSE_BUTTON_RIGHT + if right_click or event.is_action_pressed("ui_menu", true): + _add_to(field) + + +static func _add_to(field: Control) -> void: var menu: PopupMenu = field.call("get_menu") if field.has_method("get_menu") else null if menu == null or menu.has_meta("format_menu"): return diff --git a/ui/inspector.gd b/ui/inspector.gd index 8d4d72c..6a46c15 100644 --- a/ui/inspector.gd +++ b/ui/inspector.gd @@ -47,6 +47,9 @@ var fields: Dictionary = {} var open_sections: Dictionary = {} var section_parts: Dictionary = {} var section_boxes: Dictionary = {} +## The box holding the sections and the card it shows, kept between rebuilds. +var section_list: VBoxContainer +var section_list_tid := "" func setup(p_main: Main) -> void: @@ -68,6 +71,7 @@ func select(sel: Dictionary) -> void: if main and main.book and main.book.visible: SideTabs.show_tab(main, SideTabs.INSPECTOR) selection = sel + main.card_refresh.ensure(str(sel.get("tid", ""))) var kind := str(sel.get("kind", "")) if kind == "card" or kind == "result": open_sections = {InspectorList.key_of(sel): true} @@ -329,26 +333,27 @@ func rebuild() -> void: if f is LineEdit: caret = (f as LineEdit).caret_column for c in _content.get_children(): - _content.remove_child(c) - c.queue_free() + if c != section_list: + _content.remove_child(c) + c.queue_free() _live.clear() effects = null show_if_builder = null case_builder = null pipe_parts = {} fields = {} - section_parts.clear() - section_boxes.clear() var t := selected_table() var e := selected_entry() if selection.has("eid") and e == null: t = null if t == null: selection = {} + InspectorList.drop_list(self) InspectorFrame.show_empty(self) else: match str(selection.get("kind", "card")): "pipe": + InspectorList.drop_list(self) InspectorThread.section(self, t, e, str(selection.get("to", ""))) _: InspectorList.build(self, t) diff --git a/ui/inspector_list.gd b/ui/inspector_list.gd index 4568643..9cd384a 100644 --- a/ui/inspector_list.gd +++ b/ui/inspector_list.gd @@ -5,7 +5,8 @@ extends RefCounted ## ## Clicking the card or a result on the spread opens that section and closes the ## rest (Inspector.select). Sections opened by hand stay open until then. -## Only open sections build their fields, so long cards stay quick. +## Only open sections build their fields, so long cards stay quick, and a +## rebuild of the same card keeps the closed sections' headers (`_keep_closed`). ## ## The older section code edits "the selected result" (Inspector.selection, ## fields, effects, ...). So each open section keeps its own parts, and a click @@ -17,20 +18,27 @@ const CARD := "card" ## Builds the whole page for card `t` into the inspector's content box. static func build(insp: Inspector, t: RollTable) -> void: + var kept := _keep_closed(insp, t) insp.section_parts.clear() insp.section_boxes.clear() var keep_selection := insp.selection.duplicate() insp._content.add_child(insp._head("Card · " + Describe.kind_label(t), Inspector._title_of(t.name, "(no name)"))) - var list := InspectorKit.vbox(6) - insp._content.add_child(list) - _section(insp, list, CARD, "Card", "Settings", "", func(body: VBoxContainer) -> void: + var list := insp.section_list + if list == null: + list = InspectorKit.vbox(6) + insp.section_list = list + insp.section_list_tid = t.id + insp._content.add_child(list) + else: + insp._content.move_child(list, -1) + _section(insp, list, kept, CARD, "Card", "Settings", "", func(body: VBoxContainer) -> void: insp.selection = {"kind": "card", "tid": t.id} InspectorCard.build(insp, body, t, false)) if t.kind != RollTable.KIND_VARIABLE: for i in t.entries.size(): var e := t.entries[i] var span := t.num_label(e, i) if t.is_ranged() and e.has_range else "" - _section(insp, list, e.id, _kind_word(t), Inspector._title_of(e.text, "(nothing)"), span, func(body: VBoxContainer) -> void: + _section(insp, list, kept, e.id, _kind_word(t), Inspector._title_of(e.text, "(nothing)"), span, func(body: VBoxContainer) -> void: insp.selection = {"kind": "result", "tid": t.id, "eid": e.id} InspectorRange.build(insp, body, t, e) var outer := insp._content @@ -38,9 +46,49 @@ static func build(insp: Inspector, t: RollTable) -> void: InspectorResult.section(insp, t, e, false) insp._content = outer) insp.selection = keep_selection + for key: String in kept: + var box: Control = kept[key]["box"] + list.remove_child(box) + box.queue_free() + var at := 0 + for key: String in insp.section_boxes: + list.move_child(insp.section_boxes[key], at) + at += 1 activate(insp, key_of(insp.selection)) +## Before a rebuild: the closed sections that can stay, as {key: {box, parts}}. +## Sections with fields go. The list itself goes when the page shows another +## card or isn't a list (Inspector.rebuild keeps only `section_list`). +static func _keep_closed(insp: Inspector, t: RollTable) -> Dictionary: + var kept := {} + if insp.section_list == null: + return kept + if insp.section_list_tid != t.id: + drop_list(insp) + return kept + for key: String in insp.section_boxes: + var box: Control = insp.section_boxes[key] + var parts: Dictionary = insp.section_parts[key] + if parts["built"]: + insp.section_list.remove_child(box) + box.queue_free() + else: + kept[key] = {"box": box, "parts": parts} + return kept + + +## Forgets the list of sections and everything in it. +static func drop_list(insp: Inspector) -> void: + if insp.section_list != null: + insp.section_list.get_parent().remove_child(insp.section_list) + insp.section_list.queue_free() + insp.section_list = null + insp.section_list_tid = "" + insp.section_parts.clear() + insp.section_boxes.clear() + + ## "card" for a card selection, the result's id for a result. static func key_of(sel: Dictionary) -> String: return str(sel.get("eid", "")) if str(sel.get("kind", "")) == "result" else CARD @@ -56,8 +104,17 @@ static func _kind_word(t: RollTable) -> String: ## One section: a header (▸/▾, kind, title, range) and, when open, its body. -static func _section(insp: Inspector, list: VBoxContainer, key: String, kind: String, title: String, span: String, fill: Callable) -> void: +## `kept`: closed sections from before the rebuild; one that still fits is used +## again (and taken out of `kept`). +static func _section(insp: Inspector, list: VBoxContainer, kept: Dictionary, key: String, kind: String, title: String, span: String, fill: Callable) -> void: var open: bool = insp.open_sections.get(key, false) + var look := "%s|%s" % [kind, span] + if not open and kept.has(key) and kept[key]["parts"]["look"] == look: + insp.section_boxes[key] = kept[key]["box"] + insp.section_parts[key] = kept[key]["parts"] + (kept[key]["parts"]["title"] as Label).text = title + kept.erase(key) + return var box := InspectorKit.vbox(0) list.add_child(box) insp.section_boxes[key] = box @@ -82,10 +139,10 @@ static func _section(insp: Inspector, list: VBoxContainer, key: String, kind: St if ev is InputEventMouseButton and (ev as InputEventMouseButton).pressed and (ev as InputEventMouseButton).button_index == MOUSE_BUTTON_LEFT: toggle(insp, key)) box.add_child(head) - var parts := {"head": head, "title": title_label, "fields": {}, "pipe_parts": {}, "built": open} + var parts := {"head": head, "title": title_label, "fields": {}, "pipe_parts": {}, "built": open, "look": look} insp.section_parts[key] = parts if not open: - _style_head(head, false, false) + _style_head(parts, false) return var pad := MarginContainer.new() for side: String in ["margin_left", "margin_right"]: @@ -104,13 +161,19 @@ static func _section(insp: Inspector, list: VBoxContainer, key: String, kind: St parts["effects"] = insp.effects parts["show_if_builder"] = insp.show_if_builder parts["case_builder"] = insp.case_builder - _style_head(head, true, false) + _style_head(parts, false) -static func _style_head(head: PanelContainer, open: bool, active: bool) -> void: +## Outlines the active section's header. A header that already looks this way +## is left alone (restyling makes it lay out again). +static func _style_head(parts: Dictionary, active: bool) -> void: + if parts.get("active") == active: + return + parts["active"] = active + var open: bool = parts["built"] var fill := Style.HOVER_ROW if open else Color(0, 0, 0, 0.04) var sb := Style.bordered(Style.box(fill, 7, [10, 7, 10, 7]), 2 if active else 1, Style.TRIM if active else Style.RULE) - head.add_theme_stylebox_override("panel", sb) + (parts["head"] as PanelContainer).add_theme_stylebox_override("panel", sb) ## Opens or closes a section by its header. Opening one makes it active. @@ -142,8 +205,7 @@ static func activate(insp: Inspector, key: String) -> void: var was := key_of(insp.selection) insp.selection = {"kind": "card", "tid": t.id} if key == CARD else {"kind": "result", "tid": t.id, "eid": key} for k: String in insp.section_parts: - var p: Dictionary = insp.section_parts[k] - _style_head(p["head"], p.get("built", false), k == key) + _style_head(insp.section_parts[k], k == key) if was != key: insp._mark_cards() diff --git a/ui/main.gd b/ui/main.gd index d456240..e4672dc 100644 --- a/ui/main.gd +++ b/ui/main.gd @@ -88,9 +88,11 @@ var inspecting: MainInspectorLink var sound: SoundBoard var cli: MainCli var layout: MainLayout +var card_refresh: CardRefreshQueue func _init() -> void: layout = MainLayout.new(self) + card_refresh = CardRefreshQueue.new(self) top_bar = MainTopBar.new(self) editing = MainEditing.new(self) grouping = MainGroups.new(self) diff --git a/ui/main_layout.gd b/ui/main_layout.gd index f8a79ea..d1c1bf2 100644 --- a/ui/main_layout.gd +++ b/ui/main_layout.gd @@ -163,8 +163,7 @@ func set_mode(new_mode: Main.Mode) -> void: SideTabs.sync(m) if new_mode != Main.Mode.BUILD: m.inspector.clear() - for card in m.cards.values(): - (card as TableCard).rebuild() + m.card_refresh.rebuild_all() for n in m.grouping._group_nodes.values(): (n as GroupCard).rebuild() m.top_bar._update_endless_chip() diff --git a/ui/main_navigation.gd b/ui/main_navigation.gd index b7965fc..211e6fb 100644 --- a/ui/main_navigation.gd +++ b/ui/main_navigation.gd @@ -75,6 +75,9 @@ func focus_table(table_id: String, entry_id: String = "") -> void: c0.rebuild() m.mark_dirty("", false) settle = true + if m.card_refresh.is_waiting(table_id): + m.card_refresh.ensure(table_id) + settle = true var card := m.card_for(table_id) if card == null: return @@ -194,6 +197,7 @@ func _nav_mode_changed() -> void: ## [{rect, group, table}] with one of group / table set. `skip` is a group id ## to leave out. func _layout_blocks(skip: String = "") -> Array: + m.card_refresh.finish() # it needs every card's real size var out: Array = [] var grouped := {} for g in m.data.groups: diff --git a/ui/pipe_batch.gd b/ui/pipe_batch.gd index da6533b..3c42b3a 100644 --- a/ui/pipe_batch.gd +++ b/ui/pipe_batch.gd @@ -105,8 +105,8 @@ func add_ref(pts: PackedVector2Array) -> void: if far: coarse(rid, pts, Color(Style.THREAD, 0.7), 4.0) return - var dashes := PipeGeometry.dashes(pts, 12.0, 7.0) - for dash in dashes: - line(rid, dash, Style.THREAD_DARK, 6.0) - for dash in dashes: - line(rid, dash, Style.THREAD, 3.0) + var segments := PipeGeometry.dash_segments(pts, 12.0, 7.0) + if segments.is_empty(): + return + RenderingServer.canvas_item_add_multiline(rid, segments, PackedColorArray([Style.THREAD_DARK]), 6.0, true) + RenderingServer.canvas_item_add_multiline(rid, segments, PackedColorArray([Style.THREAD]), 3.0, true) diff --git a/ui/pipe_geometry.gd b/ui/pipe_geometry.gd index 6fd3f80..16c6e0b 100644 --- a/ui/pipe_geometry.gd +++ b/ui/pipe_geometry.gd @@ -41,6 +41,17 @@ static func point_along(pts: PackedVector2Array, fraction: float) -> Vector2: return pts[pts.size() - 1] +## The dashes of a polyline as point pairs, so all of them can be drawn in one +## call (draw_multiline): a call per dash made long dashed threads very slow. +static func dash_segments(pts: PackedVector2Array, on: float, off: float) -> PackedVector2Array: + var segments := PackedVector2Array() + for dash in dashes(pts, on, off): + for i in range(1, dash.size()): + segments.append(dash[i - 1]) + segments.append(dash[i]) + return segments + + ## Splits a polyline into dashes `on` long with gaps `off` long. static func dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]: var out: Array[PackedVector2Array] = [] diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd index 038e86b..72c0709 100644 --- a/ui/pipe_layer.gd +++ b/ui/pipe_layer.gd @@ -294,11 +294,11 @@ func _draw_bundle(pts: PackedVector2Array) -> void: func _draw_ref(pts: PackedVector2Array, lit: bool) -> void: if lit: draw_polyline(pts, Color(Style.ACCENT, 0.14), 12.0, true) - var dashes := PipeGeometry.dashes(pts, 12.0, 7.0) - for d in dashes: - draw_polyline(d, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 6.0, true) - for d in dashes: - draw_polyline(d, Style.ACCENT if lit else Style.THREAD, 3.0, true) + var segments := PipeGeometry.dash_segments(pts, 12.0, 7.0) + if segments.is_empty(): + return + draw_multiline(segments, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 6.0, true) + draw_multiline(segments, Style.ACCENT if lit else Style.THREAD, 3.0, true) func path_length(key: String) -> float: diff --git a/ui/table_card_list.gd b/ui/table_card_list.gd index 67be6c1..a737d18 100644 --- a/ui/table_card_list.gd +++ b/ui/table_card_list.gd @@ -39,15 +39,17 @@ func fill(col: VBoxContainer, build: bool, ranged: bool, collapsed: bool) -> voi var lit := card.main.is_entry_lit(card.table.id, e.id) if collapsed and not lit: continue + var row: Control if card.table.kind == RollTable.KIND_SHEET: - card._list_box.add_child(card.rows_ui.make_sheet_row(e, build)) + row = card.rows_ui.make_sheet_row(e, build) elif card.table.kind == RollTable.KIND_ROUTER and build: - card._list_box.add_child(card.edit_ui.make_case_row(e, i, numw)) + row = card.edit_ui.make_case_row(e, i, numw) elif card.table.kind == RollTable.KIND_CHECK: - card._list_box.add_child(card.rows_ui.make_check_row(e, i, build, numw)) + row = card.rows_ui.make_check_row(e, i, build, numw) else: - card._list_box.add_child(card.rows_ui.make_row(e, i, build, ranged, numw)) + row = card.rows_ui.make_row(e, i, build, ranged, numw) card.rows_ui.set_row_state(e.id, TableCardRows.RowState.LIT if lit else TableCardRows.RowState.NORMAL) + card._list_box.add_child(row) if collapsed: card.more_row = card.rows_ui.make_more_row(numw) card._list_box.add_child(card.more_row) diff --git a/ui/table_card_rebuild.gd b/ui/table_card_rebuild.gd index 64b1c84..0bed520 100644 --- a/ui/table_card_rebuild.gd +++ b/ui/table_card_rebuild.gd @@ -15,6 +15,7 @@ func _init(p_card: TableCard) -> void: func run() -> void: var table := card.table var main := card.main + main.card_refresh.forget(table.id) for child in card.get_children(): if child == card.frame or child == card.group_mark or child == card.grip or child == card.shield: continue @@ -37,8 +38,9 @@ func run() -> void: card._shrink.call_deferred() var ranged := table.is_ranged() var collapsed := card.is_collapsed() + # Built before it joins the card: styling rows already on screen makes their + # text be measured again each time. var column := TableCard.vbox(0) - card.add_child(column) column.add_child(card.header_ui.make(build, ranged)) if not table.inputs.is_empty() and table.kind != RollTable.KIND_VARIABLE: column.add_child(card.header_ui.make_inputs_box()) @@ -79,6 +81,7 @@ func _finish(column: VBoxContainer, build: bool, ranged: bool) -> void: card.update_warning() if build: column.add_child(card.edit_ui.make_footer(ranged)) + card.add_child(column) card.skin.apply_style() card.refresh_live() card.input.raise_covers()