roamwright 0.56.0 → 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.
package/README.md CHANGED
@@ -30,7 +30,7 @@ npm resolves the Three.js peer in a new project. Roamwright targets Three.js **0
30
30
 
31
31
  ## Examples
32
32
 
33
- Browse all seventeen examples on the [live showcase](https://enestaylan.github.io/roamwright/).
33
+ Browse all eighteen examples on the [live showcase](https://enestaylan.github.io/roamwright/).
34
34
 
35
35
  | Live example | What the example shows | Source |
36
36
  | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------- |
@@ -51,6 +51,7 @@ Browse all seventeen examples on the [live showcase](https://enestaylan.github.i
51
51
  | [Figures](https://enestaylan.github.io/roamwright/examples/figure.html?seed=7) | Sculpted procedural characters from plain look specs — faces, hair, clothing, cloaks and custom weapons, near and far. | [figure.js](examples/figure.js) |
52
52
  | [A baked land](https://enestaylan.github.io/roamwright/examples/land.html?seed=7) | One height sheet baked row by row with erosion, coast, river ford, banked road, cliff-faced tel, quarry and upland mere. | [land.js](examples/land.js) |
53
53
  | [Island](https://enestaylan.github.io/roamwright/examples/island.html?seed=42) | Fractal terrain shapes a coastline, sandy coves, weathered boulders and coastal pines in turquoise shallows. | [island.js](examples/island.js) |
54
+ | [Pacing and measuring](https://enestaylan.github.io/roamwright/examples/pacing.html?seed=42) | Device-aware presets, ground render order, frame-pacing watch and a live performance box over a coastal valley. | [pacing.js](examples/pacing.js) |
54
55
 
55
56
  ### Run locally
56
57
 
@@ -0,0 +1,100 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="theme-color" content="#152c2c" />
7
+ <title>Pacing and measuring · Roamwright</title>
8
+ <link rel="stylesheet" href="./showcase.css" />
9
+ <style>
10
+ aside#perf-panel {
11
+ position: absolute;
12
+ top: 62px;
13
+ right: clamp(10px, 1.8vw, 22px);
14
+ z-index: 2;
15
+ padding: 6px 8px;
16
+ border: 1px solid #f7edcf48;
17
+ border-radius: 0.45rem;
18
+ background: #0f2324e0;
19
+ font:
20
+ 11px/1.45 ui-monospace,
21
+ Menlo,
22
+ Consolas,
23
+ monospace;
24
+ color: #d9f3ea;
25
+ pointer-events: auto;
26
+ }
27
+ aside#perf-panel .panel-head {
28
+ display: flex;
29
+ justify-content: space-between;
30
+ gap: 10px;
31
+ margin-bottom: 4px;
32
+ padding-bottom: 4px;
33
+ border-bottom: 1px solid #f7edcf28;
34
+ color: #f4e8cb;
35
+ font-size: 11px;
36
+ }
37
+ aside#perf-panel pre {
38
+ margin: 0;
39
+ font: inherit;
40
+ color: #b7f5e6;
41
+ }
42
+ aside#perf-panel pre:empty {
43
+ display: none;
44
+ }
45
+ </style>
46
+ <script type="importmap">
47
+ {
48
+ "imports": {
49
+ "three": "../node_modules/three/build/three.module.js",
50
+ "three/addons/": "../node_modules/three/examples/jsm/",
51
+ "roamwright": "../index.js",
52
+ "roamwright/": "../"
53
+ }
54
+ }
55
+ </script>
56
+ </head>
57
+ <body>
58
+ <canvas
59
+ tabindex="0"
60
+ aria-label="A sunlit coastal valley with timber-framed cottages, wooded hills, and a live performance box"
61
+ ></canvas>
62
+ <header>
63
+ <a class="back" href="../index.html"><span aria-hidden="true">←</span> Roamwright</a>
64
+ <div class="meta">
65
+ <a class="source" href="https://github.com/enestaylan/roamwright/blob/main/examples/pacing.js">Source</a>
66
+ <form method="get">
67
+ <label for="seed">Seed</label>
68
+ <input id="seed" name="seed" type="number" step="1" min="-2147483648" max="2147483647" value="42" required />
69
+ <button type="submit" title="Rebuild valley with this seed" aria-label="Rebuild valley with this seed">→</button>
70
+ </form>
71
+ </div>
72
+ </header>
73
+ <aside id="perf-panel" aria-label="Live performance readout">
74
+ <div class="panel-head">
75
+ <span id="device-tag">desktop · quality</span>
76
+ <span id="preset-tag">high</span>
77
+ </div>
78
+ <pre id="perf-text"></pre>
79
+ </aside>
80
+ <footer>
81
+ <div class="caption">
82
+ <h1>Pacing and measuring</h1>
83
+ <p>Device-aware presets, ground render order, frame-pacing monitor, and a live performance box over a coastal valley.</p>
84
+ </div>
85
+ <div class="tools">
86
+ <div class="views" role="group" aria-label="Camera viewpoint">
87
+ <button type="button" data-view="valley" aria-pressed="true">Valley</button>
88
+ <button type="button" data-view="village" aria-pressed="false">Village</button>
89
+ <button type="button" data-view="overlook" aria-pressed="false">Overlook</button>
90
+ </div>
91
+ <div class="views" role="group" aria-label="Quality preset">
92
+ <button type="button" data-preset="low" aria-pressed="false">Low</button>
93
+ <button type="button" data-preset="medium" aria-pressed="false">Medium</button>
94
+ <button type="button" data-preset="high" aria-pressed="true">High</button>
95
+ </div>
96
+ </div>
97
+ </footer>
98
+ <script type="module" src="./pacing.js"></script>
99
+ </body>
100
+ </html>
@@ -0,0 +1,305 @@
1
+ import * as THREE from 'three';
2
+ import {
3
+ createDaylightSky,
4
+ createHouseKitMaterials,
5
+ createHouseKitMeshes,
6
+ createOrbitCamera,
7
+ createDeviceQuality,
8
+ createHouseKit,
9
+ createPerfBox,
10
+ createPerfWatch,
11
+ createQualityFit,
12
+ createQualityStore,
13
+ createSimpleWater,
14
+ groundRenderOrder,
15
+ readDevice,
16
+ resolveDevicePresets,
17
+ } from 'roamwright';
18
+ import { sstep } from 'roamwright/math/scalar.js';
19
+ import { createDiagnosticLog } from 'roamwright/runtime/diagnostic-log.js';
20
+ import { estimateMemory } from 'roamwright/rendering/memory-estimate.js';
21
+ import { initExample, makeRollingGround } from './stage.js';
22
+ import { scatterTrees } from './stage-kits.js';
23
+
24
+ const { canvas, renderer, camera, scene, worldGroup, seed, random, noise, hash, shapes } = initExample({
25
+ fallbackSeed: 42,
26
+ fov: 40,
27
+ });
28
+
29
+ const device = readDevice(window);
30
+ const BASE_PRESETS = {
31
+ low: { shadow: 1024, treeScale: 0.65, dprCap: 1.25 },
32
+ medium: { shadow: 1024, treeScale: 0.85, dprCap: 1.75 },
33
+ high: { shadow: 2048, treeScale: 1, dprCap: 2 },
34
+ };
35
+ const PRESETS = resolveDevicePresets(BASE_PRESETS, device, {
36
+ medium: { dprCap: 1.5 },
37
+ low: { dprCap: 1.15 },
38
+ });
39
+
40
+ // Gently rising amphitheatre valley opening onto a calm sunlit cove.
41
+ function ground(x, z) {
42
+ const cove = Math.hypot(x + 28, z - 44);
43
+ const shore = sstep(22, 62, cove);
44
+ const ridge = sstep(38, 125, Math.hypot(x - 8, z + 14));
45
+ const hills = 15 * noise.fbm(x * 0.014, z * 0.014, 4, 13) + 6 * noise.ridged(x * 0.01, z * 0.01, 3, 29);
46
+ return -3.2 * (1 - shore) + shore * (1.2 + ridge * hills + 0.6 * noise.fbm(x * 0.04, z * 0.04, 3, 7));
47
+ }
48
+
49
+ const sandCol = new THREE.Color(0xd5c49c),
50
+ grassCol = new THREE.Color(0x6d7f4f),
51
+ meadowCol = new THREE.Color(0x8a9560),
52
+ rockCol = new THREE.Color(0x7c796f);
53
+ const terrain = makeRollingGround({
54
+ size: 420,
55
+ segs: 150,
56
+ heightAt: ground,
57
+ colorAt: (x, y, z, up, out) => {
58
+ const g = noise.fbm(x * 0.045, z * 0.045, 3, 5);
59
+ out.copy(sandCol).lerp(grassCol, sstep(0.6, 2.5, y + g * 0.6));
60
+ out.lerp(meadowCol, sstep(2.5, 9, y) * 0.45 * g);
61
+ out.lerp(rockCol, Math.max(1 - sstep(0.68, 0.9, up), sstep(11, 17, y)));
62
+ out.multiplyScalar(0.86 + 0.24 * noise.vnoise(x * 0.18, z * 0.18, 17));
63
+ },
64
+ });
65
+ terrain.renderOrder = groundRenderOrder(device);
66
+ worldGroup.add(terrain);
67
+
68
+ const { mesh: water, timeUniform: waterTime } = createSimpleWater({
69
+ width: 680,
70
+ depth: 680,
71
+ segs: 96,
72
+ level: 0,
73
+ depthAt: (x, z) => Math.max(0, -ground(x, z)),
74
+ shallowColor: 0x62a9a1,
75
+ deepColor: 0x1e5a6d,
76
+ opacity: 0.92,
77
+ });
78
+ worldGroup.add(water);
79
+
80
+ // Hillside cottages built from Roamwright's house kit.
81
+ const styles = {
82
+ cottage: {
83
+ material: 'wall',
84
+ storey: 2.9,
85
+ timber: 0.55,
86
+ jetty: 0.25,
87
+ shutters: 0.6,
88
+ shops: 0.2,
89
+ balconies: 0.2,
90
+ windowW: 0.85,
91
+ windowH: 1.35,
92
+ frame: 0x4c3726,
93
+ door: 0x362419,
94
+ trim: 0xc2b69e,
95
+ },
96
+ };
97
+ const houseKit = createHouseKit({ shapes, styles });
98
+ const linear = hex => new THREE.Color(hex).toArray();
99
+ const walls = [0xdac9a8, 0xcab48e, 0xe2d6bc, 0xc2aa84],
100
+ roofs = [0x824a38, 0x5d4b40, 0x945d3c, 0x6b4738];
101
+ const lots = [
102
+ [-6, -9, 8.2, 6.4, 2, 'gable', 0.25],
103
+ [7, -11, 7.6, 6.0, 2, 'hip', -0.18],
104
+ [18, -6, 7.2, 5.6, 1, 'gable', -0.55],
105
+ [-16, -16, 8.0, 6.2, 2, 'hip', 0.42],
106
+ [2, -22, 9.0, 6.6, 2, 'gable', 0.1],
107
+ [14, -21, 6.8, 6.8, 3, 'tower', -0.25],
108
+ [-5, -29, 7.8, 6.0, 1, 'gable', 0.3],
109
+ ];
110
+ const houseSpecs = lots
111
+ .map(([bx, bz, w, d, storeys, form, rot], i) => {
112
+ const ox = bx + (random() - 0.5) * 4;
113
+ const oz = bz + (random() - 0.5) * 4;
114
+ const y = ground(ox, oz);
115
+ if (y < 0.8) return null;
116
+ return {
117
+ x: ox,
118
+ y: y - 0.25,
119
+ z: oz,
120
+ w,
121
+ d,
122
+ h: storeys * 3.0 + random() * 0.6,
123
+ n: storeys,
124
+ rot: rot + (random() - 0.5) * 0.35,
125
+ rise: 3.0,
126
+ form,
127
+ style: 'cottage',
128
+ col: linear(walls[(i + Math.abs(seed)) % walls.length]),
129
+ rc: linear(roofs[(i + Math.abs(seed)) % roofs.length]),
130
+ brick: linear(0xa37658),
131
+ party: [0, 0, 0],
132
+ seed: seed * 31 + i * 17,
133
+ };
134
+ })
135
+ .filter(Boolean);
136
+ createHouseKitMeshes({ materials: createHouseKitMaterials({ roughness: 0.9 }) }).kitMeshes(
137
+ houseKit.housesFromSpecs(houseSpecs).kits,
138
+ worldGroup,
139
+ );
140
+
141
+ const treeGroup = new THREE.Group();
142
+ worldGroup.add(treeGroup);
143
+ scatterTrees({
144
+ worldGroup: treeGroup,
145
+ noise,
146
+ hash,
147
+ seed,
148
+ random,
149
+ groundAt: ground,
150
+ attempts: 220,
151
+ maxPerSpecies: 40,
152
+ scaleRange: [0.42, 0.34],
153
+ sample: () => {
154
+ const x = (random() - 0.5) * 190;
155
+ const z = (random() - 0.5) * 190;
156
+ if (ground(x, z) < 1.2 || Math.hypot(x - 3, z + 16) < 28) return null;
157
+ return [x, z];
158
+ },
159
+ });
160
+
161
+ const { sun } = createDaylightSky({
162
+ scene,
163
+ renderer,
164
+ noise,
165
+ sky: {
166
+ zenith: [0.22, 0.47, 0.74],
167
+ horizon: [0.84, 0.89, 0.88],
168
+ sunDir: [-0.65, 0.4, 0.64],
169
+ },
170
+ sunPosition: [-75, 48, 64],
171
+ shadowRadius: 72,
172
+ shadowFar: 220,
173
+ normalBias: 0.05,
174
+ fogColor: 0xcadbe0,
175
+ fogDensity: 0.0022,
176
+ });
177
+
178
+ // Device description, quality fit, perf watch, and off-thread performance box.
179
+ const state = { mode: 'play', quality: 'high', frame: 0 };
180
+ const log = createDiagnosticLog({ storageKey: 'roamwright-example:pacing-log' });
181
+ const store = createQualityStore('roamwright-example-pacing', { device, query: new URLSearchParams(location.search) });
182
+ const { deviceQuality } = createDeviceQuality({ renderer, device });
183
+
184
+ const deviceTag = document.getElementById('device-tag');
185
+ const presetTag = document.getElementById('preset-tag');
186
+ const presetButtons = Array.from(document.querySelectorAll('[data-preset]'));
187
+ deviceTag.textContent = `${device.kind} · ${device.aim}`;
188
+
189
+ function applyQuality(name) {
190
+ const preset = PRESETS[name] ?? PRESETS.medium;
191
+ state.quality = name;
192
+ presetTag.textContent = name;
193
+ for (const btn of presetButtons) btn.setAttribute('aria-pressed', String(btn.dataset.preset === name));
194
+ sun.castShadow = preset.shadow > 0;
195
+ if (preset.shadow > 0 && sun.shadow.mapSize.x !== preset.shadow) {
196
+ sun.shadow.mapSize.set(preset.shadow, preset.shadow);
197
+ sun.shadow.map?.dispose();
198
+ sun.shadow.map = null;
199
+ }
200
+ treeGroup.traverse(child => {
201
+ if (child.isInstancedMesh) {
202
+ child.userData.fullCount ??= child.count;
203
+ child.count = Math.max(1, Math.round(child.userData.fullCount * preset.treeScale));
204
+ }
205
+ });
206
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, preset.dprCap));
207
+ }
208
+
209
+ const fit = createQualityFit({
210
+ state,
211
+ post: { on: false },
212
+ cardBlocks: () => false,
213
+ cardDone: () => Promise.resolve({ at: performance.now(), prompt: true }),
214
+ store,
215
+ deviceQuality,
216
+ applyQuality,
217
+ warmShaders() {},
218
+ emit() {},
219
+ noteLog: log.noteLog,
220
+ adaptiveResolution: false,
221
+ });
222
+ fit.startQuality();
223
+ fit.holdQualityFor('demo', true);
224
+
225
+ for (const btn of presetButtons) {
226
+ btn.addEventListener('click', () => fit.chooseQuality(btn.dataset.preset));
227
+ }
228
+
229
+ const perfWatch = createPerfWatch({
230
+ noteLog: log.noteLog,
231
+ beforeLogRead: log.beforeLogRead,
232
+ isActive: () => !document.hidden,
233
+ subject: () => state.quality,
234
+ });
235
+ perfWatch.startFrameWatch();
236
+
237
+ const perfBox = createPerfBox({
238
+ canvas: () => null,
239
+ textElement: () => document.getElementById('perf-text'),
240
+ measureMemory: () => estimateMemory(scene, { targets: [sun.shadow.map] }),
241
+ workerCount: () => 0,
242
+ });
243
+
244
+ const views = {
245
+ valley: { eye: [-42, 24, 52], target: [4, 4, -10] },
246
+ village: { eye: [-20, 9.5, 10], target: [6, 5, -12] },
247
+ overlook: { eye: [36, 32, -48], target: [-6, 3, 4] },
248
+ };
249
+
250
+ const rig = createOrbitCamera({
251
+ camera,
252
+ canvas,
253
+ renderer,
254
+ scene,
255
+ views,
256
+ initialView: 'valley',
257
+ groundAt: (px, pz) => Math.max(0, ground(px, pz)),
258
+ minClearance: 1.5,
259
+ minDistance: 12,
260
+ maxDistance: 150,
261
+ onDraw: () => {},
262
+ });
263
+
264
+ const clock = new THREE.Timer();
265
+ let lastFrame = 0,
266
+ accSeconds = 0,
267
+ accFrames = 0,
268
+ accScript = 0;
269
+
270
+ function animate(now) {
271
+ requestAnimationFrame(animate);
272
+ clock.update();
273
+ waterTime.value = clock.getElapsed();
274
+ if (!lastFrame) {
275
+ lastFrame = now;
276
+ rig.clampCamera();
277
+ renderer.render(scene, camera);
278
+ return;
279
+ }
280
+ const rawMs = now - lastFrame;
281
+ lastFrame = now;
282
+ const began = performance.now();
283
+ rig.clampCamera();
284
+ renderer.render(scene, camera);
285
+ const scriptMs = performance.now() - began;
286
+ state.frame++;
287
+ perfWatch.watchFrame(rawMs, scriptMs);
288
+ accSeconds += rawMs / 1000;
289
+ accFrames++;
290
+ accScript += scriptMs;
291
+ if (accSeconds >= 0.5) {
292
+ perfBox.show({
293
+ seconds: accSeconds,
294
+ frames: accFrames,
295
+ scriptMs: accScript,
296
+ cardMs: null,
297
+ wide: renderer.domElement.width,
298
+ high: renderer.domElement.height,
299
+ });
300
+ accSeconds = 0;
301
+ accFrames = 0;
302
+ accScript = 0;
303
+ }
304
+ }
305
+ requestAnimationFrame(animate);
package/index.js CHANGED
@@ -142,7 +142,7 @@ export { createCrowdBatches } from './rendering/crowd-batches.js';
142
142
  export { createCrowdUpdater, registerCrowd } from './rendering/crowd-update.js';
143
143
  export { createCrowdSystem } from './rendering/crowd-system.js';
144
144
 
145
- // ── Effects, audio & runtime ─────────────────────────────────────────────
145
+ // ── Effects, audio, pacing & runtime ─────────────────────────────────────
146
146
  export { createFireLightWatch } from './rendering/fire-light-watch.js';
147
147
  export { createEffectsFrame, syncEffectsUniforms } from './rendering/effects-frame.js';
148
148
  export { createRippleRingMaterial, createWaterRises, fishGeometry } from './rendering/effects-water-rises.js';
@@ -152,3 +152,15 @@ export { createSoundscape } from './runtime/soundscape.js';
152
152
  export { createStrideFoley } from './runtime/foley-strides.js';
153
153
  export { createScriptFoley } from './runtime/foley-script.js';
154
154
  export { createPool } from './runtime/pool.js';
155
+ export { describeDevice, readDevice } from './runtime/device.js';
156
+ export { choosePostPipeline, createDeviceQuality, groundRenderOrder, resolveDevicePresets } from './runtime/device-quality.js';
157
+ export { LEVELS, createQualityStore } from './runtime/quality-store.js';
158
+ export { createQualityFit } from './runtime/quality-fit.js';
159
+ export { createSteadyFrames } from './runtime/steady-frames.js';
160
+ export { createFramePacingMonitor } from './runtime/frame-pacing.js';
161
+ export { createPerfWatch, formatLongFrameAttribution, formatLongFrameMessage } from './runtime/perf-watch.js';
162
+ export { createPerfBoxState, formatPerfBoxLines } from './runtime/perf-box-text.js';
163
+ export { createPerfBox } from './rendering/perf-box.js';
164
+ export { PERF_BOX_DEFAULTS, attachPerfBoxWorker, createPerfBoxRenderer } from './rendering/perf-box-worker.js';
165
+ export { createFrameSampler } from './runtime/perf-probe.js';
166
+ export { flyProbeRoute, runSelfProbe } from './rendering/perf-probe.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "keywords": [
6
6
  "threejs",
@@ -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
+ }