roamwright 0.55.1 → 0.57.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 (48) hide show
  1. package/README.md +2 -1
  2. package/examples/animals.js +27 -15
  3. package/examples/crowds.js +28 -18
  4. package/examples/effects.js +13 -11
  5. package/examples/figure-motion.js +17 -5
  6. package/examples/figure.js +12 -8
  7. package/examples/fliers.js +16 -12
  8. package/examples/fortification.js +31 -18
  9. package/examples/house-kit.js +17 -10
  10. package/examples/island.js +25 -12
  11. package/examples/land.js +14 -8
  12. package/examples/pacing.html +100 -0
  13. package/examples/pacing.js +305 -0
  14. package/examples/props-and-plants.js +21 -32
  15. package/examples/rooms.js +2 -2
  16. package/examples/ships.js +33 -15
  17. package/examples/small-world-land.js +3 -3
  18. package/examples/small-world-life.js +13 -5
  19. package/examples/small-world-town.js +8 -11
  20. package/examples/small-world.js +26 -19
  21. package/examples/soundscape.js +18 -18
  22. package/examples/stage-kits.js +5 -133
  23. package/examples/stage.js +1 -324
  24. package/examples/towns.js +25 -18
  25. package/examples/viaduct-landscape.js +1 -1
  26. package/examples/viaduct.js +3 -4
  27. package/geometry/builder.js +8 -18
  28. package/geometry/plant-broadleaf.js +10 -4
  29. package/geometry/plant-trees.js +15 -9
  30. package/geometry/still-mesh.js +35 -0
  31. package/index.js +19 -2
  32. package/motion/figure-mount.js +1 -0
  33. package/package.json +1 -1
  34. package/rendering/crowd-system.js +239 -0
  35. package/rendering/daylight-sky.js +212 -0
  36. package/rendering/house-kit-meshes.js +65 -16
  37. package/rendering/orbit-camera.js +216 -0
  38. package/rendering/perf-box-worker.js +95 -0
  39. package/rendering/perf-box.js +94 -0
  40. package/rendering/perf-probe-passes.js +333 -0
  41. package/rendering/perf-probe.js +406 -0
  42. package/rendering/water-simple.js +112 -0
  43. package/runtime/device-quality.js +75 -4
  44. package/runtime/perf-box-text.js +50 -0
  45. package/runtime/perf-probe.js +145 -0
  46. package/runtime/perf-watch.js +158 -0
  47. package/runtime/quality-fit.js +25 -5
  48. package/runtime/quality-store.js +37 -9
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Reusable orbit and showcase camera controller with ground clearance clamping, adaptive portrait
3
+ * field of view, keyboard orbit/zoom bindings, and named viewpoint switching.
4
+ * @module
5
+ */
6
+
7
+ import * as THREE from 'three';
8
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
9
+
10
+ /**
11
+ * Attaches keyboard arrow-key orbit and `+`/`=`/`-` zoom controls to `canvas` matching pointer
12
+ * `OrbitControls`, returning an unbind callback that removes the listener.
13
+ *
14
+ * @param {object} config
15
+ * @param {EventTarget} config.canvas Focusable canvas element receiving `keydown` events.
16
+ * @param {THREE.Camera} config.camera Camera driven by `controls`.
17
+ * @param {{ target: THREE.Vector3, update: () => void }} config.controls Orbit controls instance.
18
+ * @param {number} [config.minDistance=0] Minimum orbit distance from target (metres).
19
+ * @param {number} [config.maxDistance=Infinity] Maximum orbit distance from target (metres).
20
+ * @param {number} [config.yawStep=0.1] Azimuth increment per left/right key press (radians).
21
+ * @param {number} [config.pitchStep=0.08] Polar angle increment per up/down key press (radians).
22
+ * @param {number} [config.zoomFactor=0.88] Radius multiplier per `+` zoom step (`1 / zoomFactor` for `-`).
23
+ * @returns {() => void} Cleanup function removing the `keydown` listener.
24
+ */
25
+ export function bindKeyboardOrbit({
26
+ canvas,
27
+ camera,
28
+ controls,
29
+ minDistance = 0,
30
+ maxDistance = Infinity,
31
+ yawStep = 0.1,
32
+ pitchStep = 0.08,
33
+ zoomFactor = 0.88,
34
+ }) {
35
+ const offset = new THREE.Vector3();
36
+ const orbit = new THREE.Spherical();
37
+
38
+ function onKeyDown(event) {
39
+ offset.copy(camera.position).sub(controls.target);
40
+ orbit.setFromVector3(offset);
41
+ switch (event.key) {
42
+ case 'ArrowLeft':
43
+ orbit.theta -= yawStep;
44
+ break;
45
+ case 'ArrowRight':
46
+ orbit.theta += yawStep;
47
+ break;
48
+ case 'ArrowUp':
49
+ orbit.phi -= pitchStep;
50
+ break;
51
+ case 'ArrowDown':
52
+ orbit.phi += pitchStep;
53
+ break;
54
+ case '+':
55
+ case '=':
56
+ orbit.radius = Math.max(minDistance, orbit.radius * zoomFactor);
57
+ break;
58
+ case '-':
59
+ orbit.radius = Math.min(maxDistance, orbit.radius / zoomFactor);
60
+ break;
61
+ default:
62
+ return;
63
+ }
64
+ event.preventDefault();
65
+ camera.position.setFromSpherical(orbit.makeSafe()).add(controls.target);
66
+ controls.update();
67
+ }
68
+
69
+ canvas.addEventListener('keydown', onKeyDown);
70
+ return () => canvas.removeEventListener('keydown', onKeyDown);
71
+ }
72
+
73
+ /**
74
+ * Sets up `OrbitControls` with ground-clearance clamping, adaptive portrait FOV on resize,
75
+ * keyboard orbit/zoom, and optional named viewpoint buttons (`[data-view]`).
76
+ *
77
+ * @param {object} config
78
+ * @param {THREE.PerspectiveCamera} config.camera Perspective camera to control.
79
+ * @param {HTMLCanvasElement} config.canvas Target rendering canvas.
80
+ * @param {THREE.WebGLRenderer} config.renderer Renderer resized with the canvas.
81
+ * @param {THREE.Scene} config.scene Scene drawn on view changes when `onDraw` is omitted.
82
+ * @param {Record<string, { eye: [number, number, number], target: [number, number, number] }>} [config.views={}] Named viewpoints.
83
+ * @param {string} [config.initialView] Initial viewpoint key; defaults to the first key of `views`.
84
+ * @param {(x: number, z: number) => number} [config.groundAt] Ground height sampler (metres) for clearance clamping.
85
+ * @param {((camera: THREE.Camera) => void)|null} [config.guardCamera=null] Custom camera clamp overriding `groundAt` + `minClearance`.
86
+ * @param {number} [config.minClearance=1.0] Minimum height above `groundAt(x, z)` (metres).
87
+ * @param {number} [config.minDistance=4] Minimum orbit distance (metres).
88
+ * @param {number} [config.maxDistance=180] Maximum orbit distance (metres).
89
+ * @param {number} [config.baseFov=42] Landscape vertical FOV in degrees.
90
+ * @param {number} [config.maxFov=68] Maximum vertical FOV on narrow portrait viewports in degrees.
91
+ * @param {number} [config.maxPolarAngle=Math.PI * 0.485] Maximum polar angle from zenith (radians).
92
+ * @param {number} [config.far=2500] Camera far clipping plane (metres).
93
+ * @param {number} [config.maxPixelRatio=2] Upper bound on renderer pixel ratio.
94
+ * @param {boolean} [config.enableDamping=false] Enables OrbitControls damping.
95
+ * @param {boolean} [config.enablePan=false] Enables OrbitControls panning.
96
+ * @param {string|Iterable<Element>|false} [config.viewButtons='[data-view]'] CSS selector or element list for viewpoint buttons, or `false` to skip DOM binding.
97
+ * @param {(() => void)|null} [config.onDraw=null] Custom render callback (pass `() => {}` when an animation loop drives rendering).
98
+ * @returns {{ controls: OrbitControls, selectView: (name: string) => void, resize: () => void, clampCamera: () => void, dispose: () => void }}
99
+ */
100
+ export function createOrbitCamera({
101
+ camera,
102
+ canvas,
103
+ renderer,
104
+ scene,
105
+ views = {},
106
+ initialView,
107
+ groundAt = () => 0,
108
+ guardCamera = null,
109
+ minClearance = 1.0,
110
+ minDistance = 4,
111
+ maxDistance = 180,
112
+ baseFov = 42,
113
+ maxFov = 68,
114
+ maxPolarAngle = Math.PI * 0.485,
115
+ far = 2500,
116
+ maxPixelRatio = 2,
117
+ enableDamping = false,
118
+ enablePan = false,
119
+ viewButtons = '[data-view]',
120
+ onDraw = null,
121
+ }) {
122
+ const controls = new OrbitControls(camera, canvas);
123
+ controls.enableDamping = enableDamping;
124
+ controls.enablePan = enablePan;
125
+ controls.maxPolarAngle = maxPolarAngle;
126
+ controls.minDistance = minDistance;
127
+ controls.maxDistance = maxDistance;
128
+ camera.far = far;
129
+
130
+ const buttons =
131
+ viewButtons === false || viewButtons === null
132
+ ? []
133
+ : typeof viewButtons === 'string'
134
+ ? typeof document !== 'undefined'
135
+ ? Array.from(document.querySelectorAll(viewButtons))
136
+ : []
137
+ : Array.from(viewButtons);
138
+
139
+ function clampCamera() {
140
+ if (guardCamera) {
141
+ guardCamera(camera);
142
+ return;
143
+ }
144
+ const floor = groundAt(camera.position.x, camera.position.z);
145
+ if (Number.isFinite(floor) && camera.position.y < floor + minClearance) {
146
+ camera.position.y = floor + minClearance;
147
+ }
148
+ }
149
+
150
+ function render() {
151
+ clampCamera();
152
+ camera.lookAt(controls.target);
153
+ if (onDraw) onDraw();
154
+ else renderer.render(scene, camera);
155
+ }
156
+
157
+ function onControlsChange() {
158
+ clampCamera();
159
+ camera.lookAt(controls.target);
160
+ if (!onDraw) renderer.render(scene, camera);
161
+ }
162
+ controls.addEventListener('change', onControlsChange);
163
+
164
+ function selectView(name) {
165
+ const spec = views[name];
166
+ if (!spec) return;
167
+ controls.target.fromArray(spec.target);
168
+ camera.position.fromArray(spec.eye);
169
+ clampCamera();
170
+ controls.update();
171
+ camera.lookAt(controls.target);
172
+ for (const btn of buttons) {
173
+ if (btn.dataset?.view in views) {
174
+ btn.setAttribute('aria-pressed', String(btn.dataset.view === name));
175
+ }
176
+ }
177
+ if (!onDraw) renderer.render(scene, camera);
178
+ }
179
+
180
+ const buttonListeners = [];
181
+ for (const btn of buttons) {
182
+ if (btn.dataset?.view in views) {
183
+ const onClick = () => selectView(btn.dataset.view);
184
+ btn.addEventListener('click', onClick);
185
+ buttonListeners.push([btn, onClick]);
186
+ }
187
+ }
188
+
189
+ const unbindKeys = bindKeyboardOrbit({ canvas, camera, controls, minDistance, maxDistance });
190
+
191
+ function resize() {
192
+ const dpr = typeof devicePixelRatio === 'number' ? devicePixelRatio : 1;
193
+ renderer.setPixelRatio(Math.min(dpr, maxPixelRatio));
194
+ renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
195
+ camera.aspect = canvas.clientWidth / Math.max(1, canvas.clientHeight);
196
+ camera.fov = THREE.MathUtils.clamp(baseFov / Math.min(camera.aspect, 1), baseFov, maxFov);
197
+ camera.updateProjectionMatrix();
198
+ render();
199
+ }
200
+
201
+ const hasWindow = typeof window !== 'undefined' && typeof window.addEventListener === 'function';
202
+ if (hasWindow) window.addEventListener('resize', resize);
203
+ const first = initialView ?? Object.keys(views)[0];
204
+ if (first) selectView(first);
205
+ resize();
206
+
207
+ function dispose() {
208
+ if (hasWindow) window.removeEventListener('resize', resize);
209
+ controls.removeEventListener('change', onControlsChange);
210
+ for (const [btn, onClick] of buttonListeners) btn.removeEventListener('click', onClick);
211
+ unbindKeys();
212
+ controls.dispose();
213
+ }
214
+
215
+ return { controls, selectView, resize, clampCamera, dispose };
216
+ }
@@ -0,0 +1,95 @@
1
+ import { createPerfBoxState, formatPerfBoxLines } from '../runtime/perf-box-text.js';
2
+
3
+ /** Default typography, padding, width, and ink colour of the on-screen performance box. */
4
+ export const PERF_BOX_DEFAULTS = {
5
+ fontPx: 11,
6
+ linePx: 16,
7
+ padX: 9,
8
+ padY: 6,
9
+ widthPx: 132,
10
+ ink: '#b7f5e6',
11
+ font: 'ui-monospace, Menlo, Consolas, monospace',
12
+ };
13
+
14
+ /**
15
+ * Creates a 2D canvas renderer for the on-screen performance box. Resizes the canvas only when
16
+ * the line count changes and notifies `onResize({ wide, high })` so the page can match its CSS size.
17
+ * Imports nothing from Three.js so it stays light inside a dedicated metrics worker.
18
+ *
19
+ * @param {object} options
20
+ * @param {HTMLCanvasElement | OffscreenCanvas} options.canvas Target 2D canvas.
21
+ * @param {number} [options.density=1] Backing pixel density multiplier.
22
+ * @param {(size: { wide: number, high: number }) => void} [options.onResize] Called with CSS dimensions when line count changes.
23
+ * @param {number} [options.fontPx=11] Font size in CSS pixels.
24
+ * @param {number} [options.linePx=16] Line height in CSS pixels.
25
+ * @param {number} [options.padX=9] Horizontal text padding in CSS pixels.
26
+ * @param {number} [options.padY=6] Vertical box padding in CSS pixels.
27
+ * @param {number} [options.widthPx=132] Box width in CSS pixels.
28
+ * @param {string} [options.ink='#b7f5e6'] Text fill colour.
29
+ * @param {string} [options.font='ui-monospace, Menlo, Consolas, monospace'] Monospace font family stack.
30
+ * @returns {{ draw: (lines: string[]) => void, reset: () => void }}
31
+ */
32
+ export function createPerfBoxRenderer({
33
+ canvas,
34
+ density = 1,
35
+ onResize = () => {},
36
+ fontPx = PERF_BOX_DEFAULTS.fontPx,
37
+ linePx = PERF_BOX_DEFAULTS.linePx,
38
+ padX = PERF_BOX_DEFAULTS.padX,
39
+ padY = PERF_BOX_DEFAULTS.padY,
40
+ widthPx = PERF_BOX_DEFAULTS.widthPx,
41
+ ink = PERF_BOX_DEFAULTS.ink,
42
+ font = PERF_BOX_DEFAULTS.font,
43
+ }) {
44
+ const pen = canvas.getContext('2d');
45
+ let shown = 0;
46
+
47
+ function draw(lines) {
48
+ if (!pen) return;
49
+ if (lines.length !== shown) {
50
+ shown = lines.length;
51
+ const high = padY * 2 + linePx * shown;
52
+ canvas.width = Math.round(widthPx * density);
53
+ canvas.height = Math.round(high * density);
54
+ onResize({ wide: widthPx, high });
55
+ }
56
+ pen.setTransform(density, 0, 0, density, 0, 0);
57
+ pen.clearRect(0, 0, widthPx, padY * 2 + linePx * shown);
58
+ pen.font = `${fontPx}px ${font}`;
59
+ pen.textBaseline = 'middle';
60
+ pen.fillStyle = ink;
61
+ for (let i = 0; i < lines.length; i++) pen.fillText(lines[i], padX, padY + linePx * (i + 0.5));
62
+ }
63
+
64
+ function reset() {
65
+ shown = 0;
66
+ }
67
+
68
+ return { draw, reset };
69
+ }
70
+
71
+ /**
72
+ * Attaches the off-thread performance box message loop to a Web Worker scope (`self` by default).
73
+ * The first message hands over `{ canvas, density }`; subsequent messages carry raw metric samples
74
+ * formatted with `formatPerfBoxLines` and painted onto the `OffscreenCanvas`.
75
+ *
76
+ * @param {object} [options]
77
+ * @param {{ onmessage: ((event: { data: unknown }) => void) | null, postMessage: (msg: unknown) => void }} [options.port=self] Worker global or message port.
78
+ * @param {Partial<typeof PERF_BOX_DEFAULTS>} [options.style] Optional typography and layout overrides.
79
+ */
80
+ export function attachPerfBoxWorker({ port = self, style = {} } = {}) {
81
+ const kept = createPerfBoxState();
82
+ let renderer = null;
83
+ port.onmessage = ({ data }) => {
84
+ if (data.canvas) {
85
+ renderer = createPerfBoxRenderer({
86
+ ...style,
87
+ canvas: data.canvas,
88
+ density: data.density,
89
+ onResize: size => port.postMessage(size),
90
+ });
91
+ } else if (renderer) {
92
+ renderer.draw(formatPerfBoxLines(kept, data));
93
+ }
94
+ };
95
+ }
@@ -0,0 +1,94 @@
1
+ import { createPerfBoxState, formatPerfBoxLines } from '../runtime/perf-box-text.js';
2
+
3
+ /**
4
+ * Page-side controller for the on-screen performance box. On first display it transfers the canvas to a
5
+ * dedicated Web Worker (`OffscreenCanvas`) so formatting and 2D text rendering cost the main render loop
6
+ * nothing; where `transferControlToOffscreen` is unavailable or fails, it writes the exact same formatted
7
+ * lines into `textElement`. Memory estimation runs asynchronously in idle time every `memoryEveryMs`.
8
+ *
9
+ * @param {object} options
10
+ * @param {() => HTMLCanvasElement | null} options.canvas Returns the `<canvas>` element for worker rendering.
11
+ * @param {() => HTMLElement | null} options.textElement Returns the fallback `<pre>` element for text rendering.
12
+ * @param {() => string | URL | null} [options.workerUrl] Module URL of the metrics worker entry script.
13
+ * @param {() => { script: number, meshes: number, textures: number, targets: number } | null} options.measureMemory Computes current memory breakdown in bytes.
14
+ * @param {() => number} [options.workerCount] Number of active background pool workers.
15
+ * @param {number} [options.maxDensity=3] Maximum backing pixel density sent to the metrics worker.
16
+ * @param {number} [options.memoryEveryMs=3000] Milliseconds between idle memory reckonings.
17
+ * @param {number} [options.idleTimeoutMs=1000] Timeout passed to `requestIdleCallback` in milliseconds.
18
+ * @param {object} [options.page=globalThis] Host exposing `window`, `performance`, `navigator`, `devicePixelRatio`, `Worker`, and `setTimeout`.
19
+ * @returns {{ show: (sample: object) => void, dispose: () => void }}
20
+ */
21
+ export function createPerfBox({
22
+ canvas: getCanvas,
23
+ textElement: getTextElement,
24
+ workerUrl = () => null,
25
+ measureMemory,
26
+ workerCount = () => 0,
27
+ maxDensity = 3,
28
+ memoryEveryMs = 3000,
29
+ idleTimeoutMs = 1000,
30
+ page = globalThis,
31
+ }) {
32
+ const kept = createPerfBoxState();
33
+ let worker = null,
34
+ asked = false,
35
+ memory = null,
36
+ nextMemory = 0;
37
+
38
+ function begin() {
39
+ asked = true;
40
+ const canvas = getCanvas?.();
41
+ const url = workerUrl?.();
42
+ if (!canvas?.transferControlToOffscreen || !url) return;
43
+ try {
44
+ const WorkerCtor = page.Worker;
45
+ worker = new WorkerCtor(url, { type: 'module' });
46
+ const drawn = canvas.transferControlToOffscreen();
47
+ const density = Math.min(page.devicePixelRatio || 1, maxDensity);
48
+ worker.postMessage({ canvas: drawn, density }, [drawn]);
49
+ worker.onmessage = ({ data }) => {
50
+ canvas.style.width = data.wide + 'px';
51
+ canvas.style.height = data.high + 'px';
52
+ };
53
+ canvas.hidden = false;
54
+ } catch {
55
+ worker = null; // fall back to plain text rendering on the page
56
+ }
57
+ }
58
+
59
+ function reckonMemory(now) {
60
+ if (now < nextMemory) return;
61
+ nextMemory = now + memoryEveryMs;
62
+ const reckon = () => {
63
+ memory = measureMemory();
64
+ };
65
+ const host = page.window ?? page;
66
+ if (host.requestIdleCallback) host.requestIdleCallback(reckon, { timeout: idleTimeoutMs });
67
+ else page.setTimeout(reckon, 0);
68
+ }
69
+
70
+ function show(sample) {
71
+ if (!asked) begin();
72
+ reckonMemory(page.performance.now());
73
+ sample.memory = memory;
74
+ memory = null;
75
+ const nav = page.navigator;
76
+ // Active threads: main thread + builder pool + metrics worker + active service worker.
77
+ sample.threads = 1 + workerCount() + (worker ? 1 : 0) + (nav?.serviceWorker?.controller ? 1 : 0);
78
+ if (worker) worker.postMessage(sample);
79
+ else {
80
+ const textEl = getTextElement?.();
81
+ if (textEl) textEl.textContent = formatPerfBoxLines(kept, sample).join('\n');
82
+ }
83
+ }
84
+
85
+ function dispose() {
86
+ worker?.terminate?.();
87
+ worker = null;
88
+ asked = false;
89
+ memory = null;
90
+ nextMemory = 0;
91
+ }
92
+
93
+ return { show, dispose };
94
+ }