@ringozz/godot 4.7.1-8 → 4.7.2-570

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/debug.ts CHANGED
@@ -1,236 +1,354 @@
1
- /**********************************************************************
2
- Copyright (c) Vladimir Davidovich. All rights reserved.
3
- ***********************************************************************/
4
-
5
- import { Rect2, str, varToStr, Vector3 } from './index.ts';
6
- import { CanvasItem } from '../gen/classes/CanvasItem.ts';
7
- import { ClassDB } from '../gen/classes/ClassDB.ts';
8
- import { Control } from '../gen/classes/Control.ts';
9
- import { DisplayServer } from '../gen/classes/DisplayServer.ts';
10
- import { Engine } from '../gen/classes/Engine.ts';
11
- import { Node } from '../gen/classes/Node.ts';
12
- import { Node3D } from '../gen/classes/Node3D.ts';
13
- import { OS } from '../gen/classes/OS.ts';
14
- import { Time } from '../gen/classes/Time.ts';
15
-
16
- /**
17
- * Dump a Godot value or object as a string.
18
- * Value types (vectors, arrays, dictionaries, …) render via Godot's `str()`.
19
- * Objects dump via Godot's `var_to_str` — its own property walk + recursion —
20
- * with the node's `name` prepended when present.
21
- *
22
- * @param obj - Any Godot wrapper (Node, Resource, …), value type, or plain value
23
- */
24
- export function dumpStr(obj: unknown): string {
25
- if (obj == null || typeof obj !== 'object') return String(obj);
26
-
27
- // Value types & heap containers (Vector3, Array, Dictionary, …) have no getClass() —
28
- // let Godot's str() render them.
29
- if (!(obj as any).getClass) return str(obj as any);
30
-
31
- const dump = varToStr(obj as any);
32
- let name: unknown;
33
- try { name = (obj as any).name; } catch { name = undefined; }
34
- return name === undefined || name === null || name === '' ? dump : `${name}: ${dump}`;
35
- }
36
-
37
- /**
38
- * Serialize a scene subtree as a tree-formatted string.
39
- *
40
- * @param node - Root node to start from
41
- * @param depth - Max depth (default 99)
42
- */
43
- export function dumpTreeStr(node: Node, depth = 99): string {
44
- const lines: string[] = [];
45
- (function walk(n: Node, d: number, ind: string) {
46
- if (d <= 0) return;
47
- lines.push(`${ind}${n.getClass()} "${n.name}" (${n.getChildCount()} children)`);
48
- for (let i = 0; i < n.getChildCount(); i++) {
49
- const c = n.getChild(i);
50
- if (c) walk(c as Node, d - 1, ind + ' ');
51
- }
52
- })(node, depth, '');
53
- return lines.join('\n');
54
- }
55
-
56
- /**
57
- * Return a snapshot of engine runtime stats as a formatted string.
58
- *
59
- * Includes process frames, FPS, physics frames, node count, time scale,
60
- * and main-loop class. Never throws: `Engine.getMainLoop()` can be null or
61
- * throw while the engine is starting/stopping, in which case those rows show `N/A`.
62
- */
63
- export function statsStr(): string {
64
- let tree: any = null;
65
- try { tree = Engine.getMainLoop(); } catch { tree = null; }
66
- return [
67
- `Frames: ${Engine.getProcessFrames()}`,
68
- `FPS: ${Engine.getFramesPerSecond()}`,
69
- `Physics: ${Engine.getPhysicsFrames()}`,
70
- `Nodes: ${tree?.getNodeCount?.() ?? 'N/A'}`,
71
- `Time scale: ${Engine.timeScale}`,
72
- `Main loop: ${tree ? tree.getClass() : 'N/A'}`,
73
- ].join('\n');
74
- }
75
-
76
- /**
77
- * Run `gc()` and report how much heap was freed.
78
- * Requires the `--expose-gc` Node.js flag.
79
- */
80
- export function gc(): string {
81
- const before = globalThis.process?.memoryUsage?.().heapUsed;
82
- if (globalThis.Bun)
83
- globalThis.Bun.gc(true);
84
- else if (globalThis.gc)
85
- globalThis.gc({ type: 'major', execution: 'sync' });
86
- else
87
- return 'gc() unavailable — need --expose-gc';
88
-
89
- const after = globalThis.process?.memoryUsage?.().heapUsed;
90
- const freed = typeof before === 'number' && typeof after === 'number' ? (before - after) / 1024 : 0;
91
- return `GC: freed ${freed.toFixed(0)} KB`;
92
- }
93
-
94
- /**
95
- * `DOMRect` is not a global in Bun (desktop), but `getBoundingClientRect()`
96
- * constructs one. Install a minimal spec-compatible polyfill on desktop so the
97
- * helper works identically on desktop and web (browsers already define it).
98
- */
99
- function ensureDOMRect(): void {
100
- if (typeof (globalThis as any).DOMRect !== 'undefined') return;
101
- (globalThis as any).DOMRect = class DOMRect {
102
- x: number;
103
- y: number;
104
- width: number;
105
- height: number;
106
- constructor(x = 0, y = 0, width = 0, height = 0) {
107
- this.x = x;
108
- this.y = y;
109
- this.width = width;
110
- this.height = height;
111
- }
112
- get left() { return this.x; }
113
- get top() { return this.y; }
114
- get right() { return this.x + this.width; }
115
- get bottom() { return this.y + this.height; }
116
- toJSON() { return { x: this.x, y: this.y, width: this.width, height: this.height }; }
117
- };
118
- }
119
-
120
- /**
121
- * Bootstrap the debugging environment.
122
- *
123
- * - Exposes common singletons (`Engine`, `OS`, `ClassDB`, `Time`) and all
124
- * debug utility functions on `globalThis.$` so they're reachable from
125
- * breakpoints in any module.
126
- * - Registers an `uncaughtException` handler that logs but keeps the process
127
- * alive for interactive debugging.
128
- * - Polyfills `DOMRect` (needed by `getBoundingClientRect()` on desktop).
129
- */
130
- export function initDebug(): void {
131
- globalThis.process?.on?.('uncaughtException', (err, origin) => {
132
- console.error(`\n✗ ${origin}:`, err.stack);
133
- });
134
-
135
- ensureDOMRect();
136
-
137
- Object.defineProperty(CanvasItem.prototype, 'getBoundingClientRect', {
138
- configurable: true,
139
- value(this: CanvasItem): DOMRect | null {
140
- const scale = DisplayServer.screenGetScale();
141
- if (this instanceof Control) {
142
- const rc = (this as Control).getGlobalRect();
143
- return new DOMRect(
144
- rc.position.x / scale, rc.position.y / scale,
145
- rc.size.x / scale, rc.size.y / scale,
146
- );
147
- }
148
-
149
- if (typeof (this as any).getRect !== 'function') return null;
150
-
151
- const rect = (this as any).getRect() as Rect2;
152
- const t = this.getScreenTransform();
153
-
154
- const pos = rect.position;
155
- const sz = rect.size;
156
- const tx = t.x;
157
- const ty = t.y;
158
- const to = t.origin;
159
-
160
- const x0 = pos.x, y0 = pos.y;
161
- const x1 = x0 + sz.x, y1 = y0 + sz.y;
162
- const txx = tx.x, txy = tx.y;
163
- const tyx = ty.x, tyy = ty.y;
164
- const tox = to.x, toy = to.y;
165
-
166
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
167
- const accum = (px: number, py: number) => {
168
- if (px < minX) minX = px; if (py < minY) minY = py;
169
- if (px > maxX) maxX = px; if (py > maxY) maxY = py;
170
- };
171
-
172
- accum(txx * x0 + tyx * y0 + tox, txy * x0 + tyy * y0 + toy);
173
- accum(txx * x1 + tyx * y0 + tox, txy * x1 + tyy * y0 + toy);
174
- accum(txx * x0 + tyx * y1 + tox, txy * x0 + tyy * y1 + toy);
175
- accum(txx * x1 + tyx * y1 + tox, txy * x1 + tyy * y1 + toy);
176
-
177
- return new DOMRect(
178
- minX / scale, minY / scale,
179
- (maxX - minX) / scale, (maxY - minY) / scale,
180
- );
181
- },
182
- });
183
-
184
- Object.defineProperty(Node3D.prototype, 'getBoundingClientRect', {
185
- configurable: true,
186
- value(this: Node3D): DOMRect | null {
187
- if (typeof (this as any).getAabb !== 'function') return null;
188
-
189
- const aabb = (this as any).getAabb();
190
- const gt = this.globalTransform;
191
- const viewport = this.getViewport();
192
- if (!viewport) return null;
193
- const camera = viewport.getCamera3d();
194
- if (!camera) return null;
195
- const scale = DisplayServer.screenGetScale();
196
-
197
- const b = gt.basis;
198
- const bx = b.x, by = b.y, bz = b.z;
199
- const o = gt.origin;
200
- const p = aabb.position, e = aabb.end;
201
-
202
- const [px, py, pz] = [p.x, p.y, p.z];
203
- const [ex, ey, ez] = [e.x, e.y, e.z];
204
- const [bxx, bxy, bxz] = [bx.x, bx.y, bx.z];
205
- const [byx, byy, byz] = [by.x, by.y, by.z];
206
- const [bzx, bzy, bzz] = [bz.x, bz.y, bz.z];
207
- const [ox, oy, oz] = [o.x, o.y, o.z];
208
-
209
- const corners = [
210
- [px, py, pz], [ex, py, pz], [px, ey, pz], [ex, ey, pz],
211
- [px, py, ez], [ex, py, ez], [px, ey, ez], [ex, ey, ez],
212
- ];
213
-
214
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
215
-
216
- for (const [cx, cy, cz] of corners) {
217
- const wx = bxx * cx + byx * cy + bzx * cz + ox;
218
- const wy = bxy * cx + byy * cy + bzy * cz + oy;
219
- const wz = bxz * cx + byz * cy + bzz * cz + oz;
220
- const s = camera.unprojectPosition(new Vector3(wx, wy, wz));
221
- if (s.x < minX) minX = s.x; if (s.y < minY) minY = s.y;
222
- if (s.x > maxX) maxX = s.x; if (s.y > maxY) maxY = s.y;
223
- }
224
-
225
- return new DOMRect(
226
- minX / scale, minY / scale,
227
- (maxX - minX) / scale, (maxY - minY) / scale,
228
- );
229
- },
230
- });
231
-
232
- (globalThis as any).$ = {
233
- Engine, OS, ClassDB, Time,
234
- dumpStr, dumpTreeStr, statsStr, gc,
235
- };
236
- }
1
+ /**********************************************************************
2
+ Copyright (c) Vladimir Davidovich. All rights reserved.
3
+ ***********************************************************************/
4
+
5
+ import { MouseButton, Rect2, str, varToStr, Vector2, Vector3 } from './index.ts';
6
+ import { CanvasItem } from '../gen/classes/CanvasItem.ts';
7
+ import { ClassDB } from '../gen/classes/ClassDB.ts';
8
+ import { Control } from '../gen/classes/Control.ts';
9
+ import { DisplayServer } from '../gen/classes/DisplayServer.ts';
10
+ import { Engine } from '../gen/classes/Engine.ts';
11
+ import { InputEventMouseButton } from '../gen/classes/InputEventMouseButton.ts';
12
+ import { Node } from '../gen/classes/Node.ts';
13
+ import { Node3D } from '../gen/classes/Node3D.ts';
14
+ import { OS } from '../gen/classes/OS.ts';
15
+ import { SceneTree } from '../gen/classes/SceneTree.ts';
16
+ import { Time } from '../gen/classes/Time.ts';
17
+ import type { Viewport } from '../gen/classes/Viewport.ts';
18
+ import type { Window } from '../gen/classes/Window.ts';
19
+
20
+ const tree = Engine.getMainLoop() as SceneTree;
21
+
22
+ /** Does a snapshot line match a string (case-insensitive substring) or `RegExp` pattern? */
23
+ function matches(pattern: string | RegExp | undefined, line: string): boolean {
24
+ return !pattern || (pattern instanceof RegExp ? pattern.test(line) : line.toLowerCase().includes(pattern.toLowerCase()));
25
+ }
26
+
27
+ /**
28
+ * Dump a Godot value or object as a string.
29
+ * Value types (vectors, arrays, dictionaries, …) render via Godot's `str()`.
30
+ * Objects dump via Godot's `var_to_str` — its own property walk + recursion —
31
+ * with the node's `name` prepended when present.
32
+ *
33
+ * @param obj - Any Godot wrapper (Node, Resource, …), value type, or plain value
34
+ */
35
+ export function dumpStr(obj: unknown): string {
36
+ if (obj == null || typeof obj !== 'object') return String(obj);
37
+
38
+ // Value types & heap containers (Vector3, Array, Dictionary, …) have no getClass() —
39
+ // let Godot's str() render them.
40
+ if (!(obj as any).getClass) return str(obj as any);
41
+
42
+ const dump = varToStr(obj as any);
43
+ let name: unknown;
44
+ try { name = (obj as any).name; } catch { name = undefined; }
45
+ return name === undefined || name === null || name === '' ? dump : `${name}: ${dump}`;
46
+ }
47
+
48
+ /**
49
+ * Serialize a scene subtree as a tree-formatted string, optionally filtered.
50
+ *
51
+ * Emits one line per node: `Class "name" (N children)`. When `pattern` is a
52
+ * string, only lines containing it (case-insensitive) are kept; a `RegExp`
53
+ * matches against the full line.
54
+ *
55
+ * @param pattern - Optional substring or `RegExp` to filter the lines
56
+ * @param node - Root node to start from (defaults to the scene tree's root Window)
57
+ * @param depth - Max depth (default 99)
58
+ */
59
+ export function snapshot(pattern?: string | RegExp, node?: Node, depth = 99): string {
60
+ const root = node ?? tree.root;
61
+ const lines: string[] = [];
62
+ (function walk(n: Node, d: number, ind: string) {
63
+ if (d <= 0) return;
64
+ const count = n.getChildCount();
65
+ const line = `${ind}${n.getClass()} "${n.name}" (${count} children)`;
66
+ if (matches(pattern, line)) lines.push(line);
67
+ for (let i = 0; i < count; i++) {
68
+ const c = n.getChild(i);
69
+ if (c) walk(c as Node, d - 1, ind + ' ');
70
+ }
71
+ })(root, depth, '');
72
+ return lines.join('\n');
73
+ }
74
+
75
+ /**
76
+ * Resolve a node from the scene root by absolute NodePath (`/root/...`) or
77
+ * name glob (`findChild`). Returns `null` when not found.
78
+ */
79
+ function resolveNode(path: string, root: Window): Node | null {
80
+ if (path.startsWith('/')) return root.getNode(path);
81
+ return root.findChild(path, true, false);
82
+ }
83
+
84
+ /**
85
+ * Resolve a node by path (absolute NodePath or name glob) from the scene root
86
+ * and dump it via {@link dumpStr}.
87
+ *
88
+ * @param path - An absolute NodePath like `/root/Box`, or a `findChild` name/glob pattern
89
+ */
90
+ export function inspect(path: string): string | null {
91
+ const node = resolveNode(path, tree.root);
92
+ return node ? dumpStr(node) : null;
93
+ }
94
+
95
+ /**
96
+ * Synthesize a left-click at the center of a {@link Control} matched by `path`.
97
+ *
98
+ * Press and release are pushed through `Window.pushInput` (the GUI-routing
99
+ * path — `Input.parseInputEvent` doesn't reliably reach `Control.guiInput` on
100
+ * the wasm build). Positions are in device space (logical × `contentScaleFactor`).
101
+ *
102
+ * @param path - An absolute NodePath like `/root/...`, or a `findChild` name/glob pattern
103
+ * @returns The node's `dumpStr`, or `null` if not found or not a `Control`
104
+ */
105
+ export function click(path: string): string | null {
106
+ const root = tree.root;
107
+ const node = resolveNode(path, root);
108
+ if (!(node instanceof Control)) return null;
109
+ const rect = node.getGlobalRect();
110
+ const scale = root.contentScaleFactor;
111
+ const position = new Vector2(
112
+ (rect.position.x + rect.size.x / 2) * scale,
113
+ (rect.position.y + rect.size.y / 2) * scale,
114
+ );
115
+ const press = (down: boolean) => {
116
+ const event = new InputEventMouseButton();
117
+ event.position = position;
118
+ event.globalPosition = position;
119
+ event.buttonIndex = MouseButton.MOUSE_BUTTON_LEFT;
120
+ event.pressed = down;
121
+ root.pushInput(event);
122
+ };
123
+ press(true);
124
+ setTimeout(() => press(false), 50);
125
+ return dumpStr(node);
126
+ }
127
+
128
+ /**
129
+ * Enumerate nodes in the scene by name pattern and/or class, in tree order.
130
+ *
131
+ * @param pattern - Name glob matched by `findChildren` (default `"*"`)
132
+ * @param type - Class name to filter by, e.g. `"RigidBody3D"` (default `""` = any)
133
+ * @param node - Root node to search under (defaults to the scene tree's root Window)
134
+ */
135
+ export function find(pattern = '*', type = '', node?: Node): Node[] {
136
+ const root = node ?? tree.root;
137
+ return [...root.findChildren(pattern, type, true, false)];
138
+ }
139
+
140
+ /**
141
+ * Run `gc()` and report how much heap was freed.
142
+ * Requires the `--expose-gc` Node.js flag.
143
+ */
144
+ export function gc(): string {
145
+ const before = globalThis.process?.memoryUsage?.().heapUsed;
146
+ if (globalThis.Bun)
147
+ globalThis.Bun.gc(true);
148
+ else if (globalThis.gc)
149
+ globalThis.gc({ type: 'major', execution: 'sync' });
150
+ else
151
+ return 'gc() unavailable — need --expose-gc';
152
+
153
+ const after = globalThis.process?.memoryUsage?.().heapUsed;
154
+ const freed = typeof before === 'number' && typeof after === 'number' ? (before - after) / 1024 : 0;
155
+ return `GC: freed ${freed.toFixed(0)} KB`;
156
+ }
157
+
158
+ /**
159
+ * `DOMRect` is not a global in Bun (desktop), but `getBoundingClientRect()`
160
+ * constructs one. Install a minimal spec-compatible polyfill on desktop so the
161
+ * helper works identically on desktop and web (browsers already define it).
162
+ */
163
+ function ensureDOMRect(): void {
164
+ if (typeof (globalThis as any).DOMRect !== 'undefined') return;
165
+ (globalThis as any).DOMRect = class DOMRect {
166
+ x: number;
167
+ y: number;
168
+ width: number;
169
+ height: number;
170
+ constructor(x = 0, y = 0, width = 0, height = 0) {
171
+ this.x = x;
172
+ this.y = y;
173
+ this.width = width;
174
+ this.height = height;
175
+ }
176
+ get left() { return this.x; }
177
+ get top() { return this.y; }
178
+ get right() { return this.x + this.width; }
179
+ get bottom() { return this.y + this.height; }
180
+ toJSON() { return { x: this.x, y: this.y, width: this.width, height: this.height }; }
181
+ };
182
+ }
183
+
184
+ type Push = (x: number, y: number) => void;
185
+ type BoundsCollect = (node: any, push: Push, viewport: Viewport) => void;
186
+
187
+ /** Affine 2D point mapper from a transform's basis/origin, optionally scaled. */
188
+ function makeAffine(t: any, scale = 1): (x: number, y: number) => [number, number] {
189
+ const tox = t.origin.x, toy = t.origin.y;
190
+ const txx = t.x.x, txy = t.x.y;
191
+ const tyx = t.y.x, tyy = t.y.y;
192
+ return (x, y) => [(tox + txx * x + tyx * y) * scale, (toy + txy * x + tyy * y) * scale];
193
+ }
194
+
195
+ /**
196
+ * Axis-aligned 2D bounds accumulator in CSS pixels. Non-finite points (e.g.
197
+ * geometry behind the camera) are dropped; `rect()` is `null` when no point
198
+ * was added.
199
+ */
200
+ function cssBounds(): { add(x: number, y: number): void; rect(): [number, number, number, number] | null } {
201
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
202
+ let found = false;
203
+ return {
204
+ add(x, y) {
205
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return;
206
+ if (x < minX) minX = x; if (y < minY) minY = y;
207
+ if (x > maxX) maxX = x; if (y > maxY) maxY = y;
208
+ found = true;
209
+ },
210
+ rect() {
211
+ return found ? [minX, minY, maxX - minX, maxY - minY] : null;
212
+ },
213
+ };
214
+ }
215
+
216
+ /** World-space AABB (min, max) of a local AABB under its global transform, or `null` when degenerate. */
217
+ function worldAabb(aabb: any, gt: any): [number, number, number, number, number, number] | null {
218
+ if (aabb.size.x === 0 && aabb.size.y === 0 && aabb.size.z === 0) return null;
219
+ const bx = gt.basis.x, by = gt.basis.y, bz = gt.basis.z;
220
+ const cx = aabb.position.x + aabb.size.x / 2;
221
+ const cy = aabb.position.y + aabb.size.y / 2;
222
+ const cz = aabb.position.z + aabb.size.z / 2;
223
+ const ex = Math.hypot(bx.x, bx.y, bx.z) * aabb.size.x / 2;
224
+ const ey = Math.hypot(by.x, by.y, by.z) * aabb.size.y / 2;
225
+ const ez = Math.hypot(bz.x, bz.y, bz.z) * aabb.size.z / 2;
226
+ const ox = gt.origin.x, oy = gt.origin.y, oz = gt.origin.z;
227
+ const wx = ox + bx.x * cx + by.x * cy + bz.x * cz;
228
+ const wy = oy + bx.y * cx + by.y * cy + bz.y * cz;
229
+ const wz = oz + bx.z * cx + by.z * cy + bz.z * cz;
230
+ return [wx - ex, wy - ey, wz - ez, wx + ex, wy + ey, wz + ez];
231
+ }
232
+
233
+ /**
234
+ * World-space AABB of a node's visual content: the union of its own AABB (when
235
+ * it is a `VisualInstance3D`) and every descendant `VisualInstance3D`'s, each in
236
+ * its own global transform — mirrors the editor's `_calculate_spatial_bounds`.
237
+ * Returns `null` when there is no non-degenerate visual.
238
+ */
239
+ function worldBounds(node: Node3D): [number, number, number, number, number, number] | null {
240
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
241
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
242
+ const add = (aabb: any, gt: any) => {
243
+ const box = worldAabb(aabb, gt);
244
+ if (!box) return;
245
+ if (box[0] < minX) minX = box[0]; if (box[3] > maxX) maxX = box[3];
246
+ if (box[1] < minY) minY = box[1]; if (box[4] > maxY) maxY = box[4];
247
+ if (box[2] < minZ) minZ = box[2]; if (box[5] > maxZ) maxZ = box[5];
248
+ };
249
+ if (typeof (node as any).getAabb === 'function') {
250
+ add((node as any).getAabb(), node.globalTransform);
251
+ }
252
+ for (const child of node.findChildren('*', 'VisualInstance3D', true, false) as unknown as any[]) {
253
+ if (child && typeof child.getAabb === 'function') {
254
+ add(child.getAabb(), child.globalTransform);
255
+ }
256
+ }
257
+ return minX === Infinity ? null : [minX, minY, minZ, maxX, maxY, maxZ];
258
+ }
259
+
260
+ /**
261
+ * Compute a node's bounding rect in CSS pixels. The callback pushes points in
262
+ * viewport logical units; they're mapped through the viewport's screen transform
263
+ * (content scale, stretch, SubViewport/child-window placement), then divided by
264
+ * screenGetScale to reach CSS pixels. Never throws: React DevTools calls this on
265
+ * every commit and must not see a throw (e.g. a wrapper freed by an unmount).
266
+ */
267
+ function boundsForViewport(node: Node, collect: (push: Push, viewport: Viewport) => void): DOMRect | null {
268
+ try {
269
+ const viewport = node.getViewport();
270
+ if (!viewport) return null;
271
+ const xform = makeAffine(viewport.getScreenTransform(), 1 / DisplayServer.screenGetScale());
272
+ const bounds = cssBounds();
273
+ collect((x, y) => bounds.add(...xform(x, y)), viewport);
274
+ const r = bounds.rect();
275
+ return r ? new DOMRect(r[0], r[1], r[2], r[3]) : null;
276
+ } catch {
277
+ return null;
278
+ }
279
+ }
280
+
281
+ /** Install `getBoundingClientRect` on a node prototype. */
282
+ function defineBoundingClientRect(proto: object, collect: BoundsCollect): void {
283
+ Object.defineProperty(proto, 'getBoundingClientRect', {
284
+ configurable: true,
285
+ value(this: Node): DOMRect | null {
286
+ return boundsForViewport(this, (push, viewport) => collect(this, push, viewport));
287
+ },
288
+ });
289
+ }
290
+
291
+ /** Push the four corners of an axis-aligned rect through `emit`. */
292
+ function pushRect(emit: (x: number, y: number) => void, x0: number, y0: number, x1: number, y1: number): void {
293
+ for (const px of [x0, x1]) {
294
+ for (const py of [y0, y1]) {
295
+ emit(px, py);
296
+ }
297
+ }
298
+ }
299
+
300
+ const canvasItemBounds: BoundsCollect = (node, push) => {
301
+ if (node instanceof Control) {
302
+ const rc = node.getGlobalRect();
303
+ pushRect(push, rc.position.x, rc.position.y, rc.position.x + rc.size.x, rc.position.y + rc.size.y);
304
+ return;
305
+ }
306
+ if (typeof node.getRect !== 'function') return;
307
+ const rect = node.getRect() as Rect2;
308
+ const xform = makeAffine(node.getScreenTransform());
309
+ pushRect((px, py) => push(...xform(px, py)), rect.position.x, rect.position.y, rect.position.x + rect.size.x, rect.position.y + rect.size.y);
310
+ };
311
+
312
+ const node3dBounds: BoundsCollect = (node, push, viewport) => {
313
+ const camera = viewport.getCamera3d();
314
+ if (!camera) return;
315
+ const box = worldBounds(node);
316
+ if (!box) return;
317
+ const [minX, minY, minZ, maxX, maxY, maxZ] = box;
318
+ for (let i = 0; i < 8; i++) {
319
+ const s = camera.unprojectPosition(new Vector3(
320
+ i & 1 ? maxX : minX,
321
+ i & 2 ? maxY : minY,
322
+ i & 4 ? maxZ : minZ,
323
+ ));
324
+ push(s.x, s.y);
325
+ }
326
+ };
327
+
328
+ /**
329
+ * Bootstrap the debugging environment.
330
+ *
331
+ * - Exposes common singletons (`Engine`, `OS`, `ClassDB`, `Time`) and all
332
+ * debug utility functions on `globalThis.$` so they're reachable from
333
+ * breakpoints in any module.
334
+ * - Registers an `uncaughtException` handler that logs but keeps the process
335
+ * alive for interactive debugging.
336
+ * - Polyfills `DOMRect` (needed by `getBoundingClientRect()` on desktop).
337
+ */
338
+ export function initDebug(): void {
339
+ globalThis.process?.on?.('uncaughtException', (err, origin) => {
340
+ console.error(`\n✗ ${origin}:`, err.stack);
341
+ });
342
+
343
+ ensureDOMRect();
344
+ defineBoundingClientRect(CanvasItem.prototype, canvasItemBounds);
345
+ defineBoundingClientRect(Node3D.prototype, node3dBounds);
346
+
347
+ (globalThis as any).$ = {
348
+ Engine, OS, ClassDB, Time,
349
+ dumpStr, snapshot, inspect, click, find, gc,
350
+ get tree(): SceneTree { return tree; },
351
+ get paused(): boolean { return tree.paused; },
352
+ set paused(v: boolean) { tree.paused = v; },
353
+ };
354
+ }