diff --git a/README.md b/README.md index 183e9fd..7404b55 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,25 @@ godot --path . Templates live in `user://templates/` and are shared by every collection; the list can rename, delete, export and import them. - **Moving around:** drag the felt to pan, use the mouse wheel to scroll (Shift for sideways), - Ctrl+wheel or pinch to zoom, and **Fit** to see every table. + Ctrl+wheel or pinch to zoom, and **Fit** to see every table. Zoom goes out far enough + (8%) to fit a board of several hundred cards; that far out, cards show as plain cards with + their title line and group names are written large. +- **Search** (top bar, or **Ctrl+F**) finds cards by name, result text, details, choice + prompts, variable names and group names, ignoring case, accents and BBCode. ↑/↓ pick a + result, Enter or a click jumps to it, Esc closes. Jumping opens the card's group if it's + collapsed (and says so), scrolls a long list to the result, centres the card at a readable + zoom and flashes a ring around it. +- **Map** (beside Fit, or **M**) shows an overview in the corner: groups, cards, lit cards in + brass and the part in view. Click or drag on it to move there. It starts off in Play and + on in Build; the choice is remembered for each mode. +- **Arrange ▾ → Pack collapsed groups** (Build) moves collapsed groups, and the cards and + open groups between them, together to close the gaps collapsed blocks leave, keeping + their order left to right and top to bottom (undo from the toast). Expanding a group + whose frame would now cover its neighbours shifts the blocks to its right further right + and the rows below it further down, just enough to clear it (also with undo). +- **Big boards:** cards inside collapsed groups aren't built until their group opens, and + the board only redraws its pipes and ports when something changes, so an 800-card board + with its groups collapsed opens in well under a second. Collections save automatically to `user://collections/.json`, and card draws, saved variables and roll history to `user://state/state.json` (on Linux, under @@ -101,6 +119,10 @@ Groups and templates: `--select=,`, `--group-selected[=]`, `--coll `--save-template=`, `--save-group-template=first`, `--view=,[,]`, `--fit` and `--clear-result`. +Navigation: `--search=` (the search panel with results), `--focus=
[:]`, +`--minimap` / `--no-minimap`, `--pack` (Build), and `--perf` (prints load time and idle and +panning frame times with vsync off, then quits; `--perf-layers` adds a per-layer breakdown). + This uses the sample board and doesn't save anything. `tools/test_window.sh` runs the game under the window class "TableTower Test" (via a temporary `override.cfg`), which a KWin window rule keeps in the background without focus. diff --git a/tests/test_groups.gd b/tests/test_groups.gd index 671cd5b..19d483b 100644 --- a/tests/test_groups.gd +++ b/tests/test_groups.gd @@ -173,7 +173,8 @@ func _test_collapse() -> void: await process_frame var node := main.group_node(g.id) _check(g.collapsed and node.get_parent() == main.board.cards, "a collapsed group shows as a card") - _check(not main.card_for("a").visible and not main.card_for("b").visible, "its members are hidden") + _check(not _shown("a") and not _shown("b"), "its members are hidden") + _check(main.card_for("a") == null and main.card_for("b") == null, "and have no cards until the group expands") _check(main.card_for("start").visible and main.card_for("out").visible, "other cards stay") var paths: Dictionary = main.board.pipes._paths var into: PackedVector2Array = paths.get("start:e1>a", PackedVector2Array()) @@ -295,16 +296,14 @@ func _test_collapse_all_and_fit() -> void: var g := _group() main.set_all_collapsed(true) await process_frame - _check(g.collapsed and not main.card_for("a").visible, "Collapse all collapses groups too") + _check(g.collapsed and not _shown("a"), "Collapse all collapses groups too") _check(main._collapse_all.text == "Expand all", "the button then offers Expand all") # Fit ignores hidden members: move one far away; the bounds don't reach it. main.data.get_table("a").position = Vector2(30000, 30000) - main.card_for("a").position = Vector2(30000, 30000) var bounds := main.board.content_bounds() _check(bounds.end.x < 5000.0 and bounds.has_point(main.group_node(g.id).position + Vector2(5, 5)), "Fit counts the group card and leaves out its hidden cards: %s" % str(bounds)) main.data.get_table("a").position = Vector2(420, 60) - main.card_for("a").position = Vector2(420, 60) main.set_all_collapsed(false) await process_frame _check(not g.collapsed and main.card_for("a").visible, "Expand all expands groups") @@ -339,6 +338,12 @@ func _test_ungroup_and_delete() -> void: _check(main.data.groups.size() == 1 and main.data.get_table("a") != null and main.card_for("b") != null, "undo brings the group and its cards back") +## True when a table has a card on show (hidden members have no card at all). +func _shown(tid: String) -> bool: + var c := main.card_for(tid) + return c != null and c.visible + + func _check(ok: bool, what: String) -> void: if not ok: _failures += 1 diff --git a/tests/test_navigation.gd b/tests/test_navigation.gd new file mode 100644 index 0000000..503ef4c --- /dev/null +++ b/tests/test_navigation.gd @@ -0,0 +1,341 @@ +extends SceneTree +## Navigation on big boards: search (BoardSearch and the panel), focus_table, +## the minimap, Pack collapsed groups (and making room when a packed group +## expands), and lazily built cards for collapsed groups. +## Run: godot --headless --path . -s res://tests/test_navigation.gd -- --sample + +var _failures := 0 +var main: Main + + +func _init() -> void: + if not OS.get_cmdline_user_args().has("--sample"): + print("Run with -- --sample so the test can't touch saved data.") + quit(2) + return + _test_fold_and_layout() + main = load("res://ui/main.tscn").instantiate() + root.add_child(main) + for i in 5: + await process_frame + if main._saving_enabled: + print("Saving is enabled; refusing to run.") + quit(2) + return + # The headless window is tiny; give the app a real screen's worth of room. + main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT) + main.size = Vector2(1440, 900) + await _load(_board_dict()) + await _test_lazy_cards() + _test_search() + await _test_search_panel() + await _test_focus() + await _test_minimap() + await _load(_board_dict()) + await _test_pack() + await _test_zoom_range() + print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures]) + quit(1 if _failures else 0) + + +## start -> agent (in Careers, 30 results); careers and skills groups +## collapsed, far apart; a variable card and a choice card loose. +func _board_dict() -> Dictionary: + var long_entries: Array = [] + for i in 30: + long_entries.append({"id": "e%d" % i, "text": "Posting %d" % i}) + long_entries[25]["text"] = "Ráre [b]gem[/b] posting" + return {"format_version": 2, "id": "nav-test", "name": "Nav test", "tables": [ + {"id": "start", "name": "Start", "x": 40, "y": 60, "entries": [ + {"id": "e1", "text": "Go to work", "pipes": ["agent"]}, + {"id": "e2", "text": "Learn", "pipes": ["skill"]}]}, + {"id": "agent", "name": "Agent", "x": 3000, "y": 60, "entries": long_entries}, + {"id": "army", "name": "Army", "x": 3400, "y": 60, "details": "Soldiers and gems", "entries": [ + {"id": "e1", "text": "Infantry"}]}, + {"id": "skill", "name": "Gem", "x": 8000, "y": 60, "entries": [{"id": "e1", "text": "Gemology", "pipes": ["gems"]}]}, + {"id": "gems", "name": "Gemstones", "x": 8400, "y": 60, "entries": [{"id": "e1", "text": "Ruby"}]}, + {"id": "end", "name": "Endurance", "kind": "variable", "var_name": "endurance", "x": 40, "y": 3000, "entries": []}, + {"id": "pick", "name": "Pick", "kind": "choice", "prompt": "Which career calls you?", "x": 6000, "y": 3000, "entries": [ + {"id": "e1", "text": "Agent", "pipes": ["agent"]}, {"id": "e2", "text": "Army"}]}, + ], "groups": [ + {"id": "careers", "name": "Careers", "x": 2978, "y": -8, "w": 760, "h": 600, "members": ["agent", "army"], "collapsed": true}, + {"id": "skills", "name": "Skills", "x": 7978, "y": -8, "w": 760, "h": 300, "members": ["skill", "gems"], "collapsed": true}, + ]} + + +func _load(d: Dictionary) -> void: + main.data.load_dict(d) + main.lit_entries.clear() + main.lit_pipes.clear() + main.lit_texts.clear() + main._rebuild_cards() + for i in 4: + await process_frame + + +func _test_fold_and_layout() -> void: + _check(BoardSearch.fold("Ráre ÉCOLE") == "rare ecole", "fold lowers case and drops accents: %s" % BoardSearch.fold("Ráre ÉCOLE")) + _check(BoardSearch.fold("Ráre").length() == 4, "fold keeps positions") + # Pack: three blocks in a row with big gaps, one below. + var rects := [Rect2(0, 0, 100, 100), Rect2(1000, 0, 100, 50), Rect2(3000, 20, 100, 100), Rect2(2000, 900, 100, 100)] + var off := BoardLayout.pack(rects, 60.0, 60.0) + var moved: Array = [] + for i in rects.size(): + moved.append(Rect2((rects[i] as Rect2).position + off[i], (rects[i] as Rect2).size)) + _check(moved[1].position.x == 160.0 and moved[2].position.x == 320.0, "pack closes the gaps along a row: %s" % str(moved)) + _check(moved[2].position.y == 20.0, "keeping each block's height in its row") + _check(moved[3].position == Vector2(0, 180), "the next row moves up and to the left edge: %s" % str(moved[3])) + _check(not _overlaps(moved), "nothing overlaps after packing") + # Make room: a block grows from 100x100 to 600x400 in place. + var room := [Rect2(160, 0, 100, 100), Rect2(0, 160, 100, 100), Rect2(2000, 0, 100, 100)] + var ro := BoardLayout.make_room(room, Rect2(0, 0, 100, 100), Rect2(0, 0, 600, 400), 60.0) + _check(ro[0] == Vector2(500, 0), "the block to the right moves right just enough: %s" % str(ro[0])) + _check(ro[1] == Vector2(0, 300), "the block below moves down just enough: %s" % str(ro[1])) + _check(ro[2] == Vector2(500, 0), "the rest of the row moves with it, keeping order") + + +func _test_lazy_cards() -> void: + _check(main.card_for("agent") == null and main.card_for("army") == null, "members of a collapsed group have no card") + _check(main.card_for("start") != null and main.card_for("pick") != null, "cards on show are built") + _check(main.cards.size() == 3, "only the three loose cards are built: %d" % main.cards.size()) + await process_frame + var paths: Dictionary = main.board.pipes._paths + var gn := main.group_node("careers") + var into: PackedVector2Array = paths.get("start:e1>agent", PackedVector2Array()) + _check(not into.is_empty() and into[into.size() - 1].distance_to(gn.inlet_point()) < 0.5, "a pipe into a hidden member still routes to its group") + var out: PackedVector2Array = paths.get("skill:e1>gems", PackedVector2Array()) + _check(out.is_empty(), "pipes inside one collapsed group aren't drawn") + main.toggle_group("careers") + await process_frame + _check(main.card_for("agent") != null and main.card_for("army") != null, "expanding the group builds its cards") + main.toggle_group("careers") + await process_frame + _check(main.card_for("agent") == null, "collapsing it again frees them") + # Fast roll through the hidden card still works and lights the group. + main.prompt_hook = func(_req: Dictionary) -> Variant: return 0 + main.start_roll("start", true) + for i in 10: + await process_frame + _check(main.current.get("done", false), "a roll through hidden members finishes") + var rev := main.board.geometry_rev + for i in 5: + await process_frame + _check(main.board.geometry_rev == rev, "nothing redraws while the board is idle") + main.board.world.position += Vector2(30, 10) + await process_frame + _check(main.board.geometry_rev == rev, "panning doesn't redraw the pipe, port or card layers") + + +func _test_search() -> void: + var s := BoardSearch.new(main.data) + var r := s.find("gem") + _check(not r.is_empty() and r[0]["table_id"] == "skill" and r[0]["field"] == BoardSearch.FIELD_NAME, "an exact name ranks first: %s" % str(r.slice(0, 3))) + _check(r.size() > 1 and r[1]["table_id"] == "gems", "then a name that starts with it") + var entry := _find(r, "agent", "e25") + _check(not entry.is_empty() and entry["field"] == BoardSearch.FIELD_RESULT, "entry text matches, BBCode stripped") + _check(not entry.is_empty() and str(entry["snippet"]).substr(entry["hl_from"], entry["hl_len"]) == "gem", "and the snippet marks the match: %s" % str(entry)) + _check(not entry.is_empty() and entry["group"] == "Careers" and entry["name"] == "Agent" and entry["kind"] == "Table", "results name the card, its kind and its group") + _check(not _find(r, "army", "").is_empty(), "details match too") + var acc := s.find("RARE") + _check(not acc.is_empty() and acc[0]["table_id"] == "agent" and acc[0]["entry_id"] == "e25", "matching ignores case and accents") + var v := s.find("endurance") + _check(v.size() >= 2 and v[0]["table_id"] == "end", "a variable card by name: %s" % str(v)) + var has_var := false + for x: Dictionary in v: + if x["field"] == BoardSearch.FIELD_VARIABLE: + has_var = true + _check(has_var, "and by its variable name") + var g := s.find("careers") + _check(not g.is_empty() and g[0]["group_id"] == "careers" and g[0]["kind"] == "Group", "group names match") + var p := s.find("career calls") + _check(not p.is_empty() and p[0]["table_id"] == "pick" and p[0]["field"] == BoardSearch.FIELD_PROMPT, "choice prompts match") + var words := s.find("posting gem") + _check(not words.is_empty() and words[0]["entry_id"] == "e25", "every word must match, in any order") + _check(s.find("zzzz").is_empty() and s.find(" ").is_empty(), "no match, no results") + + +func _find(results: Array, tid: String, eid: String) -> Dictionary: + for r: Dictionary in results: + if r["table_id"] == tid and (eid == "" or r["entry_id"] == eid): + return r + return {} + + +func _test_search_panel() -> void: + var p := main.open_search() + await process_frame + _check(p.visible and p.field.has_focus(), "Search opens with the field focused") + p.field.text = "posting" + p.refresh() + _check(p.results.size() > 1 and p.selected == 0, "results show as you type") + var ev := InputEventKey.new() + ev.keycode = KEY_DOWN + ev.pressed = true + p._on_field_input(ev) + _check(p.selected == 1, "Down picks the next result") + ev.keycode = KEY_ESCAPE + p._on_field_input(ev) + _check(not p.visible, "Esc closes it") + # Ctrl+F opens it again. + var cf := InputEventKey.new() + cf.keycode = KEY_F + cf.ctrl_pressed = true + cf.pressed = true + main._shortcut_input(cf) + _check(p.visible, "Ctrl+F opens search") + p.field.text = "Gemstones" + p.refresh() + ev.keycode = KEY_ENTER + p._on_field_input(ev) + _check(not p.visible, "Enter jumps and closes") + for i in 40: + await process_frame + _check(main.card_for("gems") != null and not main.data.get_group("skills").collapsed, "jumping to a hidden card opens its group") + + +func _test_focus() -> void: + var g := main.data.get_group("careers") + if not g.collapsed: + main.toggle_group("careers") + await process_frame + main.board.set_zoom(0.2) + main.focus_table("agent", "e25") + for i in 120: + await process_frame + if not main.board.is_animating() and i > 5: + break + var card := main.card_for("agent") + _check(not g.collapsed and main.data.to_dict()["groups"][0].get("collapsed", false) == false, "focus expands the collapsed group (saved)") + _check(main._toast.visible and main._toast_label.text.contains("Opened group Careers"), "and says so: %s" % main._toast_label.text) + _check(card != null, "the card is built") + if card == null: + return + var view := main.board.view_rect() + var r := Rect2(card.position, card.size) + _check(main.board.zoom >= Main.MIN_FOCUS_ZOOM, "the view zooms in to read it: %.2f" % main.board.zoom) + _check(view.encloses(Rect2(r.position, Vector2(r.size.x, minf(r.size.y, view.size.y - 20.0)))), "the card is in view: %s in %s" % [str(r), str(view)]) + _check(absf(view.get_center().x - r.get_center().x) < 2.0, "and centred") + _check(card.list_scroll != null and card.list_scroll.scroll_vertical > 0, "the long list scrolls to the result") + var a := card.anchor_for("e25") + _check(not a.is_empty() and a["visible"], "the result's row is in view") + _check(main.board.cards.is_flashing() and main.board.cards.flash_rect() == r, "a ring flashes around the card") + var row := main.board.cards.flash_row_rect() + _check(row.size.y > 0.0 and absf(row.get_center().y - (a["pos"] as Vector2).y) < 1.0, "and around the row: %s" % str(row)) + # The ring fades after about 1.5 s. + main.board.cards._process(2.0) + _check(not main.board.cards.is_flashing(), "the flash ends") + # A collapsed loose card opens when a result is asked for. + main.data.get_table("start").collapsed = true + main.card_for("start").rebuild() + main.focus_table("start", "e2") + for i in 6: + await process_frame + _check(not main.data.get_table("start").collapsed, "focus on a result expands a collapsed card") + main.focus_table("nope") + _check(true, "an unknown id does nothing") + + +func _test_minimap() -> void: + var mm := main.board.minimap + main.set_minimap_visible(true) + await process_frame + _check(mm.visible and main._map_toggle.button_pressed, "the minimap shows, and its toggle is on") + _check(mm.position.x + mm.size.x <= main.board.size.x and mm.position.y + mm.size.y <= main.board.size.y, "in the board's bottom-right corner") + mm.set_world(Rect2(-100, -100, 4000, 2000)) + var p := Vector2(1234, 567) + _check(mm.map_to_world(mm.world_to_map(p)).distance_to(p) < 0.01, "map and world coordinates round-trip") + main.board.set_zoom(0.5) + main.board.center_on(Vector2(1900, 900)) + var v := main.board.view_rect() + var vm := mm.view_rect_on_map() + _check(vm.position.distance_to(mm.world_to_map(v.position)) < 0.01 and absf(vm.size.x - v.size.x * mm._scale) < 0.01, "the view rect is the board's view, scaled") + var target := mm.world_to_map(Vector2(500, 300)) + mm.pan_to_map_point(target) + _check(main.board.view_rect().get_center().distance_to(Vector2(500, 300)) < 1.0, "clicking the map pans there") + var click := InputEventMouseButton.new() + click.button_index = MOUSE_BUTTON_LEFT + click.pressed = true + click.position = mm.world_to_map(Vector2(2500, 1000)) + mm._gui_input(click) + var drag := InputEventMouseMotion.new() + drag.position = mm.world_to_map(Vector2(2600, 1200)) + mm._gui_input(drag) + _check(main.board.view_rect().get_center().distance_to(Vector2(2600, 1200)) < 1.0, "dragging on it pans along") + click.pressed = false + mm._gui_input(click) + # M toggles it (not while typing). + var m := InputEventKey.new() + m.keycode = KEY_M + m.pressed = true + main._shortcut_input(m) + _check(not mm.visible, "M hides it") + main._shortcut_input(m) + _check(mm.visible, "M shows it again") + main.set_mode(Main.Mode.PLAY) + _check(not mm.visible, "it's off by default in Play") + main.set_mode(Main.Mode.BUILD) + main.set_mode(Main.Mode.PLAY) + await process_frame + + +func _test_pack() -> void: + main.set_mode(Main.Mode.BUILD) + var before := _blocks() + var bounds0 := main.board.content_bounds() + var moved: int = await main.pack_collapsed_groups() + var after := _blocks() + _check(moved > 0, "Pack moves blocks: %d" % moved) + _check(not _overlaps(after.values()), "nothing overlaps after Pack: %s" % str(after)) + _check(after["careers"].position.x < after["skills"].position.x and after["start"].position.x < after["careers"].position.x, + "reading order holds along the top row") + _check(after["end"].position.y > after["start"].position.y and after["pick"].position.x > after["end"].position.x, "and in the row below") + var bounds1 := main.board.content_bounds() + _check(bounds1.size.x < bounds0.size.x * 0.5 and bounds1.size.y < bounds0.size.y, "the board gets much smaller: %s -> %s" % [str(bounds0.size), str(bounds1.size)]) + var agent := main.data.get_table("agent") + _check(agent.position - main.data.get_group("careers").position == Vector2(22, 68), "members move with their group") + _check(main._toast.visible and main._toast_undo.visible, "with an undo toast") + main._undo() + await process_frame + var back := _blocks() + _check(back["skills"].position == before["skills"].position and back["start"].position == before["start"].position + and back["careers"].position == before["careers"].position, "undo puts everything back") + # Expanding a packed group makes room instead of overlapping. + await main.pack_collapsed_groups() + main.toggle_group("careers") + + for i in 3: + await process_frame + var grown := _blocks() + _check(not _overlaps(grown.values()), "expanding a packed group pushes its neighbours clear: %s" % str(grown)) + _check(grown["careers"].position.x < grown["skills"].position.x, "keeping their order") + _check(main._toast_label.text.contains("make room") and main._toast_undo.visible, "and says so, with undo: %s" % main._toast_label.text) + + +func _test_zoom_range() -> void: + await _load(_board_dict()) + main.board.set_zoom(0.01) + _check(is_equal_approx(main.board.zoom, BoardView.MIN_ZOOM) and BoardView.MIN_ZOOM <= 0.1, "zoom goes down to about 0.1") + main.board.fit() + _check(main.board.zoom < 0.35, "Fit can zoom below the old minimum for a wide board: %.2f" % main.board.zoom) + + +## Rects of the blocks Pack works on: groups (compact or frame) and loose cards. +func _blocks() -> Dictionary: + var out := {} + for b: Dictionary in main._layout_blocks(): + out[b["group"] if b["group"] != "" else b["table"]] = b["rect"] + return out + + +func _overlaps(rects: Array) -> bool: + for i in rects.size(): + for j in range(i + 1, rects.size()): + if (rects[i] as Rect2).intersects(rects[j]): + return true + return false + + +func _check(ok: bool, what: String) -> void: + if not ok: + _failures += 1 + print("FAIL ", what) diff --git a/tests/test_navigation.gd.uid b/tests/test_navigation.gd.uid new file mode 100644 index 0000000..9e7b45a --- /dev/null +++ b/tests/test_navigation.gd.uid @@ -0,0 +1 @@ +uid://dp0brwyw0twhr diff --git a/ui/board_layout.gd b/ui/board_layout.gd new file mode 100644 index 0000000..ddb5ba9 --- /dev/null +++ b/ui/board_layout.gd @@ -0,0 +1,107 @@ +class_name BoardLayout +extends RefCounted +## Pure layout helpers for whole blocks on the board (group frames, collapsed +## group cards, loose cards), given as world rects. Each returns one offset +## per rect, in the same order; Main moves the blocks. + + +## Closes the big gaps between blocks while keeping their order. +## +## Blocks whose rows overlap form a band (top to bottom); inside a band, +## blocks whose columns overlap form a column (left to right), which keeps its +## inner layout. Gaps wider than `gap_x` between columns shrink to `gap_x`, the +## first column of every band moves to the board's left edge, and gaps wider +## than `gap_y` between bands shrink to `gap_y`. The mapping only ever moves +## blocks left and up, in order, so nothing that didn't overlap before +## overlaps after, and reading order (left to right, top to bottom) holds. +static func pack(rects: Array, gap_x: float = 60.0, gap_y: float = 60.0) -> Array[Vector2]: + var out: Array[Vector2] = [] + out.resize(rects.size()) + for i in rects.size(): + out[i] = Vector2.ZERO + if rects.is_empty(): + return out + var left := INF + for r: Rect2 in rects: + left = minf(left, r.position.x) + var bands := _clusters(rects, range(rects.size()), false) + var y_cursor := 0.0 + for b in bands.size(): + var band: Dictionary = bands[b] + var new_top: float = band["lo"] + if b > 0: + var prev: Dictionary = bands[b - 1] + new_top = y_cursor + minf(float(band["lo"]) - float(prev["hi"]), gap_y) + var dy := new_top - float(band["lo"]) + y_cursor = float(band["hi"]) + dy + var cols := _clusters(rects, band["members"], true) + var x_cursor := left + for c in cols.size(): + var col: Dictionary = cols[c] + var new_left := left + if c > 0: + var pc: Dictionary = cols[c - 1] + new_left = x_cursor + minf(float(col["lo"]) - float(pc["hi"]), gap_x) + var dx := new_left - float(col["lo"]) + x_cursor = float(col["hi"]) + dx + for i: int in col["members"]: + out[i] = Vector2(dx, dy) + return out + + +## Groups indices whose rects overlap along one axis (x when `horizontal`) +## into clusters sorted along that axis: [{lo, hi, members}]. +static func _clusters(rects: Array, idx: Array, horizontal: bool) -> Array: + var order := idx.duplicate() + order.sort_custom(func(a: int, b: int) -> bool: + var ra: Rect2 = rects[a] + var rb: Rect2 = rects[b] + return (ra.position.x < rb.position.x) if horizontal else (ra.position.y < rb.position.y)) + var out: Array = [] + for i: int in order: + var r: Rect2 = rects[i] + var lo := r.position.x if horizontal else r.position.y + var hi := r.end.x if horizontal else r.end.y + if not out.is_empty() and lo < float(out[-1]["hi"]): + out[-1]["hi"] = maxf(float(out[-1]["hi"]), hi) + (out[-1]["members"] as Array).append(i) + else: + out.append({"lo": lo, "hi": hi, "members": [i]}) + return out + + +## Makes room for a block that grew from `compact` to `grown` (a group +## expanding in place; both share their top-left corner). Blocks to its right +## whose rows it now covers shift right together, and the blocks below it +## shift down together, each by just enough to clear it with `gap`. Blocks +## that already clear it don't move. Returns one offset per rect. +static func make_room(rects: Array, compact: Rect2, grown: Rect2, gap: float = 60.0) -> Array[Vector2]: + var out: Array[Vector2] = [] + out.resize(rects.size()) + for i in rects.size(): + out[i] = Vector2.ZERO + var right: Array[int] = [] + var below: Array[int] = [] + for i in rects.size(): + var r: Rect2 = rects[i] + if r.position.x >= compact.end.x - 1.0 and r.position.y < grown.end.y + gap and r.end.y > grown.position.y: + right.append(i) + elif r.position.y >= compact.end.y - 1.0: + below.append(i) + var dx := 0.0 + for i in right: + var r: Rect2 = rects[i] + if r.position.y < grown.end.y and r.end.y > grown.position.y: + dx = maxf(dx, grown.end.x + gap - r.position.x) + if dx > 0.0: + for i in right: + out[i].x = dx + var dy := 0.0 + for i in below: + var r: Rect2 = rects[i] + if r.position.x < grown.end.x + gap and r.end.x > grown.position.x - gap: + dy = maxf(dy, grown.end.y + gap - r.position.y) + if dy > 0.0: + for i in below: + out[i].y = dy + return out diff --git a/ui/board_layout.gd.uid b/ui/board_layout.gd.uid new file mode 100644 index 0000000..fe91d8f --- /dev/null +++ b/ui/board_layout.gd.uid @@ -0,0 +1 @@ +uid://rqspjt5qsd48 diff --git a/ui/board_search.gd b/ui/board_search.gd new file mode 100644 index 0000000..a379fe0 --- /dev/null +++ b/ui/board_search.gd @@ -0,0 +1,223 @@ +class_name BoardSearch +extends RefCounted +## Finds text on a board: table names, result text and details, choice +## prompts, variable names and effects, table details and group names. Text is +## matched as plain text (BBCode stripped with Formatter.strip_tags), +## case-insensitive and ignoring accents. Built once per board revision (the +## index), then queried as the player types. +## +## A result is a Dictionary: +## table_id, entry_id ("" for the card itself), group_id ("" unless the +## match is a group's name), field (FIELD_*), name (card or group name), +## kind (KIND label, e.g. "Table", "Choice", "Group"), group (the card's +## group name, or ""), snippet (one line of plain text around the match), +## hl_from / hl_len (the match inside snippet) and score. + +const FIELD_NAME := "name" +const FIELD_GROUP := "group" +const FIELD_VARIABLE := "variable" +const FIELD_PROMPT := "prompt" +const FIELD_RESULT := "result" +const FIELD_EFFECTS := "effects" +const FIELD_DETAILS := "details" + +## How much a match in each field counts, before the exact/prefix bonus. +const FIELD_WEIGHT := { + FIELD_NAME: 100, FIELD_GROUP: 90, FIELD_VARIABLE: 80, FIELD_PROMPT: 50, + FIELD_RESULT: 40, FIELD_EFFECTS: 30, FIELD_DETAILS: 20, +} +const KIND_LABELS := { + RollTable.KIND_ROLL: "Table", RollTable.KIND_CHOICE: "Choice", RollTable.KIND_LOOP: "Loop", + RollTable.KIND_VARIABLE: "Variable", RollTable.KIND_SHEET: "Sheet", +} +const SNIPPET_BEFORE := 28 +const SNIPPET_AFTER := 60 + +## Accented letters and the plain letter each folds to (one for one, so +## positions in the folded text are positions in the original). +const _ACCENTS := { + "a": "àáâãäåāăąǎ", "c": "çćĉċč", "d": "ďđ", "e": "èéêëēĕėęě", "g": "ĝğġģ", + "h": "ĥħ", "i": "ìíîïĩīĭįı", "j": "ĵ", "k": "ķ", "l": "ĺļľŀł", "n": "ñńņňʼn", + "o": "òóôõöøōŏőǒ", "r": "ŕŗř", "s": "śŝşšș", "t": "ţťŧț", "u": "ùúûüũūŭůűųǔ", + "w": "ŵ", "y": "ýÿŷ", "z": "źżž", +} +static var _fold_map: Dictionary = {} + +## [{table_id, entry_id, group_id, field, text, folded, order}] +var items: Array = [] +var _names: Dictionary = {} # table id -> plain name +var _kinds: Dictionary = {} # table id -> kind label +var _groups: Dictionary = {} # table id -> plain group name + + +func _init(board: TowerBoard = null) -> void: + if board: + build(board) + + +## Lower case, accents removed; the same length as `s`. +static func fold(s: String) -> String: + if _fold_map.is_empty(): + for plain: String in _ACCENTS: + var accented: String = _ACCENTS[plain] + for i in accented.length(): + _fold_map[accented[i]] = plain + var low := s.to_lower() + if low.length() != s.length(): + low = s # a lower-casing that changes the length; keep positions right + if low.to_utf8_buffer().size() == low.length(): + return low # plain ASCII + var parts := PackedStringArray() + for i in low.length(): + var ch := low[i] + parts.append(str(_fold_map.get(ch, ch))) + return "".join(parts) + + +## One-line plain text for an entry, detail or name. +static func plain(text: String) -> String: + if text == "": + return "" + var p := Formatter.strip_tags(text) if text.contains("[") else text + return p.replace("\n", " ").replace("\t", " ").strip_edges() + + +func build(board: TowerBoard) -> void: + items.clear() + _names.clear() + _kinds.clear() + _groups.clear() + for g in board.groups: + var gname := plain(g.name) + for tid in g.members: + _groups[tid] = gname + _add("", "", g.id, FIELD_GROUP, gname) + _add("", "", g.id, FIELD_DETAILS, plain(g.details)) + for t in board.tables: + _names[t.id] = plain(t.name) + _kinds[t.id] = str(KIND_LABELS.get(t.kind, "Table")) + _add(t.id, "", "", FIELD_NAME, _names[t.id]) + _add(t.id, "", "", FIELD_DETAILS, plain(t.details)) + if t.kind == RollTable.KIND_VARIABLE and t.var_name != "": + _add(t.id, "", "", FIELD_VARIABLE, "@" + t.var_name) + if t.kind == RollTable.KIND_CHOICE: + _add(t.id, "", "", FIELD_PROMPT, plain(t.prompt)) + if t.save_as != "": + _add(t.id, "", "", FIELD_VARIABLE, t.save_as) + for e in t.entries: + _add(t.id, e.id, "", FIELD_RESULT, plain(e.text)) + _add(t.id, e.id, "", FIELD_DETAILS, plain(e.details)) + if e.effects != "": + _add(t.id, e.id, "", FIELD_EFFECTS, plain(e.effects)) + for to: String in e.pipe_save: + var sv := str(e.pipe_save[to]) + if sv != "": + _add(t.id, e.id, "", FIELD_VARIABLE, sv) + + +func _add(tid: String, eid: String, gid: String, field: String, text: String) -> void: + if text == "": + return + items.append({"table_id": tid, "entry_id": eid, "group_id": gid, "field": field, + "text": text, "folded": fold(text), "order": items.size()}) + + +## The best matches for `query`, best first, at most `limit`. Every word of +## the query must appear in the one field; the whole query as typed ranks +## higher, and so do exact names and matches at the start of a word. +func find(query: String, limit: int = 50) -> Array[Dictionary]: + var out: Array[Dictionary] = [] + var q := fold(query.strip_edges()) + if q == "": + return out + var words := q.split(" ", false) + var scored: Array = [] + for it: Dictionary in items: + var f: String = it["folded"] + var at := f.find(q) + var hl_len := q.length() + var score := 0 + if at >= 0: + if f == q: + score = 1000 + elif at == 0: + score = 300 + elif _word_start(f, at): + score = 150 + else: + score = 0 + elif words.size() > 1: + var all := true + for w in words: + if not f.contains(w): + all = false + break + if not all: + continue + at = f.find(words[0]) + hl_len = words[0].length() + score = -10 + else: + continue + score += int(FIELD_WEIGHT.get(it["field"], 0)) + scored.append([score, f.length(), int(it["order"]), it, at, hl_len]) + scored.sort_custom(func(a: Array, b: Array) -> bool: + if a[0] != b[0]: + return a[0] > b[0] + if a[1] != b[1]: + return a[1] < b[1] + return a[2] < b[2]) + for i in mini(limit, scored.size()): + var s: Array = scored[i] + out.append(_result(s[3], int(s[4]), int(s[5]), int(s[0]))) + return out + + +## How many items match `query` in all (find() stops at its limit). +func count(query: String) -> int: + return find(query, 1 << 30).size() + + +static func _word_start(f: String, at: int) -> bool: + if at <= 0: + return true + var prev := f.unicode_at(at - 1) + return not ((prev >= 97 and prev <= 122) or (prev >= 48 and prev <= 57)) + + +func _result(it: Dictionary, at: int, hl_len: int, score: int) -> Dictionary: + var text: String = it["text"] + var from := maxi(0, at - SNIPPET_BEFORE) + var to := mini(text.length(), at + hl_len + SNIPPET_AFTER) + # Start and end at word breaks where that's close by. + if from > 0: + var sp := text.rfind(" ", from + 8) + if sp >= 0 and sp < at and sp > from - 12: + from = sp + 1 + var snippet := text.substr(from, to - from) + var hl_from := at - from + if from > 0: + snippet = "…" + snippet + hl_from += 1 + if to < text.length(): + snippet += "…" + var tid: String = it["table_id"] + var gid: String = it["group_id"] + var r := {"table_id": tid, "entry_id": it["entry_id"], "group_id": gid, "field": it["field"], + "snippet": snippet, "hl_from": hl_from, "hl_len": hl_len, "score": score} + if gid != "": + r["name"] = text if it["field"] == FIELD_GROUP else _group_name(gid) + r["kind"] = "Group" + r["group"] = "" + else: + r["name"] = str(_names.get(tid, tid)) + r["kind"] = str(_kinds.get(tid, "Table")) + r["group"] = str(_groups.get(tid, "")) + return r + + +func _group_name(gid: String) -> String: + for it: Dictionary in items: + if it["group_id"] == gid and it["field"] == FIELD_GROUP: + return it["text"] + return gid diff --git a/ui/board_search.gd.uid b/ui/board_search.gd.uid new file mode 100644 index 0000000..286328f --- /dev/null +++ b/ui/board_search.gd.uid @@ -0,0 +1 @@ +uid://cnwy07w5pvr58 diff --git a/ui/board_view.gd b/ui/board_view.gd index e0fe8ac..acd3adf 100644 --- a/ui/board_view.gd +++ b/ui/board_view.gd @@ -4,8 +4,12 @@ extends Control ## cards, the cards, and the ports (pipe ends) on top. Drag the felt to pan, ## Ctrl+wheel or pinch to zoom. -const MIN_ZOOM := 0.35 +## Low enough that Fit shows a whole board of several hundred cards. +const MIN_ZOOM := 0.08 const MAX_ZOOM := 1.5 +## Below this zoom text can't be read, so cards draw as plain cards (their +## contents aren't rendered) and group names show large (CardLayer). +const FAR_ZOOM := 0.22 const WORLD_SIZE := 40000.0 var main: Main @@ -16,6 +20,19 @@ var cards: CardLayer var ports: PortLayer var overlay: Control var zoom: float = 1.0 +## The overview in the bottom-right corner (hidden unless turned on). +var minimap: Minimap +## Bumped whenever something the layers draw from changes (see _signature): +## cards or groups moved, resized, rebuilt or scrolled, lit results, edits. +## The pipe, port and card layers redraw only when it changes. +var geometry_rev := 0 +var _sig_f := PackedFloat32Array() +var _sig_i := PackedInt64Array() +var _view_sig := PackedFloat32Array() +var _view_tween: Tween +var _settle := 0 + +var _culled_rev := -1 var _panning := false var _banding := false @@ -43,7 +60,9 @@ func setup(p_main: Main) -> void: pipes.main = main world.add_child(pipes) cards = CardLayer.new() + cards.main = main world.add_child(cards) + world.add_child(cards.overlay) ports = PortLayer.new() ports.main = main world.add_child(ports) @@ -53,6 +72,9 @@ func setup(p_main: Main) -> void: overlay.set_anchors_and_offsets_preset(PRESET_FULL_RECT) overlay.draw.connect(_draw_band) add_child(overlay) + minimap = Minimap.new() + minimap.setup(self) + add_child(minimap) var img := Image.create(6, 6, false, Image.FORMAT_RGBA8) img.fill(Color(0, 0, 0, 0)) @@ -71,6 +93,89 @@ func setup(p_main: Main) -> void: resized.connect(queue_redraw) +func _process(_delta: float) -> void: + if main == null or main.data == null: + return + _signature() + var v := PackedFloat32Array([world.position.x, world.position.y, zoom, size.x, size.y]) + if v != _view_sig or _culled_rev != geometry_rev: + var far := zoom < FAR_ZOOM + if far != cards.far or (far and (_view_sig.is_empty() or v[2] != _view_sig[2])): + cards.far = far + cards.overlay.queue_redraw() + _view_sig = v + _cull() + minimap.refresh() + + +## Stops rendering cards and group frames far outside the view (half a +## screen of margin), so a big expanded board only draws what's near, and far +## out (FAR_ZOOM) stops rendering their text (CardLayer sketches them). This +## is the renderer's own visibility, not `visible`: input, layout and the +## pipe geometry are untouched. Runs when the view or the geometry changed. +func _cull() -> void: + _culled_rev = geometry_rev + var view := view_rect() + view = view.grow(maxf(view.size.x, view.size.y) * 0.5) + for layer: Control in [cards, groups]: + for c in layer.get_children(): + var n := c as Control + if n == null or not n.visible: + continue + RenderingServer.canvas_item_set_visible(n.get_canvas_item(), view.intersects(Rect2(n.position, n.size).grow(40.0))) + var content := _content_of(n) + if content: + RenderingServer.canvas_item_set_visible(content.get_canvas_item(), content.visible and not cards.far) + + +## Collects what the layers draw from into two packed arrays and bumps +## geometry_rev when they differ from last frame. Hidden table cards don't +## exist (Main builds them lazily), so this walks only what's on the board. +func _signature() -> void: + var f := PackedFloat32Array() + var ids := PackedInt64Array([main.view_rev, main.mode]) + for layer: Control in [cards, groups]: + for c in layer.get_children(): + var n := c as Control + if n == null or not n.visible: + continue + f.append(n.position.x) + f.append(n.position.y) + f.append(n.size.x) + f.append(n.size.y) + ids.append(n.get_child(0).get_instance_id() if n.get_child_count() > 0 else 0) + var tc := n as TableCard + if tc and tc.list_scroll != null: + f.append(tc.list_scroll.scroll_vertical) + var changed := f != _sig_f or ids != _sig_i + if changed: + _sig_f = f + _sig_i = ids + # Containers inside a rebuilt card can settle a frame or two later + # without the card's own rect changing, so redraw a little longer. + _settle = 2 + elif _settle > 0: + _settle -= 1 + changed = true + if changed: + geometry_rev += 1 + cards.queue_redraw() + if cards.far: + cards.overlay.queue_redraw() + minimap.refresh() + + +## The part of a card or group card that holds its text (hidden far out). +func _content_of(n: Control) -> CanvasItem: + if n.get_child_count() == 0: + return null + var first := n.get_child(0) + var gc := n as GroupCard + if gc and gc.group and gc.group.collapsed: + return first.get_child(0) as CanvasItem if first.get_child_count() > 0 else null + return first as CanvasItem + + func _draw() -> void: var r := Rect2(Vector2.ZERO, size) draw_rect(r, Style.FELT) @@ -101,12 +206,54 @@ func fit() -> void: var bounds := content_bounds() if bounds.size == Vector2.ZERO: return + stop_animation() bounds = bounds.grow(20.0) zoom = clampf(minf(1.0, minf((size.x - 16.0) / bounds.size.x, (size.y - 16.0) / bounds.size.y)), MIN_ZOOM, MAX_ZOOM) world.scale = Vector2(zoom, zoom) world.position = Vector2(maxf(8.0, (size.x - bounds.size.x * zoom) / 2.0), 8.0) - bounds.position * zoom +## The part of the world the board shows right now. +func view_rect() -> Rect2: + return Rect2(screen_to_world(Vector2.ZERO), size / zoom) + + +## Pans so a world point sits in the middle of the board. +func center_on(p: Vector2) -> void: + stop_animation() + world.position = size / 2.0 - p * zoom + + +## Glides to `z` with the world point `p` in the middle (duration 0 jumps). +func animate_to(p: Vector2, z: float, duration: float = 0.3) -> void: + stop_animation() + z = clampf(snappedf(z, 0.01), MIN_ZOOM, MAX_ZOOM) + if duration <= 0.0 or not is_inside_tree(): + _apply_view(p, z) + return + var from_p := screen_to_world(size / 2.0) + var from_z := zoom + _view_tween = create_tween().set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT) + _view_tween.tween_method(func(t: float) -> void: + _apply_view(from_p.lerp(p, t), lerpf(from_z, z, t)), 0.0, 1.0, duration) + + +func is_animating() -> bool: + return _view_tween != null and _view_tween.is_valid() and _view_tween.is_running() + + +func stop_animation() -> void: + if _view_tween and _view_tween.is_valid(): + _view_tween.kill() + _view_tween = null + + +func _apply_view(p: Vector2, z: float) -> void: + zoom = z + world.scale = Vector2(zoom, zoom) + world.position = size / 2.0 - p * zoom + + ## The world rect of every visible card, group card and group frame (empty ## when there are none). func content_bounds() -> Rect2: @@ -145,6 +292,7 @@ func _gui_input(ev: InputEvent) -> void: return _press_at = mb.position _panning = true + stop_animation() mouse_default_cursor_shape = CURSOR_DRAG else: if _banding and mb.button_index == MOUSE_BUTTON_LEFT: diff --git a/ui/card_layer.gd b/ui/card_layer.gd index 13a039a..838a0c5 100644 --- a/ui/card_layer.gd +++ b/ui/card_layer.gd @@ -1,8 +1,29 @@ class_name CardLayer extends Control ## Holds the table cards and paints their hard drop shadow underneath them. +## Redraws only when the board's geometry changes (BoardView calls +## queue_redraw), not every frame. +## +## Far out (BoardView.FAR_ZOOM) the cards' contents aren't rendered; the +## overlay sketches each card's title line (brass when it holds a lit result) +## and writes group names large enough to read. +## +## It also owns the focus flash (Main.focus_table): a brass ring around a card +## and, optionally, around one of its rows, fading out over FLASH_TIME. The +## flash is drawn in `overlay`, a layer BoardView puts above the cards. +const FLASH_TIME := 1.5 + +## Drawn above the cards (BoardView adds it to the world after this layer). +var overlay: Control +var main: Main +## True while the board is zoomed out past BoardView.FAR_ZOOM. +var far := false var _shadow: StyleBoxFlat +var _ring: StyleBoxFlat +var _flash_node: Control = null +var _flash_row: Rect2 = Rect2() +var _flash_left := 0.0 func _init() -> void: @@ -10,10 +31,14 @@ func _init() -> void: # Controls only draw inside their own rect, so cover the whole world. size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) _shadow = Style.box(Color(0, 0, 0, 0.22), 10) - - -func _process(_delta: float) -> void: - queue_redraw() + _ring = Style.box(Color(0, 0, 0, 0), 14) + _ring.draw_center = false + Style.bordered(_ring, 4, Style.BRASS) + overlay = Control.new() + overlay.mouse_filter = MOUSE_FILTER_IGNORE + overlay.size = size + overlay.draw.connect(_draw_flash) + set_process(false) func _draw() -> void: @@ -21,3 +46,99 @@ func _draw() -> void: var card := c as Control if card and card.visible: draw_style_box(_shadow, Rect2(card.position + Vector2(0, 5), card.size)) + + +## Flashes a ring around `node` (a TableCard or GroupCard) for FLASH_TIME. +## `row` is a world rect inside it to ring as well (Rect2() for none). +func flash(node: Control, row: Rect2 = Rect2()) -> void: + _flash_node = node + _flash_row = row + _flash_left = FLASH_TIME + set_process(true) + overlay.queue_redraw() + + +func is_flashing() -> bool: + return _flash_left > 0.0 and is_instance_valid(_flash_node) + + +## The world rect of the flashed card, or Rect2() when nothing flashes. +func flash_rect() -> Rect2: + if not is_flashing(): + return Rect2() + return Rect2(_flash_node.position, _flash_node.size) + + +func flash_row_rect() -> Rect2: + return _flash_row if is_flashing() else Rect2() + + +func _process(delta: float) -> void: + _flash_left -= delta + overlay.queue_redraw() + if _flash_left <= 0.0: + _flash_node = null + set_process(false) + + +func _draw_flash() -> void: + if far: + _draw_far() + if not is_flashing(): + return + var t := clampf(_flash_left / FLASH_TIME, 0.0, 1.0) + # Two quick pulses, then a fade. + var pulse := 0.65 + 0.35 * cos((1.0 - t) * TAU * 2.0) + var a := minf(1.0, t * 2.5) * pulse + var r := Rect2(_flash_node.position, _flash_node.size).grow(8.0) + overlay.draw_style_box(_glow_box(a), r.grow(6.0)) + _ring.border_color = Color(Style.BRASS, a) + overlay.draw_style_box(_ring, r) + if _flash_row.size != Vector2.ZERO: + overlay.draw_rect(_flash_row, Color(Style.BRASS, 0.28 * a)) + overlay.draw_rect(_flash_row, Color(Style.BRASS_DARK, a), false, 2.5) + + +func _glow_box(a: float) -> StyleBoxFlat: + var g := Style.box(Color(0, 0, 0, 0), 20) + g.draw_center = false + Style.bordered(g, 8, Color(Style.BRASS, 0.25 * a)) + return g + + +## The far-out sketch: a title line per card, group names in large type. +func _draw_far() -> void: + if main == null or main.data == null: + return + var lit := {} + for k: String in main.lit_entries: + lit[k.substr(0, k.rfind(":"))] = true + var ink := Color(Style.INK, 0.45) + for c in get_children(): + var card := c as TableCard + if card == null or not card.visible or card.table == null: + continue + var p := card.position + var w := card.size.x + overlay.draw_rect(Rect2(p + Vector2(14, 16), Vector2(w * 0.6, 16)), ink) + if lit.has(card.table.id): + overlay.draw_rect(Rect2(p + Vector2(0, 46), Vector2(w, minf(40.0, card.size.y - 52.0))), Style.BRASS) + var z := main.board.zoom + var font := Style.display(true) + for g in main.data.groups: + var n := main.group_node(g.id) + if n == null: + continue + var r := Rect2(n.position, n.size) + var text := Formatter.strip_tags(g.name) + var fs := int(18.0 / z) + var tw := font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x + var room := maxf(r.size.x, 520.0) * 1.1 + if tw > room: + fs = maxi(8, int(fs * room / tw)) + tw = font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x + var at := Vector2(r.position.x + (r.size.x - tw) / 2.0, r.position.y + fs * 0.85) + if g.collapsed: + at.y = r.position.y + r.size.y / 2.0 + fs * 0.3 + overlay.draw_string_outline(font, at, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, maxi(2, int(4.0 / z)), Style.FELT_DEEP) + overlay.draw_string(font, at, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Style.ON_FELT if not g.collapsed else Style.BRASS) diff --git a/ui/main.gd b/ui/main.gd index 122640f..a222240 100644 --- a/ui/main.gd +++ b/ui/main.gd @@ -22,6 +22,10 @@ var lit_pipes: Dictionary = {} # "tid:eid>to" -> true var current: Dictionary = {} var history: Array = [] var rng := RandomNumberGenerator.new() +## Bumped by mark_dirty and _refresh_lit; BoardView redraws its layers when it changes. +var view_rev := 0 +## Bumped by mark_dirty: the search index is rebuilt when it changes. +var edit_rev := 0 var board: BoardView var tray: ResultTray @@ -214,12 +218,16 @@ func _build_top_bar() -> Control: _board_menu.import_requested.connect(import_collection) _board_menu.export_requested.connect(export_collection) tools.add_child(_board_menu) + tools.add_child(_make_arrange_menu()) tools.visible = false h.add_child(tools) _endless_chip = _make_endless_chip() h.add_child(_endless_chip) + _search_button = _make_search_button() + h.add_child(_search_button) + _collapse_all = Style.bar_button("Collapse all") _collapse_all.tooltip_text = "Collapse or expand every table at once" _collapse_all.pressed.connect(func() -> void: set_all_collapsed(_any_expanded())) @@ -240,6 +248,8 @@ func _build_top_bar() -> Control: zin.pressed.connect(func() -> void: board.set_zoom(board.zoom * 1.15)) for b in [zout, zfit, zin]: zoom.add_child(b) + _map_toggle = _make_map_toggle() + zoom.add_child(_map_toggle) h.add_child(zoom) return bar @@ -332,16 +342,14 @@ func is_entry_lit(tid: String, eid: String) -> bool: return lit_entries.has(Roller.entry_key(tid, eid)) +## Rebuilds every card. Cards hidden in collapsed groups aren't built at all +## (card_for gives null for them) until their group expands; see +## _apply_group_visibility. func _rebuild_cards() -> void: for c in board.cards.get_children(): board.cards.remove_child(c) c.queue_free() cards.clear() - for t in data.tables: - var card := TableCard.new() - board.cards.add_child(card) - card.setup(self, t) - cards[t.id] = card selection.clear() _rebuild_groups() _update_selection_bar() @@ -349,6 +357,7 @@ func _rebuild_cards() -> void: func _refresh_lit() -> void: + view_rev += 1 for card in cards.values(): (card as TableCard).refresh_lit() _refresh_group_lits() @@ -371,12 +380,15 @@ func set_mode(m: Mode) -> void: for n in _group_nodes.values(): (n as GroupCard).rebuild() _update_endless_chip() + _nav_mode_changed() func mark_dirty() -> void: if _saving_enabled: _save_timer.start() _ref_cache.clear() + view_rev += 1 + edit_rev += 1 _update_collapse_all() _update_endless_chip() if mode == Mode.BUILD: @@ -417,7 +429,9 @@ func set_all_collapsed(collapsed: bool) -> void: for t in data.tables: if t.collapsed != collapsed: t.collapsed = collapsed - card_for(t.id).rebuild() + var card := card_for(t.id) + if card: + card.rebuild() var changed := false for g in data.groups: if g.collapsed != collapsed: @@ -582,7 +596,8 @@ func delete_table(tid: String) -> void: selection.erase(tid) var card := card_for(tid) cards.erase(tid) - card.queue_free() + if card: + card.queue_free() for c in cards.values(): (c as TableCard).rebuild() if in_group: @@ -728,15 +743,34 @@ func _groups_changed() -> void: _update_collapse_all() +## Builds the cards that are on show and frees the ones hidden in collapsed +## groups, so a big board with most of it collapsed stays light. func _apply_group_visibility() -> void: _hidden_cache = null var hidden := hidden_groups() - for tid: String in cards: - var c: TableCard = cards[tid] - var hide := hidden.has(tid) - c.visible = not hide - if hide and selection.erase(tid): - c.set_selected(false) + var built := false + for t in data.tables: + var c: TableCard = cards.get(t.id) + if hidden.has(t.id): + if c: + selection.erase(t.id) + cards.erase(t.id) + # Hidden until it goes at the end of the frame (a deferred + # call of its own may still run). + c.hide() + c.queue_free() + elif c == null: + c = TableCard.new() + board.cards.add_child(c) + c.setup(self, t) + cards[t.id] = c + built = true + if built: + # Collapsed group cards stay on top of the table cards. + for g in data.groups: + var n := group_node(g.id) + if g.collapsed and n and n.get_parent() == board.cards: + board.cards.move_child(n, -1) _update_selection_bar() @@ -764,10 +798,21 @@ func toggle_group(gid: String) -> void: var g := data.get_group(gid) if g == null: return + var compact := Rect2() + var blocks: Array = [] + var n := group_node(gid) + if g.collapsed and n: + compact = Rect2(n.position, n.size) + blocks = _layout_blocks(gid) g.collapsed = not g.collapsed details().hide_for() _groups_changed() mark_dirty() + if not g.collapsed: + var room := _make_room_for(g, compact, blocks) + if int(room["moved"]) > 0: + toast("Opened %s and moved %d %s to make room" % [Formatter.strip_tags(g.name), room["moved"], + "block" if int(room["moved"]) == 1 else "blocks"], room["snap"]) func set_group_collapsed(gid: String, collapsed: bool) -> void: @@ -2018,7 +2063,7 @@ func _run_group_cli(args: PackedStringArray) -> void: # A card held over the first group's frame, to show the drop highlight. var g := data.groups[0] for t in data.tables: - if not g.has(t.id) and card_for(t.id).visible: + if not g.has(t.id) and card_for(t.id) and card_for(t.id).visible: var c := card_for(t.id) c.get_parent().move_child(c, -1) begin_card_drag(c) @@ -2373,6 +2418,9 @@ func _load_board_file(path: String) -> void: func _run_cli_extras(args: PackedStringArray) -> void: + if args.has("--perf"): + _run_perf() + _run_nav_cli(args) if args.has("--clear-result"): # Keeps the board lit but empties the tray (a tall sheet result can fill it). current = {} @@ -2404,3 +2452,456 @@ func _run_cli_extras(args: PackedStringArray) -> void: await get_tree().process_frame details().show_table(card, det) details().pin(card.get_global_rect().position + Vector2(60, 46)) + + +# ---------- Navigation: search, focus, minimap, pack, lazy cards ---------- + +## --perf: times a reload of the current board and the frame cost while idle +## and while panning (vsync off), then prints the numbers and quits. +func _run_perf() -> void: + DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED) + Engine.max_fps = 0 + var text := data.to_json() + for i in 10: + await get_tree().process_frame + var t0 := Time.get_ticks_usec() + data.load_json(text) + var tj := Time.get_ticks_usec() + _rebuild_cards() + var t1 := Time.get_ticks_usec() + _seed_session() + var t2 := Time.get_ticks_usec() + await get_tree().process_frame + await get_tree().process_frame + var t3 := Time.get_ticks_usec() + board.fit() + print("PERF load: parse %.1f ms, rebuild_cards %.1f ms, seed %.1f ms, first two frames %.1f ms, total %.1f ms" % [ + (tj - t0) / 1000.0, (t1 - tj) / 1000.0, (t2 - t1) / 1000.0, (t3 - t2) / 1000.0, (t3 - t0) / 1000.0]) + print("PERF nodes: %d, table cards built: %d of %d" % [Performance.get_monitor(Performance.OBJECT_NODE_COUNT), cards.size(), data.tables.size()]) + for i in 30: + await get_tree().process_frame + print("PERF idle (fit view): %s" % await _perf_frames(240, Vector2.ZERO)) + board.set_zoom(0.6) + print("PERF pan (zoom 0.6): %s" % await _perf_frames(240, Vector2(-6, -2))) + board.set_zoom(1.0) + print("PERF idle (zoom 1): %s" % await _perf_frames(240, Vector2.ZERO)) + print("PERF pan (zoom 1): %s" % await _perf_frames(240, Vector2(-6, -2))) + if OS.get_cmdline_user_args().has("--perf-layers"): + board.fit() + print("PERF idle (fit view again): %s" % await _perf_frames(120, Vector2.ZERO)) + board.pipes.visible = false + print("PERF idle, no pipes: %s" % await _perf_frames(120, Vector2.ZERO)) + board.ports.visible = false + print("PERF idle, no pipes or ports: %s" % await _perf_frames(120, Vector2.ZERO)) + board.cards.visible = false + print("PERF idle, no cards either: %s" % await _perf_frames(120, Vector2.ZERO)) + board.set_process(false) + board.groups.set_process(false) + print("PERF idle, board and group processing off: %s" % await _perf_frames(120, Vector2.ZERO)) + get_tree().quit() + + +func _perf_frames(n: int, pan: Vector2) -> String: + var times: Array[float] = [] + var last := Time.get_ticks_usec() + for i in n: + if pan != Vector2.ZERO: + board.world.position += pan + await get_tree().process_frame + var now := Time.get_ticks_usec() + times.append((now - last) / 1000.0) + last = now + times.sort() + var total := 0.0 + for t in times: + total += t + return "mean %.2f ms, median %.2f ms, p95 %.2f ms" % [total / n, times[n / 2], times[int(n * 0.95)]] + + +# ----- Search (top bar, Ctrl+F) ----- + +var _search_button: Button +var _search_panel: SearchPanel +var _map_toggle: Button + +## focus_table zooms in to at least this, so the card can be read. +const READABLE_ZOOM := 0.85 +## ...but zooms out as far as this to fit a tall card. +const MIN_FOCUS_ZOOM := 0.7 + + +func _make_search_button() -> Button: + var b := Style.bar_button("Search") + b.tooltip_text = "Find a card by its name, results, prompt, variables or group (Ctrl+F)" + _bar_icon(b, func(c: Control) -> void: + c.draw_arc(Vector2(6.5, 6.5), 5.0, 0.0, TAU, 24, Style.ON_FELT, 1.8, true) + c.draw_line(Vector2(10.3, 10.3), Vector2(14.5, 14.5), Style.ON_FELT, 2.4, true)) + b.pressed.connect(toggle_search) + return b + + +## Puts a 16 px drawn icon at the left of a top-bar button. +func _bar_icon(b: Button, paint: Callable) -> void: + for n in ["normal", "hover", "pressed", "hover_pressed", "disabled"]: + var sb := b.get_theme_stylebox(n) as StyleBoxFlat + if sb: + sb.content_margin_left = 32 + var icon := Control.new() + icon.mouse_filter = MOUSE_FILTER_IGNORE + icon.size = Vector2(16, 16) + icon.draw.connect(paint.bind(icon)) + b.add_child(icon) + b.resized.connect(func() -> void: icon.position = Vector2(11, roundf((b.size.y - 16.0) / 2.0))) + + +func toggle_search() -> void: + if _search_panel and _search_panel.visible: + _search_panel.close() + else: + open_search() + + +## Opens the search pop-over (Ctrl+F), with its field focused. +func open_search() -> SearchPanel: + if _search_panel == null: + _search_panel = SearchPanel.new() + add_child(_search_panel) + _search_panel.setup(self) + _search_panel.open(_search_button) + return _search_panel + + +func _shortcut_input(ev: InputEvent) -> void: + var k := ev as InputEventKey + if k == null or not k.pressed or k.echo: + return + if k.keycode == KEY_F and (k.ctrl_pressed or k.meta_pressed) and not k.alt_pressed: + open_search() + get_viewport().set_input_as_handled() + elif k.keycode == KEY_M and not (k.ctrl_pressed or k.meta_pressed or k.alt_pressed or k.shift_pressed): + var f := get_viewport().gui_get_focus_owner() + if f is LineEdit or f is TextEdit: + return + set_minimap_visible(not board.minimap.visible, true) + get_viewport().set_input_as_handled() + + +# ----- Focus: jump to a card ----- + +## Shows a card: expands its group if that's collapsed (saved, with a toast), +## expands the card if it's collapsed and an entry was asked for, glides the +## view so the card sits in the middle at a readable zoom and flashes a ring +## around it. With `entry_id`, a long list scrolls to that result +## (TableCard.reveal) and its row flashes too. Unknown ids do nothing. +func focus_table(table_id: String, entry_id: String = "") -> void: + var t := data.get_table(table_id) + if t == null: + return + if entry_id != "" and t.find_entry(entry_id) == null: + entry_id = "" + var notes := PackedStringArray() + var snap := "" + var settle := false + var g := data.group_of(table_id) + if g and g.collapsed: + var info := _expand_group(g) + notes.append("Opened group %s" % Formatter.strip_tags(g.name)) + if int(info["moved"]) > 0: + notes.append("moved %d %s to make room" % [info["moved"], "block" if int(info["moved"]) == 1 else "blocks"]) + snap = info["snap"] + settle = true + if entry_id != "" and t.collapsed and t.kind != RollTable.KIND_VARIABLE and t.kind != RollTable.KIND_SHEET: + t.collapsed = false + var c0 := card_for(table_id) + if c0: + c0.rebuild() + mark_dirty() + settle = true + var card := card_for(table_id) + if card == null: + return + if settle or card.size.y <= 0.0: + # Let a card that was just built or expanded lay out before measuring it. + for i in 3: + await get_tree().process_frame + card = card_for(table_id) + if card == null: + return + # On top of any card it overlaps. + card.get_parent().move_child(card, -1) + if entry_id != "": + card.reveal(entry_id) + var r := Rect2(card.position, card.size) + board.animate_to(_focus_point(r), _focus_zoom(r)) + board.cards.flash(card) + if not notes.is_empty(): + toast(", ".join(notes), snap) + if entry_id != "": + # The list scrolls on the next layout pass; ring the row after it. + await get_tree().process_frame + if is_instance_valid(card): + board.cards.flash(card, entry_rect(card, entry_id)) + + +## Centres a group: its frame, or its compact card when collapsed (which +## isn't expanded), and flashes it. +func focus_group(gid: String) -> void: + var g := data.get_group(gid) + var n := group_node(gid) + if g == null or n == null: + return + if g.collapsed: + n.get_parent().move_child(n, -1) + var r := Rect2(n.position, n.size) + var z := _focus_zoom(r) if g.collapsed else clampf(_fit_zoom(r), BoardView.MIN_ZOOM, READABLE_ZOOM) + board.animate_to(r.get_center() if not g.collapsed or r.size.y * z < board.size.y else _focus_point(r), z) + board.cards.flash(n) + + +## The world rect of an entry's row on a card (anchor_for geometry), or Rect2(). +func entry_rect(card: TableCard, eid: String) -> Rect2: + var a := card.anchor_for(eid) + var row: Control = card.rows.get(eid) + if a.is_empty() or row == null: + return Rect2() + var p: Vector2 = a["pos"] + var h := row.size.y + return Rect2(card.position.x + 3.0, p.y - h / 2.0, card.size.x - 6.0, h) + + +func _fit_zoom(r: Rect2) -> float: + return minf((board.size.x - 80.0) / maxf(r.size.x, 1.0), (board.size.y - 80.0) / maxf(r.size.y, 1.0)) + + +func _focus_zoom(r: Rect2) -> float: + var z := maxf(board.zoom, READABLE_ZOOM) + return clampf(minf(z, maxf(MIN_FOCUS_ZOOM, _fit_zoom(r))), BoardView.MIN_ZOOM, BoardView.MAX_ZOOM) + + +## The middle of a card, or a point that keeps its top in view when it's +## taller than the board at the zoom focus_table picks. +func _focus_point(r: Rect2) -> Vector2: + var z := _focus_zoom(r) + var c := r.get_center() + if r.size.y > (board.size.y - 80.0) / z: + c.y = r.position.y - 40.0 / z + board.size.y / 2.0 / z + return c + + +## Expands a collapsed group (saved) and makes room for it. Returns +## _make_room_for's {moved, snap}. +func _expand_group(g: TableGroup) -> Dictionary: + var n := group_node(g.id) + var compact := Rect2(n.position, n.size) if n else Rect2() + var blocks := _layout_blocks(g.id) + g.collapsed = false + details().hide_for() + _groups_changed() + mark_dirty() + return _make_room_for(g, compact, blocks) + + +# ----- Minimap ----- + +func _make_map_toggle() -> Button: + var b := Style.bar_button("Map") + b.toggle_mode = true + b.tooltip_text = "Show an overview of the board in the corner (M)" + var on := Style.bordered(Style.box(Color(Style.BRASS, 0.16), 8, [12, 6, 12, 6]), 1, Style.BRASS) + b.add_theme_stylebox_override("pressed", on) + b.add_theme_stylebox_override("hover_pressed", on) + _bar_icon(b, func(c: Control) -> void: + c.draw_rect(Rect2(1, 2, 14, 12), Style.ON_FELT, false, 1.5) + c.draw_rect(Rect2(4, 5, 4, 3), Style.ON_FELT) + c.draw_rect(Rect2(9, 8, 3, 3), Style.BRASS)) + b.toggled.connect(func(pressed: bool) -> void: set_minimap_visible(pressed, true)) + _nav_mode_changed.call_deferred() + return b + + +## Shows or hides the minimap; `remember` saves the choice for this mode. +func set_minimap_visible(on: bool, remember: bool = false) -> void: + if board == null: + return + board.minimap.visible = on + if _map_toggle: + _map_toggle.set_pressed_no_signal(on) + if remember and state: + state.set_setting(_minimap_key(), on) + state.save() + + +func _minimap_key() -> String: + return "minimap_build" if mode == Mode.BUILD else "minimap_play" + + +## Off by default in Play (which stays simple), on by default in Build; +## either is remembered once toggled. +func _minimap_default() -> bool: + var dflt := mode == Mode.BUILD + return bool(state.get_setting(_minimap_key(), dflt)) if state else dflt + + +## set_mode calls this after switching. +func _nav_mode_changed() -> void: + set_minimap_visible(_minimap_default()) + + +# ----- Arrange: pack collapsed groups ----- + +const PACK_GAP := 60.0 +const ARRANGE_PACK := 0 + + +func _make_arrange_menu() -> MenuButton: + var mb := MenuButton.new() + mb.text = "Arrange ▾" + mb.tooltip_text = "Tidy the layout of the board" + mb.flat = false + var ref := Style.bar_button("") + for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]: + mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n)) + for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]: + mb.add_theme_color_override(c, ref.get_theme_color(c)) + mb.add_theme_font_size_override("font_size", 15) + mb.mouse_default_cursor_shape = CURSOR_POINTING_HAND + ref.free() + var pm := mb.get_popup() + ModalCard.style_popup(pm) + pm.add_item("Pack collapsed groups", ARRANGE_PACK) + pm.set_item_tooltip(0, "Move collapsed groups and the cards between them together, closing the gaps, in reading order") + pm.id_pressed.connect(func(id: int) -> void: + if id == ARRANGE_PACK: + pack_collapsed_groups()) + return mb + + +## The blocks Pack and make-room move: every group (its compact card when +## collapsed, its frame when expanded) and every card in no group, as +## [{rect, group, table}] with one of group / table set. `skip` is a group id +## to leave out. +func _layout_blocks(skip: String = "") -> Array: + var out: Array = [] + var grouped := {} + for g in data.groups: + for tid in g.members: + grouped[tid] = true + if g.id == skip: + continue + var r := g.rect() + if g.collapsed: + var n := group_node(g.id) + r = Rect2(n.position, n.size) if n else Rect2(g.position, Vector2(TableCard.WIDTH, 120)) + out.append({"rect": r, "group": g.id, "table": ""}) + for t in data.tables: + if grouped.has(t.id): + continue + var c := card_for(t.id) + var r := Rect2(c.position, c.size) if c else Rect2(t.position, Vector2(TableCard.WIDTH, 120)) + out.append({"rect": r, "group": "", "table": t.id}) + return out + + +func _move_block(b: Dictionary, delta: Vector2) -> void: + if delta == Vector2.ZERO: + return + if b["group"] != "": + move_group(str(b["group"]), delta) + else: + var t := data.get_table(str(b["table"])) + t.position += delta + var c := card_for(t.id) + if c: + c.position = t.position + + +## Build ▸ Arrange ▸ Pack collapsed groups: closes the gaps that collapsed +## blocks leave (BoardLayout.pack), keeping reading order, then fits the view. +## Saved, with undo. Returns how many blocks moved. +func pack_collapsed_groups() -> int: + var any := false + for g in data.groups: + if g.collapsed: + any = true + break + if not any: + toast("Collapse some groups first: Pack closes the gaps they leave") + return 0 + var blocks := _layout_blocks() + var rects: Array = [] + for b: Dictionary in blocks: + rects.append(b["rect"]) + var offsets := BoardLayout.pack(rects, PACK_GAP, PACK_GAP) + var snap := _snapshot() + var moved := 0 + for i in blocks.size(): + var d := offsets[i].round() + if d != Vector2.ZERO: + _move_block(blocks[i], d) + moved += 1 + if moved == 0: + toast("Already packed") + return 0 + mark_dirty() + toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], snap) + await get_tree().process_frame + await get_tree().process_frame + board.fit() + return moved + + +## After a group expands in place: if its frame now covers other blocks, they +## shift right or down to clear it (BoardLayout.make_room). `blocks` are the +## other blocks (_layout_blocks) measured before the group expanded, while +## every group card was laid out. Returns {moved, snap}, snap being the board +## before the move (for an undo toast). +func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary: + if compact.size == Vector2.ZERO or blocks.is_empty(): + return {"moved": 0, "snap": ""} + var grown := g.rect() + var rects: Array = [] + var hits := false + for b: Dictionary in blocks: + var r: Rect2 = b["rect"] + rects.append(r) + if r.intersects(grown): + hits = true + if not hits: + return {"moved": 0, "snap": ""} + var snap := _snapshot() + var offsets := BoardLayout.make_room(rects, compact, grown, PACK_GAP) + var moved := 0 + for i in blocks.size(): + var d := offsets[i].round() + if d != Vector2.ZERO: + _move_block(blocks[i], d) + moved += 1 + if moved > 0: + mark_dirty() + return {"moved": moved, "snap": snap} + + +# ----- Navigation screenshot flags ----- +# --search= open the search panel with that query +# --focus=
[:] jump to a card (and result) +# --minimap / --no-minimap show or hide the overview +# --pack Build ▸ Arrange ▸ Pack collapsed groups +# --perf print load and frame timings, then quit + +func _run_nav_cli(args: PackedStringArray) -> void: + if args.has("--minimap"): + set_minimap_visible(true) + if args.has("--no-minimap"): + set_minimap_visible(false) + if args.has("--pack"): + await pack_collapsed_groups() + var f := _arg_value(args, "--focus") + if f != "": + await get_tree().process_frame + focus_table(f.get_slice(":", 0), f.get_slice(":", 1) if f.contains(":") else "") + var q := _arg_value(args, "--search") + if q != "": + await get_tree().process_frame + var p := open_search() + p.field.text = q + p.refresh() diff --git a/ui/minimap.gd b/ui/minimap.gd new file mode 100644 index 0000000..807f1f1 --- /dev/null +++ b/ui/minimap.gd @@ -0,0 +1,164 @@ +class_name Minimap +extends Control +## A small overview of the whole board in the bottom-right corner: group +## frames and collapsed group cards as tinted blocks, cards as card-coloured +## rectangles (brass when they hold a lit result) and the part of the board +## in view as a rectangle. Click or drag on it to pan there. +## +## It only redraws when BoardView asks (the view moved, or the board's +## geometry changed), never every frame. The map's scale comes from the +## board's content, so it holds still while panning. + +const MAX_SIZE := Vector2(232, 160) +const MARGIN := 14.0 +const PAD := 8.0 + +var board: BoardView +var _bg: StyleBoxFlat +var _dragging := false +## World rect the map shows, and how it maps onto the map's inner rect. +var _world := Rect2() +var _scale := 1.0 +var _offset := Vector2.ZERO +var _rev := -1 + + +func setup(p_board: BoardView) -> void: + board = p_board + mouse_filter = MOUSE_FILTER_STOP + mouse_default_cursor_shape = CURSOR_POINTING_HAND + tooltip_text = "Overview: click or drag to move around (M)" + _bg = Style.bordered(Style.box(Color(Style.FELT_DEEP, 0.92), 10), 1, Color(1, 1, 1, 0.16)) + _bg.shadow_color = Color(0, 0, 0, 0.35) + _bg.shadow_size = 12 + _bg.shadow_offset = Vector2(0, 4) + visible = false + size = MAX_SIZE + board.resized.connect(place) + + +## Re-places and redraws the map (BoardView calls this when the view or the +## board's geometry changed). Does nothing while hidden. +func refresh() -> void: + if not visible: + return + place() + queue_redraw() + + +## Keeps the map in the board's bottom-right corner, sized to the content's shape. +func place() -> void: + if board == null: + return + _refresh_frame() + position = board.size - size - Vector2(MARGIN, MARGIN) + + +func _notification(what: int) -> void: + if what == NOTIFICATION_VISIBILITY_CHANGED and visible: + _rev = -1 + refresh() + + +## Recomputes the world rect and scale from the board's content (only when +## the board's geometry changed). +func _refresh_frame() -> void: + if _rev == board.geometry_rev and _world.size != Vector2.ZERO: + return + _rev = board.geometry_rev + var b := board.content_bounds() + if b.size == Vector2.ZERO: + b = Rect2(Vector2.ZERO, Vector2(1000, 700)) + b = b.grow(maxf(b.size.x, b.size.y) * 0.03 + 40.0) + set_world(b) + + +## Sets the world rect the map covers and resizes the map to its shape. +func set_world(b: Rect2) -> void: + _world = b + var inner := MAX_SIZE - Vector2(PAD, PAD) * 2.0 + _scale = minf(inner.x / b.size.x, inner.y / b.size.y) + var used := b.size * _scale + size = Vector2(maxf(used.x, 90.0), maxf(used.y, 60.0)) + Vector2(PAD, PAD) * 2.0 + _offset = (size - used) / 2.0 + + +func world_to_map(p: Vector2) -> Vector2: + return _offset + (p - _world.position) * _scale + + +func map_to_world(p: Vector2) -> Vector2: + return _world.position + (p - _offset) / _scale + + +## The board's view as a rect on the map (map coordinates). +func view_rect_on_map() -> Rect2: + var v := board.view_rect() + return Rect2(world_to_map(v.position), v.size * _scale) + + +func _draw() -> void: + if board == null or board.main == null or board.main.data == null: + return + var main := board.main + draw_style_box(_bg, Rect2(Vector2.ZERO, size)) + var inner := Rect2(Vector2(3, 3), size - Vector2(6, 6)) + # Expanded group frames first, then cards and collapsed groups on top. + for g in main.data.groups: + if not g.collapsed: + _block(g.rect(), Color(0, 0, 0, 0.28), Color(1, 1, 1, 0.18), inner) + var hidden := main.hidden_groups() + var lit_tables := {} + for k: String in main.lit_entries: + lit_tables[k.substr(0, k.rfind(":"))] = true + for t in main.data.tables: + if hidden.has(t.id): + continue + var c := main.card_for(t.id) + var r := Rect2(c.position, c.size) if c else Rect2(t.position, Vector2(TableCard.WIDTH, 120)) + var lit := lit_tables.has(t.id) + _block(r, Style.BRASS if lit else Color(Style.CARD, 0.85), Color(0, 0, 0, 0), inner) + for g in main.data.groups: + if g.collapsed: + var n := main.group_node(g.id) + var r := Rect2(n.position, n.size) if n else Rect2(g.position, Vector2(TableCard.WIDTH, 120)) + var lit := false + for tid in g.members: + if lit_tables.has(tid): + lit = true + break + _block(r, Style.BRASS if lit else Color("#cfc6ae"), Style.COPPER_DARK, inner) + var v := view_rect_on_map().intersection(inner) + if v.size.x > 0.0 and v.size.y > 0.0: + draw_rect(v, Color(Style.ON_FELT, 0.08)) + draw_rect(v, Style.ON_FELT, false, 1.5) + + +## One block on the map, at least 2 px so tiny cards still show. +func _block(r: Rect2, fill: Color, edge: Color, clip: Rect2) -> void: + var m := Rect2(world_to_map(r.position), (r.size * _scale).max(Vector2(2, 2))).intersection(clip) + if m.size.x <= 0.0 or m.size.y <= 0.0: + return + draw_rect(m, fill) + if edge.a > 0.0 and m.size.x > 4.0 and m.size.y > 4.0: + draw_rect(m, edge, false, 1.0) + + +func _gui_input(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb: + if mb.button_index == MOUSE_BUTTON_LEFT: + _dragging = mb.pressed + if mb.pressed: + pan_to_map_point(mb.position) + accept_event() + return + var mm := ev as InputEventMouseMotion + if mm and _dragging: + pan_to_map_point(mm.position) + accept_event() + + +## Centres the board's view on the world point under a map point. +func pan_to_map_point(p: Vector2) -> void: + board.center_on(map_to_world(p)) diff --git a/ui/minimap.gd.uid b/ui/minimap.gd.uid new file mode 100644 index 0000000..09678d0 --- /dev/null +++ b/ui/minimap.gd.uid @@ -0,0 +1 @@ +uid://bkbfg0jywu2u4 diff --git a/ui/pipe_layer.gd b/ui/pipe_layer.gd index 54d8828..e77b9cb 100644 --- a/ui/pipe_layer.gd +++ b/ui/pipe_layer.gd @@ -28,6 +28,15 @@ var _rerouted: Dictionary = {} ## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer. var group_ports: Dictionary = {} var _label_box: StyleBoxFlat +## What the last redraw was drawn from (see _process). +var _drawn_state: Array = [] +## Unlit pipes each go in a canvas item of their own (see _batch_item), so the +## renderer skips the ones out of view; lit pipes, labels and the bead are +## drawn by _draw on top. A pool reused between redraws. +var _items: Array[RID] = [] +var _items_used := 0 +## Zoomed far out (BoardView.FAR_ZOOM): unlit pipes draw as one coarse line. +var _far := false func _init() -> void: @@ -38,8 +47,95 @@ func _init() -> void: Style.bordered(_label_box, 1, Style.COPPER_DARK) +## Redraws only when something it draws changed: the board's geometry +## (BoardView.geometry_rev: cards moved, resized, rebuilt or scrolled, lit +## results, edits), the hovered or selected pipe, or the travelling bead. func _process(_delta: float) -> void: - queue_redraw() + if main == null or main.board == null: + return + var state := [main.board.geometry_rev, hover_key, select_key, pulse_key, pulse_t, main.board.cards.far] + if state != _drawn_state: + _drawn_state = state + queue_redraw() + + +# ---------- Batched unlit pipes (performance) ---------- + +func _begin_batch() -> void: + _far = main.board.cards.far + for i in _items_used: + RenderingServer.canvas_item_clear(_items[i]) + _items_used = 0 + + +## The next free canvas item for one pipe: a child of this layer's item drawn +## behind it, so lit pipes and labels stay on top. Its bounds come from what's +## drawn in it, so the renderer culls it when the pipe is out of view. +func _batch_item() -> RID: + if _items_used == _items.size(): + var rid := RenderingServer.canvas_item_create() + RenderingServer.canvas_item_set_parent(rid, get_canvas_item()) + RenderingServer.canvas_item_set_draw_behind_parent(rid, true) + _items.append(rid) + _items_used += 1 + return _items[_items_used - 1] + + +func _line(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void: + RenderingServer.canvas_item_add_polyline(rid, pts, PackedColorArray([color]), width, true) + + +## Far out: one plain line through every fourth point. +func _coarse(rid: RID, pts: PackedVector2Array, color: Color, width: float) -> void: + var c := PackedVector2Array() + for i in range(0, pts.size(), 4): + c.append(pts[i]) + if (pts.size() - 1) % 4 != 0: + c.append(pts[pts.size() - 1]) + RenderingServer.canvas_item_add_polyline(rid, c, PackedColorArray([color]), width, false) + + +## An unlit pipe (as _draw_pipe draws it), in its own canvas item. +func _batch_pipe(pts: PackedVector2Array, hovered: bool) -> void: + var rid := _batch_item() + if _far: + _coarse(rid, pts, Style.COPPER, 10.0) + return + _line(rid, pts, Style.COPPER_DARK, 11.0) + _line(rid, pts, Style.COPPER.lightened(0.35) if hovered else Style.COPPER, 6.0) + RenderingServer.canvas_item_add_set_transform(rid, Transform2D(0.0, Vector2(0, -1.5))) + _line(rid, pts, Color(1.0, 0.886, 0.745, 0.4), 1.5) + RenderingServer.canvas_item_add_set_transform(rid, Transform2D.IDENTITY) + + +## An unlit pipe to or from a collapsed group (as _draw_bundle draws it). +func _batch_bundle(pts: PackedVector2Array) -> void: + var rid := _batch_item() + if _far: + _coarse(rid, pts, Color(Style.COPPER, 0.6), 6.0) + return + _line(rid, pts, Color(Style.COPPER_DARK, 0.55), 6.0) + _line(rid, pts, Color(Style.COPPER, 0.6), 3.0) + + +## An unlit reference pipe (as _draw_ref draws it). +func _batch_ref(pts: PackedVector2Array) -> void: + var rid := _batch_item() + if _far: + _coarse(rid, pts, Color(Style.COPPER, 0.7), 4.0) + return + var dashes := _dashes(pts, 12.0, 7.0) + for d in dashes: + _line(rid, d, Style.COPPER_DARK, 6.0) + for d in dashes: + _line(rid, d, Style.COPPER, 3.0) + + +func _notification(what: int) -> void: + if what == NOTIFICATION_PREDELETE: + for rid in _items: + RenderingServer.free_rid(rid) + _items.clear() static func curve(a: Vector2, b: Vector2) -> PackedVector2Array: @@ -53,6 +149,7 @@ static func curve(a: Vector2, b: Vector2) -> PackedVector2Array: func _draw() -> void: + _begin_batch() _paths.clear() _rerouted.clear() group_ports.clear() @@ -65,10 +162,12 @@ func _draw() -> void: # from the group card's right edge and arrive at its inlet. var hidden := main.hidden_groups() for t in main.data.tables: + # Tables hidden in a collapsed group have no card (Main builds them + # lazily); their pipes leave from the group card. var card := main.card_for(t.id) - if card == null: - continue var src_g: GroupCard = hidden.get(t.id) + if card == null and src_g == null: + continue for e in t.entries: var refs := main.ref_targets_for(e) if e.pipes.is_empty() and refs.is_empty(): @@ -84,9 +183,9 @@ func _draw() -> void: var is_ref := i < refs.size() var to: String = refs[i] if is_ref else e.pipes[i - refs.size()] var target := main.card_for(to) - if target == null: - continue var dst_g: GroupCard = hidden.get(to) + if target == null and dst_g == null: + continue if src_g != null and dst_g == src_g: continue # inside one collapsed group var key := Roller.ref_key(t.id, e.id, to) if is_ref else Roller.pipe_key(t.id, e.id, to) @@ -109,11 +208,11 @@ func _draw() -> void: continue drawn[dk] = true if is_ref: - _draw_ref(pts, false) + _batch_ref(pts) elif rerouted: - _draw_bundle(pts) + _batch_bundle(pts) else: - _draw_pipe(pts, false, build and (key == hover_key or key == select_key)) + _batch_pipe(pts, build and (key == hover_key or key == select_key)) if not is_ref and not rerouted: var tag := _pipe_tag(e, to) if tag != "": diff --git a/ui/port_layer.gd b/ui/port_layer.gd index ece9fc1..2559c7e 100644 --- a/ui/port_layer.gd +++ b/ui/port_layer.gd @@ -11,6 +11,10 @@ var _grab: Array = [] # [{pos, tid, eid}] outlets that can start a pipe var _linking := false var _ghost_from := Vector2.ZERO var _ghost_to := Vector2.ZERO +var _drawn_rev := -1 +var _drawn_hover := -1 +var _drawn_mode := -1 +var _drawn_far := false func _init() -> void: @@ -20,8 +24,30 @@ func _init() -> void: size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE) +## Redraws only when the board's geometry changed (BoardView.geometry_rev), +## the outlet under the mouse changed (Build), or while a pipe is being laid. func _process(_delta: float) -> void: - queue_redraw() + if main == null or main.board == null: + return + var hover := _hovered_grab() + var far := main.board.cards.far + if _linking or main.board.geometry_rev != _drawn_rev or hover != _drawn_hover or main.mode != _drawn_mode or far != _drawn_far: + _drawn_far = far + _drawn_rev = main.board.geometry_rev + _drawn_hover = hover + _drawn_mode = main.mode + queue_redraw() + + +## Index in _grab of the outlet under the mouse, or -1 (always -1 in Play). +func _hovered_grab() -> int: + if main.mode != Main.Mode.BUILD or _grab.is_empty(): + return -1 + var mouse := get_local_mouse_position() + for i in _grab.size(): + if mouse.distance_to(_grab[i]["pos"]) <= GRAB_RADIUS: + return i + return -1 func _has_point(p: Vector2) -> bool: @@ -37,6 +63,9 @@ func _has_point(p: Vector2) -> bool: func _draw() -> void: _grab.clear() + # Zoomed far out (BoardView.FAR_ZOOM) the ports would be specks. + if main.board.cards.far and not _linking: + return var build := main.mode == Main.Mode.BUILD var mouse := get_local_mouse_position() for t in main.data.tables: diff --git a/ui/search_panel.gd b/ui/search_panel.gd new file mode 100644 index 0000000..75e317d --- /dev/null +++ b/ui/search_panel.gd @@ -0,0 +1,284 @@ +class_name SearchPanel +extends PanelContainer +## The Search pop-over under the top bar's Search button (or Ctrl+F): a text +## field and a live list of matches (BoardSearch). Up/Down pick a result, +## Enter or a click jumps to it (Main.focus_table / focus_group), Esc or a +## click elsewhere closes it. + +const WIDTH := 460.0 +const LIST_HEIGHT := 400.0 +const SHOWN := 40 + +signal closed + +var main: Main +var field: LineEdit +## The matches shown, best first (BoardSearch results). +var results: Array[Dictionary] = [] +var selected := -1 + +var _search: BoardSearch +var _search_rev := -1 +var _anchor: Control +var _scroll: ScrollContainer +var _list: VBoxContainer +var _note: Label +var _rows: Array[PanelContainer] = [] +var _row_normal: StyleBoxFlat +var _row_hover: StyleBoxFlat +var _row_selected: StyleBoxFlat + + +func setup(p_main: Main) -> void: + main = p_main + visible = false + mouse_filter = MOUSE_FILTER_STOP + top_level = true + theme = Style.card_theme() + var sb := Style.box(Style.CARD, 10, [12, 12, 12, 10]) + sb.shadow_color = Color(0, 0, 0, 0.4) + sb.shadow_size = 18 + sb.shadow_offset = Vector2(0, 8) + add_theme_stylebox_override("panel", sb) + custom_minimum_size = Vector2(WIDTH, 0) + _row_normal = Style.box(Color(0, 0, 0, 0), 7, [10, 6, 10, 7]) + _row_hover = Style.box(Style.HOVER_ROW, 7, [10, 6, 10, 7]) + _row_selected = Style.bordered(Style.box(Style.LIT, 7, [10, 6, 10, 7]), 1, Color(Style.BRASS_DARK, 0.35)) + + var col := VBoxContainer.new() + col.add_theme_constant_override("separation", 8) + add_child(col) + field = LineEdit.new() + field.placeholder_text = "Search names, results, prompts, variables, groups…" + field.add_theme_font_override("font", Style.body()) + field.add_theme_font_size_override("font_size", 16) + field.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.RULE)) + field.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 2, Style.COPPER)) + field.clear_button_enabled = true + field.text_changed.connect(func(_t: String) -> void: refresh()) + field.gui_input.connect(_on_field_input) + col.add_child(field) + _note = Style.make_label("", Style.body_italic(), 14, Style.MUTED) + _note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + col.add_child(_note) + _scroll = ScrollContainer.new() + _scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + col.add_child(_scroll) + _list = VBoxContainer.new() + _list.add_theme_constant_override("separation", 2) + _list.size_flags_horizontal = SIZE_EXPAND_FILL + _scroll.add_child(_list) + + +## Opens under `anchor` (the Search button) with the field focused. +func open(anchor: Control = null) -> void: + _anchor = anchor + visible = true + _place() + field.grab_focus() + field.select_all() + refresh() + + +func close() -> void: + if not visible: + return + visible = false + if field.has_focus(): + field.release_focus() + closed.emit() + + +func _place() -> void: + reset_size() + var vp := get_viewport_rect().size + var x := vp.x - size.x - 12.0 + var y := 56.0 + if is_instance_valid(_anchor) and _anchor.is_inside_tree(): + var r := _anchor.get_global_rect() + x = r.end.x - size.x + y = r.end.y + 8.0 + position = Vector2(clampf(x, 8.0, maxf(8.0, vp.x - size.x - 8.0)), y) + + +## The index, rebuilt when the board was edited since it was made. +func index() -> BoardSearch: + if _search == null or _search_rev != main.edit_rev: + _search = BoardSearch.new(main.data) + _search_rev = main.edit_rev + return _search + + +## Re-runs the query and rebuilds the list. +func refresh() -> void: + for c in _list.get_children(): + _list.remove_child(c) + c.queue_free() + _rows.clear() + var q := field.text.strip_edges() + results = index().find(q, SHOWN + 1) if q != "" else ([] as Array[Dictionary]) + var more := results.size() > SHOWN + if more: + results.resize(SHOWN) + for i in results.size(): + _rows.append(_make_row(results[i], i)) + _list.add_child(_rows[i]) + if q == "": + _note.text = "Type to find a card by its name, results, details, prompt, variables or group." + elif results.is_empty(): + _note.text = "Nothing matches “%s”." % q + elif more: + _note.text = "The first %d matches. Keep typing to narrow them down." % SHOWN + else: + _note.text = "%d %s · ↑↓ to pick, Enter to jump" % [results.size(), "match" if results.size() == 1 else "matches"] + _scroll.custom_minimum_size.y = 0.0 if results.is_empty() else minf(LIST_HEIGHT, results.size() * 62.0) + selected = 0 if not results.is_empty() else -1 + _update_selected() + _place.call_deferred() + + +func _make_row(r: Dictionary, i: int) -> PanelContainer: + var row := PanelContainer.new() + row.add_theme_stylebox_override("panel", _row_normal) + row.mouse_filter = MOUSE_FILTER_STOP + row.mouse_default_cursor_shape = CURSOR_POINTING_HAND + var v := VBoxContainer.new() + v.add_theme_constant_override("separation", 1) + v.mouse_filter = MOUSE_FILTER_IGNORE + row.add_child(v) + var top := HBoxContainer.new() + top.add_theme_constant_override("separation", 8) + top.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(top) + var name_field: bool = r["field"] == BoardSearch.FIELD_NAME or r["field"] == BoardSearch.FIELD_GROUP + var title := _rich(highlight(r["snippet"], r["hl_from"], r["hl_len"]) if name_field else _esc(str(r["name"])), + Style.body_bold(), 16) + title.size_flags_horizontal = SIZE_EXPAND_FILL + top.add_child(title) + var kind := Style.make_label(str(r["kind"]).to_upper(), Style.caps(), 10, Style.COPPER_DARK) + kind.size_flags_vertical = SIZE_SHRINK_CENTER + kind.mouse_filter = MOUSE_FILTER_IGNORE + top.add_child(kind) + var where := PackedStringArray() + if str(r["group"]) != "": + where.append("in " + str(r["group"])) + if not name_field: + where.append(_field_label(str(r["field"]))) + if not where.is_empty(): + var sub := Style.make_label(" · ".join(where), Style.body(), 13, Style.MUTED) + sub.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS + sub.custom_minimum_size = Vector2(40, 0) + sub.mouse_filter = MOUSE_FILTER_IGNORE + v.add_child(sub) + if not name_field: + var snip := _rich(highlight(r["snippet"], r["hl_from"], r["hl_len"]), Style.body(), 14) + v.add_child(snip) + row.mouse_entered.connect(func() -> void: + if selected != i: + row.add_theme_stylebox_override("panel", _row_hover)) + row.mouse_exited.connect(func() -> void: _update_selected()) + row.gui_input.connect(func(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.pressed and mb.button_index == MOUSE_BUTTON_LEFT: + selected = i + activate() + row.accept_event()) + return row + + +static func _field_label(field: String) -> String: + match field: + BoardSearch.FIELD_RESULT: return "result" + BoardSearch.FIELD_DETAILS: return "details" + BoardSearch.FIELD_PROMPT: return "prompt" + BoardSearch.FIELD_VARIABLE: return "variable" + BoardSearch.FIELD_EFFECTS: return "effects" + return field + + +func _rich(bb: String, font: Font, fs: int) -> RichTextLabel: + var l := RichTextLabel.new() + l.bbcode_enabled = true + l.fit_content = true + l.scroll_active = false + l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART + l.mouse_filter = MOUSE_FILTER_IGNORE + l.add_theme_font_override("normal_font", font) + l.add_theme_font_override("bold_font", Style.body_bold()) + l.add_theme_font_size_override("normal_font_size", fs) + l.add_theme_font_size_override("bold_font_size", fs) + l.add_theme_color_override("default_color", Style.INK) + l.custom_minimum_size = Vector2(40, 0) + l.size_flags_horizontal = SIZE_EXPAND_FILL + l.text = bb + return l + + +static func _esc(s: String) -> String: + return s.replace("[", "[lb]") + + +## BBCode for plain `text` with [from, from + length) marked in brass. +static func highlight(text: String, from: int, length: int) -> String: + if from < 0 or length <= 0 or from >= text.length(): + return _esc(text) + return "%s[bgcolor=#%s][b]%s[/b][/bgcolor]%s" % [_esc(text.substr(0, from)), Style.BRASS.to_html(false), + _esc(text.substr(from, length)), _esc(text.substr(from + length))] + + +func _update_selected() -> void: + for i in _rows.size(): + _rows[i].add_theme_stylebox_override("panel", _row_selected if i == selected else _row_normal) + + +func move_selection(step: int) -> void: + if results.is_empty(): + return + selected = wrapi(selected + step, 0, results.size()) + _update_selected() + if selected < _rows.size(): + _scroll.ensure_control_visible(_rows[selected]) + + +## Jumps to the selected result and closes. +func activate() -> void: + if selected < 0 or selected >= results.size(): + return + var r := results[selected] + close() + if str(r["group_id"]) != "": + main.focus_group(str(r["group_id"])) + else: + main.focus_table(str(r["table_id"]), str(r["entry_id"])) + + +func _on_field_input(ev: InputEvent) -> void: + var k := ev as InputEventKey + if k == null or not k.pressed: + return + match k.keycode: + KEY_DOWN: + move_selection(1) + KEY_UP: + move_selection(-1) + KEY_ENTER, KEY_KP_ENTER: + activate() + KEY_ESCAPE: + close() + _: + return + field.accept_event() + + +func _input(ev: InputEvent) -> void: + if not visible: + return + var mb := ev as InputEventMouseButton + if mb and mb.pressed and not get_global_rect().has_point(mb.global_position): + # A click elsewhere closes it (the Search button toggles it itself). + if not (is_instance_valid(_anchor) and _anchor.get_global_rect().has_point(mb.global_position)): + close() + var k := ev as InputEventKey + if k and k.pressed and k.keycode == KEY_ESCAPE: + close() + get_viewport().set_input_as_handled() diff --git a/ui/search_panel.gd.uid b/ui/search_panel.gd.uid new file mode 100644 index 0000000..ac7656a --- /dev/null +++ b/ui/search_panel.gd.uid @@ -0,0 +1 @@ +uid://b2pvp72n3d4al