@playcanvas/inspector 0.1.0

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.
Files changed (77) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +110 -0
  3. package/package.json +62 -0
  4. package/src/asset-usage.js +108 -0
  5. package/src/asset-view.js +370 -0
  6. package/src/camera-view.js +128 -0
  7. package/src/debug.js +31 -0
  8. package/src/describe.js +302 -0
  9. package/src/entity-inspector-script.js +130 -0
  10. package/src/frame-graph-view.js +767 -0
  11. package/src/hierarchy-view.js +475 -0
  12. package/src/index.js +4 -0
  13. package/src/input/fly-controller.js +116 -0
  14. package/src/input/input.js +299 -0
  15. package/src/input/math.js +8 -0
  16. package/src/input/orbit-controller.js +158 -0
  17. package/src/input/pose.js +207 -0
  18. package/src/inspector.js +3293 -0
  19. package/src/instance-survey.js +50 -0
  20. package/src/list-view.js +410 -0
  21. package/src/material-view.js +197 -0
  22. package/src/memory-view.js +344 -0
  23. package/src/mesh-view.js +235 -0
  24. package/src/model.js +170 -0
  25. package/src/node-model.js +404 -0
  26. package/src/physics-debug.js +527 -0
  27. package/src/physics-view.js +314 -0
  28. package/src/picker/picker.js +545 -0
  29. package/src/picker/render-pass-picker.js +206 -0
  30. package/src/property-view.js +628 -0
  31. package/src/render-target-view.js +288 -0
  32. package/src/renderers/texture-renderer-shaders.js +139 -0
  33. package/src/renderers/texture-renderer.js +430 -0
  34. package/src/renderers/wire-renderer.js +954 -0
  35. package/src/script-view.js +288 -0
  36. package/src/shader-view.js +287 -0
  37. package/src/styles.js +918 -0
  38. package/src/texture-view.js +186 -0
  39. package/src/tooltip.js +72 -0
  40. package/src/viewport-tools.js +695 -0
  41. package/types/asset-usage.d.ts +23 -0
  42. package/types/asset-view.d.ts +94 -0
  43. package/types/camera-view.d.ts +45 -0
  44. package/types/debug.d.ts +14 -0
  45. package/types/describe.d.ts +43 -0
  46. package/types/entity-inspector-script.d.ts +87 -0
  47. package/types/frame-graph-view.d.ts +155 -0
  48. package/types/hierarchy-view.d.ts +172 -0
  49. package/types/index.d.ts +3 -0
  50. package/types/input/fly-controller.d.ts +42 -0
  51. package/types/input/input.d.ts +192 -0
  52. package/types/input/math.d.ts +1 -0
  53. package/types/input/orbit-controller.d.ts +63 -0
  54. package/types/input/pose.d.ts +126 -0
  55. package/types/inspector.d.ts +1304 -0
  56. package/types/instance-survey.d.ts +35 -0
  57. package/types/list-view.d.ts +151 -0
  58. package/types/material-view.d.ts +63 -0
  59. package/types/memory-view.d.ts +95 -0
  60. package/types/mesh-view.d.ts +89 -0
  61. package/types/model.d.ts +104 -0
  62. package/types/node-model.d.ts +54 -0
  63. package/types/physics-debug.d.ts +254 -0
  64. package/types/physics-view.d.ts +81 -0
  65. package/types/picker/picker.d.ts +255 -0
  66. package/types/picker/render-pass-picker.d.ts +47 -0
  67. package/types/property-view.d.ts +189 -0
  68. package/types/render-target-view.d.ts +98 -0
  69. package/types/renderers/texture-renderer-shaders.d.ts +9 -0
  70. package/types/renderers/texture-renderer.d.ts +231 -0
  71. package/types/renderers/wire-renderer.d.ts +347 -0
  72. package/types/script-view.d.ts +56 -0
  73. package/types/shader-view.d.ts +46 -0
  74. package/types/styles.d.ts +22 -0
  75. package/types/texture-view.d.ts +30 -0
  76. package/types/tooltip.d.ts +17 -0
  77. package/types/viewport-tools.d.ts +237 -0
@@ -0,0 +1,695 @@
1
+ import {
2
+ BoundingBox, Entity, PROJECTION_ORTHOGRAPHIC, RENDERSTYLE_SOLID, RENDERSTYLE_WIREFRAME, SHADERPASS_ALBEDO, SHADERPASS_AO, SHADERPASS_EMISSION, SHADERPASS_FORWARD, SHADERPASS_GLOSS, SHADERPASS_LIGHTING, SHADERPASS_METALNESS, SHADERPASS_OPACITY, SHADERPASS_SPECULARITY, SHADERPASS_UV0, SHADERPASS_WORLDNORMAL, Vec2, Vec3, math
3
+ } from 'playcanvas';
4
+
5
+ import { Picker } from './picker/picker.js';
6
+ import { FlyController } from './input/fly-controller.js';
7
+ import { OrbitController } from './input/orbit-controller.js';
8
+ import { InputFrame } from './input/input.js';
9
+ import { Pose } from './input/pose.js';
10
+
11
+ import { collectMeshInstances } from './instance-survey.js';
12
+
13
+ /** @import { Quat } from 'playcanvas' */
14
+ /** @import { AppBase } from 'playcanvas' */
15
+ /** @import { CameraComponent } from 'playcanvas' */
16
+ /** @import { GraphNode } from 'playcanvas' */
17
+ /** @import { MeshInstance } from 'playcanvas' */
18
+
19
+ /**
20
+ * The shader passes a camera can render with, as the editor offers them: the lit scene, and the
21
+ * debug views of the standard material's inputs.
22
+ */
23
+ const RENDER_MODES = [
24
+ [SHADERPASS_FORWARD, 'standard'], [SHADERPASS_ALBEDO, 'albedo'], [SHADERPASS_OPACITY, 'opacity'],
25
+ [SHADERPASS_WORLDNORMAL, 'world normal'], [SHADERPASS_SPECULARITY, 'specularity'], [SHADERPASS_GLOSS, 'gloss'],
26
+ [SHADERPASS_METALNESS, 'metalness'], [SHADERPASS_AO, 'ao'], [SHADERPASS_EMISSION, 'emission'],
27
+ [SHADERPASS_LIGHTING, 'lighting'], [SHADERPASS_UV0, 'uv0']
28
+ ];
29
+
30
+ // the input events the pick and fly modes take ahead of the app while they are on
31
+ const POINTER_EVENTS = ['pointerdown', 'pointermove', 'pointerup', 'mousedown', 'mousemove', 'mouseup', 'click', 'dblclick', 'wheel', 'contextmenu', 'touchstart', 'touchmove', 'touchend'];
32
+
33
+ /**
34
+ * @param {Event} e - An event.
35
+ * @returns {boolean} Whether it is aimed at a text field, which keeps its keys.
36
+ */
37
+ function isTextTarget(e) {
38
+ const target = /** @type {HTMLElement|undefined} */ (e.composedPath?.()[0]);
39
+ return !!target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT' || target.isContentEditable);
40
+ }
41
+
42
+ /**
43
+ * @param {CameraComponent} camera - A camera.
44
+ * @returns {boolean} Whether it draws to the screen, the ones a pointer can be over.
45
+ */
46
+ function isScreenCamera(camera) {
47
+ return camera.enabled && camera.entity.enabled && !camera.renderTarget;
48
+ }
49
+
50
+ /**
51
+ * The screen camera whose viewport holds a point of the canvas, the last one drawn when several
52
+ * overlap, which is the one on top.
53
+ *
54
+ * @param {AppBase} app - The app.
55
+ * @param {number} x - The point, as a fraction of the canvas width from its left edge.
56
+ * @param {number} y - The point, as a fraction of the canvas height from its top edge.
57
+ * @returns {CameraComponent|null} The camera, or null when no camera draws there.
58
+ */
59
+ function screenCameraAt(app, x, y) {
60
+ const cameras = /** @type {CameraComponent[]} */ (app.systems.camera?.cameras ?? []);
61
+ let found = null;
62
+ for (const camera of cameras) {
63
+ if (!isScreenCamera(camera)) continue;
64
+ // a camera rect has its origin at the bottom left
65
+ const rect = camera.rect;
66
+ const up = 1 - y;
67
+ if (x >= rect.x && x <= rect.x + rect.z && up >= rect.y && up <= rect.y + rect.w) found = camera;
68
+ }
69
+ return found;
70
+ }
71
+
72
+ /**
73
+ * @param {GraphNode|null} node - A node.
74
+ * @returns {Entity|null} The node, or the closest entity above it: the node of a mesh instance an
75
+ * imported model creates can be a plain graph node.
76
+ */
77
+ function entityOf(node) {
78
+ let current = node;
79
+ while (current && !(current instanceof Entity)) current = current.parent;
80
+ return /** @type {Entity|null} */ (current);
81
+ }
82
+
83
+ /**
84
+ * Takes the pointer events on the canvas ahead of the app's own handlers, for a mode of the
85
+ * inspector that uses the pointer itself. The listeners sit in the capture phase on the window, so
86
+ * they run before any listener of the app, and stop the events there.
87
+ */
88
+ class CanvasCapture {
89
+ /** @type {HTMLCanvasElement} */
90
+ canvas;
91
+
92
+ /** @type {(e: Event) => void} */
93
+ _listener;
94
+
95
+ /**
96
+ * @param {HTMLCanvasElement} canvas - The canvas.
97
+ * @param {(e: Event) => void} onEvent - Called with every pointer event on the canvas.
98
+ */
99
+ constructor(canvas, onEvent) {
100
+ this.canvas = canvas;
101
+ this._listener = (e) => {
102
+ // a drag started on the canvas keeps its moves and release when the pointer leaves it
103
+ if (e.target !== canvas && !(this._dragging && (e.type.endsWith('move') || e.type.endsWith('up')))) return;
104
+ if (e.type === 'pointerdown' || e.type === 'mousedown') this._dragging = true;
105
+ if (e.type === 'pointerup' || e.type === 'mouseup') this._dragging = false;
106
+ e.stopImmediatePropagation();
107
+ if (e.cancelable) e.preventDefault();
108
+ onEvent(e);
109
+ };
110
+ this._dragging = false;
111
+ for (const type of POINTER_EVENTS) window.addEventListener(type, this._listener, { capture: true, passive: false });
112
+ }
113
+
114
+ destroy() {
115
+ for (const type of POINTER_EVENTS) window.removeEventListener(type, this._listener, { capture: true });
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Picks the entity under the pointer, through the screen camera whose viewport holds it, the way
121
+ * the editor picks: an id buffer the size of the canvas is rendered for that camera, which draws
122
+ * into its own viewport of it, and read back under the pointer.
123
+ */
124
+ class ViewportPicker {
125
+ /** @type {AppBase} */
126
+ app;
127
+
128
+ /** @type {Picker|null} */
129
+ _picker = null;
130
+
131
+ /**
132
+ * The picks in flight, one after the other, as each reads back the id buffer the next renders.
133
+ *
134
+ * @type {Promise<*>}
135
+ */
136
+ _queue = Promise.resolve();
137
+
138
+ /**
139
+ * @param {AppBase} app - The app.
140
+ */
141
+ constructor(app) {
142
+ this.app = app;
143
+ }
144
+
145
+ /**
146
+ * @param {number} clientX - The pointer, in client pixels.
147
+ * @param {number} clientY - The pointer, in client pixels.
148
+ * @returns {Promise<{ entity: Entity, instance: MeshInstance, camera: CameraComponent }|null>} What
149
+ * is under the pointer, or null for nothing. Picks run one after the other.
150
+ */
151
+ pick(clientX, clientY) {
152
+ const result = this._queue.then(() => this._pickNow(clientX, clientY));
153
+ this._queue = result.catch(() => null);
154
+ return result;
155
+ }
156
+
157
+ /**
158
+ * @param {number} clientX - The pointer, in client pixels.
159
+ * @param {number} clientY - The pointer, in client pixels.
160
+ * @returns {Promise<{ entity: Entity, instance: MeshInstance, camera: CameraComponent }|null>} What
161
+ * is under the pointer.
162
+ * @private
163
+ */
164
+ async _pickNow(clientX, clientY) {
165
+ if (!this._picker && this._destroyed) return null;
166
+ const device = this.app.graphicsDevice;
167
+ const canvas = /** @type {HTMLCanvasElement} */ (device.canvas);
168
+ const bounds = canvas.getBoundingClientRect();
169
+ if (!bounds.width || !bounds.height) return null;
170
+ const fx = (clientX - bounds.left) / bounds.width;
171
+ const fy = (clientY - bounds.top) / bounds.height;
172
+ const camera = screenCameraAt(this.app, fx, fy);
173
+ if (!camera) return null;
174
+
175
+ this._picker ??= new Picker(this.app, device.width, device.height);
176
+ if (this._picker.width !== device.width || this._picker.height !== device.height) {
177
+ this._picker.resize(device.width, device.height);
178
+ }
179
+ this._picker.prepare(camera, this.app.scene);
180
+
181
+ const [hit] = await this._picker.getSelectionAsync(Math.floor(fx * device.width), Math.floor(fy * device.height));
182
+ const node = /** @type {any} */ (hit)?.node ?? /** @type {any} */ (hit)?.entity ?? null;
183
+ const entity = entityOf(node);
184
+ return entity ? { entity, instance: /** @type {MeshInstance} */ (hit), camera } : null;
185
+ }
186
+
187
+ destroy() {
188
+ this._destroyed = true;
189
+ this._picker?.destroy();
190
+ this._picker = null;
191
+ }
192
+ }
193
+
194
+ const _position = new Vec3();
195
+ const _target = new Vec3();
196
+ const _offset = new Vec3();
197
+ const _focus = new Vec3();
198
+ const _from = new Pose();
199
+
200
+ // fly speeds: units a second, and degrees of turn per pixel dragged
201
+ const FLY_SPEED = 5;
202
+ const FLY_FAST = 4;
203
+ const LOOK_SPEED = 0.2;
204
+
205
+ // an orthographic view pans by this share of its height a second, and zooms by this rate
206
+ const ORTHO_PAN = 0.5;
207
+ const ORTHO_ZOOM = 1;
208
+
209
+ // orbit speeds: degrees of turn per pixel dragged, and the share of the distance a wheel pixel zooms
210
+ const ORBIT_SPEED = 0.3;
211
+ const ORBIT_ZOOM = 0.0012;
212
+
213
+ // the pitch an orbit stays within, short of straight up and down, where it would flip over
214
+ const ORBIT_PITCH = new Vec2(-89, 89);
215
+
216
+ // the keys that fly, as offsets along right, up and forward
217
+ const FLY_KEYS = {
218
+ KeyW: [0, 0, 1],
219
+ ArrowUp: [0, 0, 1],
220
+ KeyS: [0, 0, -1],
221
+ ArrowDown: [0, 0, -1],
222
+ KeyA: [-1, 0, 0],
223
+ ArrowLeft: [-1, 0, 0],
224
+ KeyD: [1, 0, 0],
225
+ ArrowRight: [1, 0, 0],
226
+ KeyE: [0, 1, 0],
227
+ PageUp: [0, 1, 0],
228
+ KeyQ: [0, -1, 0],
229
+ PageDown: [0, -1, 0]
230
+ };
231
+
232
+ /**
233
+ * Drives a camera the app keeps drawing with, from the inspector's own input. The app may move the
234
+ * camera itself, from a script or from code of its own, so the camera is not taken over: its
235
+ * transform is swapped for the driven one on the app's prerender event, after every update has run,
236
+ * and put back on postrender, so the frame is drawn from the driven pose while the app keeps seeing
237
+ * and moving its own. Its projection is held the same way, at the field of view or orthographic
238
+ * height it had when the drive started, as an app may animate those too. Ending the drive needs no
239
+ * restoring. The keyboard and the pointer on the canvas are taken ahead of the app while driving,
240
+ * and the drive runs on the wall clock, so a paused app can be looked around.
241
+ *
242
+ * @abstract
243
+ */
244
+ class CameraDrive {
245
+ /** @type {AppBase} */
246
+ app;
247
+
248
+ /** @type {CameraComponent} */
249
+ camera;
250
+
251
+ /** @type {{ position: Vec3, rotation: Quat, fov: number, orthoHeight: number }|null} */
252
+ _saved = null;
253
+
254
+ /** Whether the camera is orthographic, which zooms by its height rather than by moving. */
255
+ _ortho = false;
256
+
257
+ /** The field of view the driven view keeps. */
258
+ _fov = 0;
259
+
260
+ /** The orthographic height the driven view keeps, changed by zooming. */
261
+ _orthoHeight = 0;
262
+
263
+ _lastTime = 0;
264
+
265
+ /** @type {CanvasCapture} */
266
+ _capture;
267
+
268
+ /**
269
+ * @param {AppBase} app - The app.
270
+ * @param {CameraComponent} camera - The camera to drive.
271
+ * @param {() => void} onEnd - Called when the drive ends from the keyboard.
272
+ */
273
+ constructor(app, camera, onEnd) {
274
+ this.app = app;
275
+ this.camera = camera;
276
+ this._onEnd = onEnd;
277
+ this._ortho = camera.projection === PROJECTION_ORTHOGRAPHIC;
278
+ this._fov = camera.fov;
279
+ this._orthoHeight = camera.orthoHeight;
280
+
281
+ // the subclasses' handlers are methods, so they are bound here rather than as fields,
282
+ // which would not exist yet while this constructor runs
283
+ this._pointerListener = e => this._onPointer(e);
284
+ this._keyDownListener = (e) => {
285
+ if (isTextTarget(e)) return;
286
+ if (e.key === 'Escape') {
287
+ e.stopImmediatePropagation();
288
+ this._onEnd();
289
+ return;
290
+ }
291
+ this._onKey(e, true);
292
+ };
293
+ this._keyUpListener = e => this._onKey(e, false);
294
+ this._blurListener = () => this._onBlur();
295
+
296
+ this._capture = new CanvasCapture(/** @type {HTMLCanvasElement} */ (app.graphicsDevice.canvas), this._pointerListener);
297
+ window.addEventListener('keydown', this._keyDownListener, true);
298
+ window.addEventListener('keyup', this._keyUpListener, true);
299
+ window.addEventListener('blur', this._blurListener);
300
+ app.on('prerender', this._onPrerender, this);
301
+ app.on('postrender', this._onPostrender, this);
302
+ this._lastTime = performance.now();
303
+ }
304
+
305
+ destroy() {
306
+ this.app.off('prerender', this._onPrerender, this);
307
+ this.app.off('postrender', this._onPostrender, this);
308
+ window.removeEventListener('keydown', this._keyDownListener, true);
309
+ window.removeEventListener('keyup', this._keyUpListener, true);
310
+ window.removeEventListener('blur', this._blurListener);
311
+ this._capture.destroy();
312
+ this._onPostrender();
313
+ }
314
+
315
+ /**
316
+ * @param {Event} e - A pointer event on the canvas.
317
+ * @abstract
318
+ */
319
+ _onPointer(e) {}
320
+
321
+ /**
322
+ * @param {KeyboardEvent} e - A key pressed or released, other than Esc.
323
+ * @param {boolean} down - Whether it was pressed.
324
+ */
325
+ _onKey(e, down) {}
326
+
327
+ _onBlur() {}
328
+
329
+ /**
330
+ * @param {number} dt - Seconds since the last frame.
331
+ * @returns {Pose} The pose to draw from this frame.
332
+ * @abstract
333
+ */
334
+ _update(dt) {
335
+ return new Pose();
336
+ }
337
+
338
+ _onPrerender() {
339
+ const now = performance.now();
340
+ const dt = Math.min(0.1, (now - this._lastTime) / 1000);
341
+ this._lastTime = now;
342
+ const pose = this._update(dt);
343
+
344
+ // draw from the driven pose and projection, keeping the app's own to put back after the frame
345
+ const camera = this.camera;
346
+ const entity = camera.entity;
347
+ if (!this._saved) {
348
+ this._saved = {
349
+ position: entity.getLocalPosition().clone(),
350
+ rotation: entity.getLocalRotation().clone(),
351
+ fov: camera.fov,
352
+ orthoHeight: camera.orthoHeight
353
+ };
354
+ }
355
+ entity.setPosition(pose.position);
356
+ entity.setEulerAngles(pose.angles);
357
+ if (this._ortho) {
358
+ if (camera.orthoHeight !== this._orthoHeight) camera.orthoHeight = this._orthoHeight;
359
+ } else if (camera.fov !== this._fov) {
360
+ camera.fov = this._fov;
361
+ }
362
+ }
363
+
364
+ _onPostrender() {
365
+ const saved = this._saved;
366
+ if (!saved) return;
367
+ this._saved = null;
368
+ const camera = this.camera;
369
+ const entity = camera.entity;
370
+ entity.setLocalPosition(saved.position);
371
+ entity.setLocalRotation(saved.rotation);
372
+ if (camera.fov !== saved.fov) camera.fov = saved.fov;
373
+ if (camera.orthoHeight !== saved.orthoHeight) camera.orthoHeight = saved.orthoHeight;
374
+ }
375
+
376
+ /**
377
+ * @returns {boolean} Whether the view zooms by its orthographic height rather than by moving.
378
+ */
379
+ get zooms() {
380
+ return this._ortho;
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Flies a camera with the mouse and WASD. An orthographic view shows no movement along its
386
+ * direction, so there forward and back zoom instead, and panning scales with the height of the view.
387
+ */
388
+ class CameraFly extends CameraDrive {
389
+ /** Units a second, changed with the wheel. */
390
+ speed = FLY_SPEED;
391
+
392
+ /** @type {FlyController} */
393
+ _controller = new FlyController();
394
+
395
+ /** @type {InputFrame<{ move: number[], rotate: number[] }>} */
396
+ _frame = new InputFrame({ move: [0, 0, 0], rotate: [0, 0] });
397
+
398
+ /** @type {Pose} */
399
+ _pose = new Pose();
400
+
401
+ /** @type {Set<string>} */
402
+ _keys = new Set();
403
+
404
+ _fast = false;
405
+
406
+ _looking = false;
407
+
408
+ _lastX = 0;
409
+
410
+ _lastY = 0;
411
+
412
+ /**
413
+ * @param {AppBase} app - The app.
414
+ * @param {CameraComponent} camera - The camera to fly.
415
+ * @param {() => void} onEnd - Called when the flight ends from the keyboard.
416
+ */
417
+ constructor(app, camera, onEnd) {
418
+ super(app, camera, onEnd);
419
+
420
+ // start where the camera is, looking where it looks
421
+ const entity = camera.entity;
422
+ _position.copy(entity.getPosition());
423
+ _target.copy(entity.forward).add(_position);
424
+ this._pose.look(_position, _target);
425
+ this._controller.attach(this._pose, false);
426
+ this._controller.moveDamping = 0.9;
427
+ this._controller.rotateDamping = 0.8;
428
+ }
429
+
430
+ /** @param {Event} e - A pointer event on the canvas. */
431
+ _onPointer(e) {
432
+ const pointer = /** @type {PointerEvent} */ (e);
433
+ if (e.type === 'pointerdown') {
434
+ this._looking = true;
435
+ this._lastX = pointer.clientX;
436
+ this._lastY = pointer.clientY;
437
+ } else if (e.type === 'pointerup') {
438
+ this._looking = false;
439
+ } else if (e.type === 'pointermove' && this._looking) {
440
+ this._frame.deltas.rotate.append([(pointer.clientX - this._lastX) * LOOK_SPEED, (pointer.clientY - this._lastY) * LOOK_SPEED]);
441
+ this._lastX = pointer.clientX;
442
+ this._lastY = pointer.clientY;
443
+ } else if (e.type === 'wheel') {
444
+ const wheel = /** @type {WheelEvent} */ (e);
445
+ this.speed = Math.min(1000, Math.max(0.05, this.speed * (wheel.deltaY < 0 ? 1.2 : 1 / 1.2)));
446
+ }
447
+ }
448
+
449
+ /**
450
+ * @param {KeyboardEvent} e - The event.
451
+ * @param {boolean} down - Whether the key was pressed.
452
+ */
453
+ _onKey(e, down) {
454
+ this._fast = e.shiftKey;
455
+ if (!down) {
456
+ if (this._keys.delete(e.code)) e.stopImmediatePropagation();
457
+ } else if (FLY_KEYS[e.code] && !e.ctrlKey && !e.metaKey && !e.altKey) {
458
+ e.stopImmediatePropagation();
459
+ e.preventDefault();
460
+ this._keys.add(e.code);
461
+ }
462
+ }
463
+
464
+ _onBlur() {
465
+ this._keys.clear();
466
+ this._looking = false;
467
+ }
468
+
469
+ /**
470
+ * @param {number} dt - Seconds since the last frame.
471
+ * @returns {Pose} The flown pose.
472
+ */
473
+ _update(dt) {
474
+ const move = [0, 0, 0];
475
+ for (const code of this._keys) {
476
+ const offset = FLY_KEYS[code];
477
+ for (let i = 0; i < 3; i++) move[i] += offset[i];
478
+ }
479
+ const boost = this._fast ? FLY_FAST : 1;
480
+ let step = this.speed * boost * dt;
481
+ if (this._ortho) {
482
+ // forward and back zoom, and the view pans in proportion to what it shows
483
+ const rate = (this.speed / FLY_SPEED) * boost * ORTHO_ZOOM * dt;
484
+ this._orthoHeight = Math.max(1e-3, this._orthoHeight * Math.exp(-move[2] * rate));
485
+ move[2] = 0;
486
+ step = this._orthoHeight * ORTHO_PAN * (this.speed / FLY_SPEED) * boost * dt;
487
+ }
488
+ this._frame.deltas.move.append(move.map(value => value * step));
489
+ return this._controller.update(this._frame, dt);
490
+ }
491
+ }
492
+
493
+ /**
494
+ * Orbits a camera around a node: drag to orbit, right-drag or Shift-drag to pan, and the wheel to
495
+ * zoom. The camera turns to the node from where it is, keeping its distance unless that is inside
496
+ * the node's bounds. The orbit follows the node as it moves, around the center of its bounds when
497
+ * the orbit started, or its position when it has none. An orthographic view zooms by its height.
498
+ */
499
+ class CameraOrbit extends CameraDrive {
500
+ /** @type {GraphNode} */
501
+ target;
502
+
503
+ /** @type {OrbitController} */
504
+ _controller = new OrbitController();
505
+
506
+ /** @type {InputFrame<{ move: number[], rotate: number[] }>} */
507
+ _frame = new InputFrame({ move: [0, 0, 0], rotate: [0, 0] });
508
+
509
+ /** The pose drawn last, for a change of target to turn from. */
510
+ _pose = new Pose();
511
+
512
+ /** The center of the target's bounds, relative to its position. */
513
+ _center = new Vec3();
514
+
515
+ /** Where the orbit was centered last frame, to follow the target by. */
516
+ _focus = new Vec3();
517
+
518
+ /** @type {'orbit'|'pan'|null} */
519
+ _drag = null;
520
+
521
+ _lastX = 0;
522
+
523
+ _lastY = 0;
524
+
525
+ /**
526
+ * @param {AppBase} app - The app.
527
+ * @param {CameraComponent} camera - The camera to orbit.
528
+ * @param {GraphNode} target - The node to orbit around.
529
+ * @param {() => void} onEnd - Called when the orbit ends from the keyboard.
530
+ */
531
+ constructor(app, camera, target, onEnd) {
532
+ super(app, camera, onEnd);
533
+ this._controller.pitchRange = ORBIT_PITCH;
534
+ this._controller.moveDamping = 0.8;
535
+ this._controller.rotateDamping = 0.8;
536
+ this._controller.zoomDamping = 0.8;
537
+
538
+ // the pose the camera has now, focused straight ahead, for the turn to the target to start from
539
+ const entity = camera.entity;
540
+ _position.copy(entity.getPosition());
541
+ _target.copy(entity.forward).add(_position);
542
+ this._pose.look(_position, _target);
543
+ this._controller.attach(this._pose, false);
544
+ this.setTarget(target);
545
+ }
546
+
547
+ /**
548
+ * Turns the orbit to another node, from where the camera is now.
549
+ *
550
+ * @param {GraphNode} target - The node to orbit around.
551
+ */
552
+ setTarget(target) {
553
+ this.target = target;
554
+ const radius = boundsOf(target, this._center);
555
+ this._focus.copy(this._center);
556
+ this._center.sub(target.getPosition());
557
+
558
+ // keep the distance the camera is at, unless that is inside the bounds
559
+ const position = this._pose.position;
560
+ const distance = Math.max(position.distance(this._focus), radius * 1.5, 1e-3);
561
+ _offset.sub2(position, this._focus).normalize().mulScalar(distance);
562
+ _from.look(_position.add2(this._focus, _offset), this._focus);
563
+ this._controller.attach(_from, true);
564
+ }
565
+
566
+ /** @param {Event} e - A pointer event on the canvas. */
567
+ _onPointer(e) {
568
+ const pointer = /** @type {PointerEvent} */ (e);
569
+ if (e.type === 'pointerdown') {
570
+ this._drag = pointer.button === 2 || pointer.button === 1 || pointer.shiftKey ? 'pan' : 'orbit';
571
+ this._lastX = pointer.clientX;
572
+ this._lastY = pointer.clientY;
573
+ } else if (e.type === 'pointerup') {
574
+ this._drag = null;
575
+ } else if (e.type === 'pointermove' && this._drag) {
576
+ const dx = pointer.clientX - this._lastX;
577
+ const dy = pointer.clientY - this._lastY;
578
+ this._lastX = pointer.clientX;
579
+ this._lastY = pointer.clientY;
580
+ if (this._drag === 'orbit') {
581
+ this._frame.deltas.rotate.append([dx * ORBIT_SPEED, dy * ORBIT_SPEED]);
582
+ } else {
583
+ // pan by what the view shows at the target, so the scene there moves with the pointer
584
+ const height = this._ortho ?
585
+ this._orthoHeight * 2 :
586
+ 2 * this._controller._childPose.position.z * Math.tan(this._fov * 0.5 * math.DEG_TO_RAD);
587
+ const scale = height / Math.max(1, this._capture.canvas.clientHeight);
588
+ this._frame.deltas.move.append([-dx * scale, dy * scale, 0]);
589
+ }
590
+ } else if (e.type === 'wheel') {
591
+ const wheel = /** @type {WheelEvent} */ (e);
592
+ const zoom = Math.max(-0.5, Math.min(0.5, wheel.deltaY * ORBIT_ZOOM));
593
+ if (this._ortho) {
594
+ this._orthoHeight = Math.max(1e-3, this._orthoHeight * (1 + zoom));
595
+ } else {
596
+ this._frame.deltas.move.append([0, 0, zoom]);
597
+ }
598
+ }
599
+ }
600
+
601
+ _onBlur() {
602
+ this._drag = null;
603
+ }
604
+
605
+ /**
606
+ * @param {number} dt - Seconds since the last frame.
607
+ * @returns {Pose} The orbiting pose.
608
+ */
609
+ _update(dt) {
610
+ // follow the target as it moves, without the lag of the smoothing. The controller has no
611
+ // way to move its focus without easing, so its two root poses move directly
612
+ _focus.add2(this.target.getPosition(), this._center);
613
+ if (!_focus.equals(this._focus)) {
614
+ _offset.sub2(_focus, this._focus);
615
+ this._controller._rootPose.position.add(_offset);
616
+ this._controller._targetRootPose.position.add(_offset);
617
+ this._focus.copy(_focus);
618
+ }
619
+ const pose = this._controller.update(this._frame, dt);
620
+ this._pose.copy(pose);
621
+ return pose;
622
+ }
623
+ }
624
+
625
+ /**
626
+ * The world bounds of a node and everything under it, from the mesh instances of their render and
627
+ * model components and the bounds of their splats.
628
+ *
629
+ * @param {GraphNode} node - The node.
630
+ * @param {Vec3} center - Receives the center of the bounds, or the node's position when it has none.
631
+ * @returns {number} The radius of the bounds, or 0 when the node has none.
632
+ */
633
+ function boundsOf(node, center) {
634
+ const bounds = new BoundingBox();
635
+ let found = false;
636
+ const add = (aabb) => {
637
+ if (found) {
638
+ bounds.add(aabb);
639
+ } else {
640
+ bounds.copy(aabb);
641
+ found = true;
642
+ }
643
+ };
644
+ node.forEach((child) => {
645
+ if (!(child instanceof Entity) || !child.enabled) return;
646
+ const meshInstances = child.render?.meshInstances ?? child.model?.meshInstances;
647
+ if (meshInstances) {
648
+ for (const meshInstance of meshInstances) {
649
+ if (meshInstance.visible) add(meshInstance.aabb);
650
+ }
651
+ }
652
+ const splat = child.gsplat?.customAabb;
653
+ if (splat) {
654
+ const world = new BoundingBox();
655
+ world.setFromTransformedAabb(splat, child.getWorldTransform());
656
+ add(world);
657
+ }
658
+ });
659
+ if (!found) {
660
+ center.copy(node.getPosition());
661
+ return 0;
662
+ }
663
+ center.copy(bounds.center);
664
+ return bounds.halfExtents.length();
665
+ }
666
+
667
+ /**
668
+ * Draws every mesh instance of the app in wireframe while on, keeping the render style each had to
669
+ * put back. Mesh instances the app adds while it is on take it on at the next apply.
670
+ */
671
+ class WireframeMode {
672
+ /** @type {Map<MeshInstance, number>} */
673
+ _styles = new Map();
674
+
675
+ /**
676
+ * @param {AppBase} app - The app, whose mesh instances to draw in wireframe.
677
+ */
678
+ apply(app) {
679
+ for (const { instance } of collectMeshInstances(app)) {
680
+ if (this._styles.has(instance)) continue;
681
+ this._styles.set(instance, instance.renderStyle);
682
+ if (instance.renderStyle !== RENDERSTYLE_WIREFRAME) instance.renderStyle = RENDERSTYLE_WIREFRAME;
683
+ }
684
+ }
685
+
686
+ /** Puts back the render style of every mesh instance drawn in wireframe. */
687
+ restore() {
688
+ for (const [instance, style] of this._styles) {
689
+ if (instance.mesh && instance.renderStyle !== style) instance.renderStyle = style ?? RENDERSTYLE_SOLID;
690
+ }
691
+ this._styles.clear();
692
+ }
693
+ }
694
+
695
+ export { CameraFly, CameraOrbit, CanvasCapture, RENDER_MODES, ViewportPicker, WireframeMode, isScreenCamera, screenCameraAt };