roamwright 0.61.20 → 0.61.22

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 (43) hide show
  1. package/README.md +13 -12
  2. package/examples/scenes.html +54 -0
  3. package/examples/scenes.js +594 -0
  4. package/geometry/projectile-shapes.js +85 -0
  5. package/index.js +50 -0
  6. package/motion/fallen-mount.js +63 -0
  7. package/motion/melee-combat.js +328 -0
  8. package/motion/melee-cuts.js +395 -0
  9. package/motion/melee-duels.js +142 -0
  10. package/motion/melee-exchange-creatures.js +86 -0
  11. package/motion/melee-exchange.js +498 -0
  12. package/motion/melee-reactions.js +147 -0
  13. package/motion/prop-contact.js +87 -0
  14. package/package.json +1 -1
  15. package/rendering/blade-trails.js +128 -0
  16. package/rendering/scene-beams.js +486 -0
  17. package/rendering/scene-coverage.js +500 -0
  18. package/rendering/scene-markers.js +421 -0
  19. package/rendering/scene-projectiles.js +395 -0
  20. package/rendering/scene-props.js +383 -0
  21. package/rendering/scene-shots.js +199 -0
  22. package/runtime/foley-surface.js +79 -0
  23. package/runtime/scene-script.js +137 -0
  24. package/runtime/scene-zones.js +117 -0
  25. package/tools/README.md +34 -25
  26. package/tools/cpu-profile.cjs +117 -0
  27. package/tools/cpu-profile.test.cjs +31 -1
  28. package/tools/figure-inspect.cjs +475 -0
  29. package/tools/figure-inspect.test.cjs +153 -0
  30. package/tools/geometry-hash.cjs +361 -0
  31. package/tools/geometry-hash.test.cjs +146 -0
  32. package/tools/load-audit.cjs +199 -2
  33. package/tools/load-audit.test.cjs +68 -0
  34. package/tools/quiet-bench.cjs +202 -0
  35. package/tools/quiet-bench.test.cjs +91 -0
  36. package/tools/scene-detail.cjs +355 -0
  37. package/tools/scene-detail.test.cjs +162 -0
  38. package/tools/scrub-clear.cjs +191 -0
  39. package/tools/scrub-clear.test.cjs +100 -0
  40. package/tools/tree-inspect.cjs +271 -0
  41. package/tools/tree-inspect.test.cjs +123 -0
  42. package/tools/world-tour.cjs +223 -0
  43. package/tools/world-tour.test.cjs +77 -0
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Scene script coordinate resolution and step-analysis helpers: resolves anchor-relative positions,
3
+ * named places, `['ground', offset]` heights, continuous walks, prop-carried moves, and blast wear.
4
+ * Pure runtime module with zero Three.js or DOM dependencies.
5
+ * @module
6
+ */
7
+
8
+ const DEFAULT_WALKS_ON = 0.15;
9
+
10
+ /**
11
+ * Resolves a scene height specification relative to `anchorY`, ground height, or a named place.
12
+ * Accepts a numeric offset from `anchorY`, `'ground'`, a named place key, or `['ground' | place, offset]`.
13
+ * @param {number | string | [string, number]} value Height specification from a scene script.
14
+ * @param {number} anchorY Scene anchor world Y height.
15
+ * @param {number} x World X coordinate used when sampling `'ground'`.
16
+ * @param {number} z World Z coordinate used when sampling `'ground'`.
17
+ * @param {(x: number, z: number) => number} groundAt Ground height sampler.
18
+ * @param {(name: string) => number | { y: number }} [resolveNamed] Named-place lookup.
19
+ * @returns {number} Resolved world Y coordinate in metres.
20
+ */
21
+ export function resolveSceneY(value, anchorY, x, z, groundAt, resolveNamed) {
22
+ if (Array.isArray(value)) {
23
+ const base = value[0] === 'ground' ? groundAt(x, z) : resolveSceneY(value[0], anchorY, x, z, groundAt, resolveNamed);
24
+ return base + (value[1] || 0);
25
+ }
26
+ if (typeof value === 'string') {
27
+ if (value === 'ground') return groundAt(x, z);
28
+ const place = resolveNamed?.(value);
29
+ return typeof place === 'number' ? place : place.y;
30
+ }
31
+ return anchorY + value;
32
+ }
33
+
34
+ /**
35
+ * Resolves a scene position specification into `out` (`{ x, y, z }`): a special `'@…'` target,
36
+ * an actor id (at chest height `y + height * 0.72`), or an anchor-relative `[dx, ySpec, dz]` triple.
37
+ * @param {string | [number, number | string | [string, number], number]} spec Position specification.
38
+ * @param {{ x: number, y: number, z: number }} anchor Scene anchor world position.
39
+ * @param {Record<string, { x: number, y: number, z: number, height: number }>} actors Actor table by id.
40
+ * @param {(x: number, z: number) => number} groundAt Ground height sampler.
41
+ * @param {(name: string) => number | { y: number }} [resolveNamed] Named-place lookup.
42
+ * @param {(name: string, out: { x: number, y: number, z: number }) => boolean} [resolveSpecial] Handler for special string targets (e.g. `'@…'`).
43
+ * @param {{ x: number, y: number, z: number, set?: Function }} out Destination vector or coordinate object.
44
+ * @returns {{ x: number, y: number, z: number }} The populated `out` object.
45
+ */
46
+ export function resolveScenePos(spec, anchor, actors, groundAt, resolveNamed, resolveSpecial, out) {
47
+ if (typeof spec === 'string') {
48
+ if (resolveSpecial && resolveSpecial(spec, out)) return out;
49
+ const a = actors[spec];
50
+ const x = a.x,
51
+ y = a.y + a.height * 0.72,
52
+ z = a.z;
53
+ if (out.set) return out.set(x, y, z);
54
+ out.x = x;
55
+ out.y = y;
56
+ out.z = z;
57
+ return out;
58
+ }
59
+ const wx = anchor.x + spec[0],
60
+ wz = anchor.z + spec[2],
61
+ wy = resolveSceneY(spec[1], anchor.y, wx, wz, groundAt, resolveNamed);
62
+ if (out.set) return out.set(wx, wy, wz);
63
+ out.x = wx;
64
+ out.y = wy;
65
+ out.z = wz;
66
+ return out;
67
+ }
68
+
69
+ /**
70
+ * Returns true if the same actor has another `'move'` step beginning within `windowSeconds` of
71
+ * `step`'s completion, so locomotion flows smoothly without halting between segments.
72
+ * @param {readonly any[]} steps Chronological scene steps array.
73
+ * @param {number} nextIndex Index of the next step after `step`.
74
+ * @param {readonly any[]} step Current `'move'` step `[time, 'move', actorId, x, z, dur, ...]`.
75
+ * @param {number} [windowSeconds] Maximum gap in seconds to treat as continuous walking (default `0.15`).
76
+ * @returns {boolean} True when the actor continues walking into the next move.
77
+ */
78
+ export function stepWalksOn(steps, nextIndex, step, windowSeconds = DEFAULT_WALKS_ON) {
79
+ const ends = step[0] + step[5];
80
+ for (let i = nextIndex; i < steps.length && steps[i][0] <= ends + windowSeconds; i++) {
81
+ if (steps[i][1] === 'move' && steps[i][2] === step[2] && steps[i][0] >= ends - windowSeconds) return true;
82
+ }
83
+ return false;
84
+ }
85
+
86
+ /**
87
+ * Returns true if a `'move'` step matches the start time and duration of a `'prop' ... 'to'` step
88
+ * (such as passengers carried aboard a moving boat), indicating the actor is carried rather than walking.
89
+ * @param {readonly any[]} steps Scene steps array.
90
+ * @param {readonly any[]} step Current `'move'` step.
91
+ * @returns {boolean} True when carried by a synchronized moving prop.
92
+ */
93
+ export function stepRidesProp(steps, step) {
94
+ for (let i = 0; i < steps.length; i++) {
95
+ const other = steps[i];
96
+ if (other[1] === 'prop' && other[3] === 'to' && Math.abs(other[0] - step[0]) < 0.05 && other[8] === step[5]) return true;
97
+ }
98
+ return false;
99
+ }
100
+
101
+ /**
102
+ * Applies blood splatter, blast scorch, or dust wear to active cast members near a scripted burst.
103
+ * @param {Record<string, object> | null | undefined} cast Scene cast definition map.
104
+ * @param {Record<string, object>} actors Actor table by id.
105
+ * @param {string} kind Burst kind (`'blood'`, `'fire'`, `'dark'`, `'violet'`, `'earth'`, `'dust'`, etc.).
106
+ * @param {any} targetSpec Burst target spec (actor id or position).
107
+ * @param {number} x Burst world X coordinate.
108
+ * @param {number} z Burst world Z coordinate.
109
+ * @param {number} [size] Burst radius scale (default `1`).
110
+ * @param {(actor: object, dust: number, sweat: number, blood: number, scorch: number) => void} [addWear] Wear accumulator callback.
111
+ */
112
+ export function applyBurstWear(cast, actors, kind, targetSpec, x, z, size = 1, addWear = () => {}) {
113
+ if (!cast) return;
114
+ if (kind === 'blood') {
115
+ const direct = typeof targetSpec === 'string' ? actors[targetSpec] : null;
116
+ if (direct) addWear(direct, 0, 0, 0.44, 0);
117
+ for (const id in cast) {
118
+ const c = actors[id];
119
+ if (!c?.active || c === direct) continue;
120
+ const d = Math.hypot(c.x - x, c.z - z);
121
+ if (d < 2.2) addWear(c, 0, 0, 0.18 * (1 - d / 2.2), 0);
122
+ }
123
+ return;
124
+ }
125
+ const scorchBlast = kind === 'fire' || kind === 'dark' || kind === 'violet',
126
+ dustBlast = kind === 'earth' || kind === 'dust';
127
+ if (!scorchBlast && !dustBlast) return;
128
+ const reach = Math.max(3, size * 2.4);
129
+ for (const id in cast) {
130
+ const c = actors[id];
131
+ if (!c?.active) continue;
132
+ const d = Math.hypot(c.x - x, c.z - z);
133
+ if (d >= reach) continue;
134
+ const falloff = 1 - d / reach;
135
+ addWear(c, (dustBlast ? 0.34 : 0.14) * falloff, 0.04 * falloff, 0, scorchBlast ? 0.46 * falloff : 0);
136
+ }
137
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Scene anchor resolution, multi-zone pre-streaming collector, and caption timing helpers.
3
+ * Pure runtime module with zero Three.js or DOM dependencies.
4
+ * @module
5
+ */
6
+
7
+ /**
8
+ * Default minimum distance in metres between distinct scene camera or actor zones queued for pre-streaming.
9
+ */
10
+ export const DEFAULT_ZONE_STRIDE = 90;
11
+
12
+ /**
13
+ * Resolves a scene's world anchor into `out` (`{ x, y, z }`) from either a named place (with
14
+ * optional opening offset `ev.off`) or the scene space's origin.
15
+ * @param {object} ev Scene event record with `space`, optional `at`, and optional `off`.
16
+ * @param {string | null | undefined} key Optional override place key (e.g. from an `'anchor'` step).
17
+ * @param {Record<string, { origin: { x: number, z: number }, ground: (x: number, z: number) => number }>} spaces Map of spaces by id.
18
+ * @param {(name: string) => { x: number, z: number }} resolveNamed Named-place lookup.
19
+ * @param {{ x: number, y: number, z: number }} out Destination anchor object.
20
+ * @returns {{ x: number, y: number, z: number }} The populated `out` object.
21
+ */
22
+ export function resolveSceneAnchor(ev, key, spaces, resolveNamed, out) {
23
+ const sp = spaces[ev.space];
24
+ if (!ev.at && !key) {
25
+ const o = sp.origin;
26
+ out.x = o.x;
27
+ out.z = o.z;
28
+ out.y = sp.ground(o.x, o.z);
29
+ return out;
30
+ }
31
+ const p = resolveNamed(key || ev.at),
32
+ off = key ? null : ev.off;
33
+ out.x = p.x + (off ? off[0] : 0);
34
+ out.z = p.z + (off ? off[1] : 0);
35
+ out.y = sp.ground(out.x, out.z);
36
+ return out;
37
+ }
38
+
39
+ /**
40
+ * Collects distinct `(x, z)` zones visited by a scene's opening anchor, secondary `'anchor'` shifts,
41
+ * `'place'`/`'move'` actor marks, and camera track keyframes spaced at least `stride` metres apart.
42
+ * @param {object} ev Scene event record with `steps` and `cam`.
43
+ * @param {{ x: number, z: number }} openingAnchor Opening world anchor.
44
+ * @param {(key: string, out: { x: number, y: number, z: number }) => { x: number, y: number, z: number }} resolveAnchor Resolves a secondary anchor key.
45
+ * @param {number} [stride] Minimum separation in metres between queued zones (default `90`).
46
+ * @returns {[number, number][]} Array of `[x, z]` zone coordinates.
47
+ */
48
+ export function collectSceneZones(ev, openingAnchor, resolveAnchor, stride = DEFAULT_ZONE_STRIDE) {
49
+ const zones = [[openingAnchor.x, openingAnchor.z]];
50
+ const zoneAnchor = { x: 0, y: 0, z: 0 };
51
+ const addZone = (x, z) => {
52
+ if (!Number.isFinite(x) || !Number.isFinite(z)) return;
53
+ for (let i = 0; i < zones.length; i++) if (Math.hypot(x - zones[i][0], z - zones[i][1]) < stride) return;
54
+ zones.push([x, z]);
55
+ };
56
+ let ax = openingAnchor.x,
57
+ az = openingAnchor.z;
58
+ const anchors = [[0, ax, az]];
59
+ for (const s of ev.steps ?? []) {
60
+ if (s[1] === 'anchor') {
61
+ resolveAnchor(s[2], zoneAnchor);
62
+ ax = zoneAnchor.x;
63
+ az = zoneAnchor.z;
64
+ anchors.push([s[0], ax, az]);
65
+ addZone(ax, az);
66
+ } else if (s[1] === 'place' || s[1] === 'move') addZone(ax + s[3], az + s[4]);
67
+ }
68
+ let ai = 0;
69
+ for (const k of ev.cam ?? []) {
70
+ while (ai + 1 < anchors.length && anchors[ai + 1][0] <= k[0]) ai++;
71
+ addZone(anchors[ai][1] + k[1], anchors[ai][2] + k[3]);
72
+ }
73
+ return zones;
74
+ }
75
+
76
+ /**
77
+ * Pre-streams ambient figures and near settlement/set detail across every zone a scene visits.
78
+ * @param {object} ev Scene event record.
79
+ * @param {{ x: number, z: number }} openingAnchor Opening world anchor.
80
+ * @param {object} options
81
+ * @param {(key: string, out: { x: number, y: number, z: number }) => { x: number, y: number, z: number }} options.resolveAnchor Secondary anchor resolver.
82
+ * @param {(x: number, z: number) => number} options.groundAt Ground height sampler for the scene's space.
83
+ * @param {(spaceId: string, x: number, y: number, z: number) => void} [options.orderSeenFrom] Orders ambient cast visible from a zone point.
84
+ * @param {(spaceId: string, x: number, z: number) => Promise<any> | null | undefined} [options.nearDetailAt] Requests near settlement/set detail at `(x, z)`.
85
+ * @param {number} [options.stride] Minimum zone spacing in metres (default `90`).
86
+ * @returns {Promise<any[]> | null} Combined promise for pending detail loads, or `null` when nothing async was queued.
87
+ */
88
+ export function prepareSceneZones(
89
+ ev,
90
+ openingAnchor,
91
+ { resolveAnchor, groundAt, orderSeenFrom, nearDetailAt, stride = DEFAULT_ZONE_STRIDE },
92
+ ) {
93
+ const zones = collectSceneZones(ev, openingAnchor, resolveAnchor, stride);
94
+ const waits = [];
95
+ for (let i = 0; i < zones.length; i++) {
96
+ const [zx, zz] = zones[i];
97
+ orderSeenFrom?.(ev.space, zx, groundAt(zx, zz) + 2, zz);
98
+ const detail = nearDetailAt?.(ev.space, zx, zz);
99
+ if (detail) waits.push(detail);
100
+ }
101
+ return waits.length ? Promise.all(waits) : null;
102
+ }
103
+
104
+ /**
105
+ * Returns the active caption index (`-1` before `leadIn`) sharing a scene's duration equally across `count` captions.
106
+ * @param {number} elapsed Scene elapsed time in seconds.
107
+ * @param {number} duration Scene total duration in seconds.
108
+ * @param {number} count Number of caption lines.
109
+ * @param {number} [leadIn] Opening delay in seconds before the first caption appears (default `1.6`).
110
+ * @param {number} [margin] Combined lead-in/out margin subtracted from duration (default `2.4`).
111
+ * @returns {number} Active caption index in `-1 .. count - 1`.
112
+ */
113
+ export function captionIndexAt(elapsed, duration, count, leadIn = 1.6, margin = 2.4) {
114
+ if (count <= 0 || elapsed < leadIn) return -1;
115
+ const slot = (duration - margin) / count;
116
+ return Math.min(count - 1, Math.floor((elapsed - leadIn) / slot));
117
+ }
package/tools/README.md CHANGED
@@ -23,12 +23,19 @@ const { renewShaders, renewalFlags, saltFor } = require('roamwright/tools/shader
23
23
  | `speed-guard.cjs` | Fixed-view frame, load, and memory speed-guard runner (`runSpeedGuard`) and YAML baseline comparison (`compareSpeedGuardFiles`). |
24
24
  | `frame-parts.cjs` | Per-point frame cost breakdown: pass list and draw-call makers, shader cuts, moving delta, and per-material hide gains (`measureFrameParts`, `parseFramePartsArgs`). |
25
25
  | `frame-bench.cjs` | Single-page preset-figure toggles (`runPresetParts`), headless phone preset/memory cost (`runPhoneCost`), and uncapped vsync-off loop timing (`runUncapped`). |
26
- | `cpu-profile.cjs` | Shared CDP V8 CPU profiler helpers (`startCpuProfile`, `stopCpuProfile`, `summarizeCpuProfile`, `findBusyStretches`) and startup profile runners (`runStartupProfile`, `runInclusiveProfile`). |
26
+ | `cpu-profile.cjs` | Shared CDP V8 CPU profiler helpers (`startCpuProfile`, `stopCpuProfile`, `summarizeCpuProfile`, `findBusyStretches`), startup profile runners (`runStartupProfile`, `runInclusiveProfile`), and post-change / arrival jump profiling (`runJumpProfile`). |
27
27
  | `program-census.cjs` | WebGL program census: hooks shader links, driver waits, first draws, main-thread stalls, and near-duplicate shader twins (`observePrograms`, `runProgramCensus`). |
28
28
  | `program-census-report.cjs` | Human-readable console formatter for `program-census.cjs` results (`reportProgramCensus`). |
29
29
  | `first-draws.cjs` | First-draw pipeline audit: records framebuffer formats, post-entry `(program, target format)` pairs, long frames, `--finish` GL call timings, `--profile`, and `--trace` (`watchDraws`, `runFirstDraws`). |
30
30
  | `shader-arrival.cjs` | Fresh and repeat visit shader-arrival and late-compile audits (`observeShaderArrival`, `verifyShaderArrival`, `runShaderArrival`, `runLateCompiles`). |
31
- | `load-audit.cjs` | Step-by-step load timing (`runReady`), stalled-load diagnostics (`runLoadDiag`), and invalid WebGL program watch (`runGlWatch`). |
31
+ | `load-audit.cjs` | Step-by-step load timing (`runReady`), stalled-load diagnostics (`runLoadDiag`), invalid WebGL program watch (`runGlWatch`), first-visit terrain-shaping timing (`runShapeTiming`), and cold throttled scene-set fetch timing (`runColdSetFetch`). |
32
+ | `world-tour.cjs` | Multi-land, interior-vision, and scene smoke tour runner (`runWorldTour`) that visits configured stops in one session and tags page/console errors by stage. |
33
+ | `quiet-bench.cjs` | Quiet-machine full benchmark runner (`runQuietBench`): measures first and repeat load times, post-GC heap/backing memory, GPU renderer, fixed-view `perfTest()`, and opening-view `stageTimes()`. |
34
+ | `geometry-hash.cjs` | In-browser geometry and terrain-bake hashing runners: worker-baked height lattice readback (`runGroundHash`), crowd batch & standard hashing (`runCrowdHash`), skinned figure hashing (`runFigureHash`), and full cast & mount hashing (`runBeastHash`). |
35
+ | `tree-inspect.cjs` | Instanced tree inspection and wood benchmark runners: four-distance open-side stills of the nearest tree of a kind (`runTreeLook`) and GPU `bench()` across the densest 100 m square (`runTreeBench`). |
36
+ | `figure-inspect.cjs` | Character, crowd, and head-sheet inspection runners: five-angle stills of a character at home (`runPersonLook`), street-level crowd stills (`runCrowdLook`), and multi-actor head contact sheets (`runHeadSheet`). |
37
+ | `scene-detail.cjs` | Scene close-up inspection runners: close-up hand/grip tracking (`runHandLook`) and troop standard-bearer tracking (`runBearerLook`). |
38
+ | `scrub-clear.cjs` | Ground-cover clearing disc check (`runScrubClear`): shoots a nearby bush before and after pressing a clearing disc and asserts it cleared. |
32
39
  | `memory-audit.cjs` | Worker heap polling (`runWorkerMemory`), live typed-array allocation tracking (`runHeldArrays`), multi-run collected heap checks (`runHeapRuns`), and CDP sampling heap attribution (`runHeapWho`, `summarizeSamplingProfile`). |
33
40
  | `look-stats.cjs` | Photo statistics of a frame's RGBA pixels (clipped and crushed shares, saturation, contrast), warnings against thresholds, and drift against a kept baseline. Runs in Node and, handed over as text, inside a page. |
34
41
  | `scene-run.cjs` | Shared scene playback helpers (`seekSceneInPage`, `startSceneInPage`, `readyPageForSceneInPage`, `releaseLoopInPage`, `parseSceneSpec`), single-scene still capture (`captureSceneStills`), shadow half-width sampling (`measureSceneShadow`), and full-duration contact-strip watching (`watchScenes`). |
@@ -60,26 +67,28 @@ Their tests are `tools/*.test.cjs`, run by `npm test`.
60
67
 
61
68
  Headless tools talk to a world's built page through a single global object whose name is passed to `createPageDriver({ debug: '<NAME>' })` (`window[debug]`). A world exposes the fields and methods below so every engine tool works without hardcoding world-specific globals:
62
69
 
63
- | Member | Role |
64
- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
65
- | `state` | `{ mode, quality, measuring, frame, debug }`: `mode` becomes `'play'` when the land is ready; `'inspect'` detaches the camera for stills/benchmarks. |
66
- | `loadTimes` | Array of `[stepName, ms]` tuples recorded during startup, with numeric `.ready` property holding total time from entry to ready in milliseconds. |
67
- | `log()` / `clearLog()` | Reads or clears the page's diagnostic log entries (`{ t, kind, text, n, ctx }`, where `kind` is `'error'`, `'warn'`, `'perf'`, or `'note'`). |
68
- | `bench(n)` | Async GPU-fenced benchmark of `n` frames returning `{ ms, cpu, update, draw, fps, calls, tris, px }`. |
69
- | `stageTimes()` | Optional async pass breakdown returning `{ whole, script, mirror, shadows, bloom }`. |
70
- | `perfTest(options)` | Optional async fixed-view benchmark suite returning per-view `{ view, ms, fps, cpu, update, draw, calls, tris, mirror }`. |
71
- | `step(dt)` | Advances simulation deterministically by `dt` seconds while `state.measuring` holds the animation loop. |
72
- | `draw()` | Renders one frame immediately while `state.measuring` holds the animation loop. |
73
- | `memory()` | Returns script and GPU memory usage summary (geometries, textures, buffers, heap). |
74
- | `clearCamera()` | Nudges an `inspect`-mode camera clear of any solid obstacle; returns truthy when moved. |
75
- | `holdSize(w, h, pr)` / `holdQuality(flag)` | Locks viewport pixel dimensions and disables automatic quality fitting during measurements. |
76
- | `chooseQuality(preset)` / `quality` | Switches active quality preset and exposes the live preset configuration object. |
77
- | `scene`, `camera`, `renderer`, `THREE`, `post` | Core Three.js scene graph, active camera, WebGLRenderer, Three namespace, and post-processing handle. |
78
- | `env`, `windU`, `mirror`, `player`, `space` | Environment (`time`, `flow`, `sunDir`), wind uniforms (`uWindDrift`), planar reflection handle, player pose, and active space (`ground(x, z)`, `id`). |
79
- | `placePlayer(x, z, yaw)`, `setFly(flag)` | Teleports the visitor and toggles flight mode. |
80
- | `quarters`, `CONFIG` | Streamed settlement quarters (`.job` status) and world catalog (`CONFIG.events` array of `{ id, n, book, space, dur, chapter, title, who, cast }`). |
81
- | `director` | Scene player state: `{ ev, ready, preparing, ending, t, paused, A }`: active event, readiness/transition flags, playback clock `t` (seconds), pause flag for benchmarks, and world anchor `A` (`{ x, z }`). |
82
- | `startScene(ev, fromUi)` / `endScene()` | Starts a catalog event scene (`state.mode` becomes `'scene'`) and ends it cleanly back to `state.mode === 'play'`. |
83
- | `actors`, `spaces` | Live actor registry by id (`{ id, active, height, x, z, group, chest, head }`) and space registry by id (`{ ground(x, z) }`) used by scene watching and visibility audits. |
84
- | `perf`, `partTimes()` | Live frame metrics (`{ fps, scriptMs, last }`) and per-part hiding breakdown (`{ parts, members }`, built on `rendering/part-costs.js`) for scene cost analysis. |
85
- | Self-measuring probe (`?probe[=<mode>]`) | Optional query-parameter self-probe for devices without DevTools/Playwright control (e.g. mobile browsers), writing results to `log()`. |
70
+ | Member | Role |
71
+ | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
72
+ | `state` | `{ mode, quality, measuring, frame, debug }`: `mode` becomes `'play'` when the land is ready; `'inspect'` detaches the camera for stills/benchmarks. |
73
+ | `loadTimes` | Array of `[stepName, ms]` tuples recorded during startup, with numeric `.ready` property holding total time from entry to ready in milliseconds. |
74
+ | `log()` / `clearLog()` | Reads or clears the page's diagnostic log entries (`{ t, kind, text, n, ctx }`, where `kind` is `'error'`, `'warn'`, `'perf'`, or `'note'`). |
75
+ | `bench(n)` | Async GPU-fenced benchmark of `n` frames returning `{ ms, cpu, update, draw, fps, calls, tris, px }`. |
76
+ | `stageTimes()` | Optional async pass breakdown returning `{ whole, script, mirror, shadows, bloom }`. |
77
+ | `perfTest(options)` | Optional async fixed-view benchmark suite returning per-view `{ view, ms, fps, cpu, update, draw, calls, tris, mirror }`. |
78
+ | `step(dt)` | Advances simulation deterministically by `dt` seconds while `state.measuring` holds the animation loop. |
79
+ | `draw()` | Renders one frame immediately while `state.measuring` holds the animation loop. |
80
+ | `memory()` | Returns script and GPU memory usage summary (geometries, textures, buffers, heap). |
81
+ | `clearCamera()` | Nudges an `inspect`-mode camera clear of any solid obstacle; returns truthy when moved. |
82
+ | `holdSize(w, h, pr)` / `holdQuality(flag)` | Locks viewport pixel dimensions and disables automatic quality fitting during measurements. |
83
+ | `chooseQuality(preset)` / `quality` | Switches active quality preset and exposes the live preset configuration object. |
84
+ | `scene`, `camera`, `renderer`, `THREE`, `post` | Core Three.js scene graph, active camera, WebGLRenderer, Three namespace, and post-processing handle. |
85
+ | `env`, `windU`, `mirror`, `player`, `space` | Environment (`time`, `flow`, `sunDir`), wind uniforms (`uWindDrift`), planar reflection handle, player pose, and active space (`ground(x, z)`, `id`). |
86
+ | `placePlayer(x, z, yaw)`, `setFly(flag)` | Teleports the visitor and toggles flight mode. |
87
+ | `quarters`, `CONFIG` | Streamed settlement quarters (`.job` status) and world catalog (`CONFIG.events` array of `{ id, n, book, space, dur, chapter, title, who, cast }`). |
88
+ | `director` | Scene player state: `{ ev, ready, preparing, ending, t, paused, A }`: active event, readiness/transition flags, playback clock `t` (seconds), pause flag for benchmarks, and world anchor `A` (`{ x, z }`). |
89
+ | `startScene(ev, fromUi)` / `endScene()` | Starts a catalog event scene (`state.mode` becomes `'scene'`) and ends it cleanly back to `state.mode === 'play'`. |
90
+ | `actors`, `spaces`, `crowds`, `P` | Live actor registry by id (`{ id, active, height, x, z, group, chest, head }`), space registry by id (`{ ground(x, z) }`), active crowd lists, and named anchor points (`P`) used by scene watching, visibility audits, and figure/crowd inspectors. |
91
+ | `enterVision(id)` / `leaveVision()` | Optional interior/vision space transitions used by `world-tour.cjs`. |
92
+ | `terrainHeight(x, z)`, `pressGrass(n)` | Optional primary-space terrain height sampler (used by `geometry-hash.cjs` and `figure-inspect.cjs`) and ground-cover clearing disc setter (used by `scene-detail.cjs`). |
93
+ | `perf`, `partTimes()` | Live frame metrics (`{ fps, scriptMs, last }`) and per-part hiding breakdown (`{ parts, members }`, built on `rendering/part-costs.js`) for scene cost analysis. |
94
+ | Self-measuring probe (`?probe[=<mode>]`) | Optional query-parameter self-probe for devices without DevTools/Playwright control (e.g. mobile browsers), writing results to `log()`. |
@@ -264,10 +264,127 @@ async function runInclusiveProfile(
264
264
  await browser.close();
265
265
  }
266
266
 
267
+ /**
268
+ * Parses CLI arguments for `runJumpProfile`: `<address> <script|arrive> [seconds=8] [stretches=3]`.
269
+ *
270
+ * @param {string[]} [argv=[]]
271
+ * @returns {{ address: string, script: string, arrive: boolean, seconds: number, stretches: number }}
272
+ */
273
+ function parseJumpArgs(argv = []) {
274
+ const [address = '', script = '', seconds = 8, stretches = 3] = argv;
275
+ return {
276
+ address,
277
+ script,
278
+ arrive: script === 'arrive',
279
+ seconds: +seconds || 8,
280
+ stretches: +stretches || 3,
281
+ };
282
+ }
283
+
284
+ /**
285
+ * Clears the diagnostic log on `window[debug]` before a sudden state change is profiled.
286
+ * Passed to `page.evaluate`; must remain self-contained.
287
+ *
288
+ * @param {{ debug: string }} arg
289
+ */
290
+ function clearLogInPage({ debug }) {
291
+ window[debug].clearLog();
292
+ }
293
+
294
+ /**
295
+ * Runs a caller-supplied expression inside the page (using indirect eval in global scope).
296
+ * Passed to `page.evaluate`; must remain self-contained.
297
+ *
298
+ * @param {{ script: string }} arg
299
+ */
300
+ function evalScriptInPage({ script }) {
301
+ (0, eval)(script);
302
+ }
303
+
304
+ /**
305
+ * Reads the performance mark timestamp recorded when the title overlay became hidden (`arrive` mode).
306
+ * Passed to `page.evaluate`; must remain self-contained.
307
+ *
308
+ * @param {{ markName?: string }} [arg]
309
+ * @returns {number}
310
+ */
311
+ function readEnteredMarkInPage({ markName = 'jump:entered' } = {}) {
312
+ return performance.getEntriesByName(markName)[0].startTime;
313
+ }
314
+
315
+ /**
316
+ * Profiles busy CPU stretches after a sudden state change (running `script` in the page) or right after
317
+ * entering the world (`script === 'arrive'`).
318
+ *
319
+ * @param {object} driver Page driver from `createPageDriver`.
320
+ * @param {object} [options]
321
+ * @param {string[]} [options.argv=[]] Raw CLI arguments (`<address> <script|arrive> [seconds=8] [stretches=3]`).
322
+ * @param {string} [options.titleElementId='title'] DOM element id whose `'gone'` class marks arrival.
323
+ * @param {number} [options.settleMs=6000] Wait before invoking `script` in non-arrive mode.
324
+ * @returns {Promise<Array<{ busyMs: number, atMs: number, incl: Array<[string, number]>, own: Array<[string, number]> }>>}
325
+ */
326
+ async function runJumpProfile(driver, { argv = [], titleElementId = 'title', settleMs = 6000 } = {}) {
327
+ const { address, script, arrive, seconds, stretches } = parseJumpArgs(argv);
328
+ const debug = driver.debug;
329
+ const browser = await driver.chromium.launch({ executablePath: driver.shell, ...driver.GPU });
330
+ const ctx = await browser.newContext({ viewport: { width: 1400, height: 800 } });
331
+ await driver.applyStorage(ctx, { quality: 'high', muted: '1' });
332
+ const page = await ctx.newPage();
333
+ page.on('pageerror', e => console.log('PAGE ERROR', e.message.slice(0, 300)));
334
+ const cdp = await ctx.newCDPSession(page);
335
+ if (arrive) {
336
+ await page.addInitScript(id => {
337
+ document.addEventListener('DOMContentLoaded', () => {
338
+ const title = document.getElementById(id);
339
+ if (!title) return;
340
+ const observer = new MutationObserver(() => {
341
+ if (!title.classList.contains('gone')) return;
342
+ performance.mark('jump:entered');
343
+ observer.disconnect();
344
+ });
345
+ observer.observe(title, { attributes: true, attributeFilter: ['class'] });
346
+ });
347
+ }, titleElementId);
348
+ await cdp.send('Performance.enable');
349
+ await startCpuProfile(cdp, 200);
350
+ }
351
+ await driver.enter(page, driver.routeUrl(address));
352
+ if (!arrive) {
353
+ await page.waitForTimeout(settleMs);
354
+ await page.evaluate(clearLogInPage, { debug });
355
+ await startCpuProfile(cdp, 200);
356
+ await page.evaluate(evalScriptInPage, { script });
357
+ }
358
+ await page.waitForTimeout(seconds * 1000);
359
+ const profile = await stopCpuProfile(cdp);
360
+ let offsetMs = 0;
361
+ if (arrive) {
362
+ const { metrics } = await cdp.send('Performance.getMetrics');
363
+ const navigation = metrics.find(m => m.name === 'NavigationStart').value;
364
+ const entered = await page.evaluate(readEnteredMarkInPage, { markName: 'jump:entered' });
365
+ offsetMs = navigation * 1000 + entered - profile.startTime / 1000;
366
+ }
367
+ const found = findBusyStretches(profile, { offsetMs, limit: stretches });
368
+ for (const s of found) {
369
+ console.log(`== ${Math.round(s.busyMs)} ms busy, ${Math.round(s.atMs)} ms after the change`);
370
+ console.log('-- inside (ms, itself and what it calls)');
371
+ for (const [k, ms] of s.incl.slice(0, 22)) console.log(String(Math.round(ms)).padStart(6), k);
372
+ console.log('-- own time');
373
+ for (const [k, ms] of s.own.slice(0, 8)) console.log(String(Math.round(ms)).padStart(6), k);
374
+ }
375
+ await driver.closeBrowser(browser);
376
+ return found;
377
+ }
378
+
267
379
  module.exports = {
380
+ clearLogInPage,
381
+ evalScriptInPage,
268
382
  findBusyStretches,
269
383
  formatCallFrame,
384
+ parseJumpArgs,
385
+ readEnteredMarkInPage,
270
386
  runInclusiveProfile,
387
+ runJumpProfile,
271
388
  runStartupProfile,
272
389
  startCpuProfile,
273
390
  stopCpuProfile,
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
  const test = require('node:test');
3
3
  const assert = require('node:assert/strict');
4
- const { findBusyStretches, summarizeCpuProfile } = require('./cpu-profile.cjs');
4
+ const { clearLogInPage, findBusyStretches, parseJumpArgs, readEnteredMarkInPage, summarizeCpuProfile } = require('./cpu-profile.cjs');
5
5
  const { verifyShaderArrival } = require('./shader-arrival.cjs');
6
6
  const { summarizeSamplingProfile } = require('./memory-audit.cjs');
7
7
 
@@ -96,3 +96,33 @@ test('verifyShaderArrival accepts clean 4K arrival and flags draws that link pro
96
96
  process.exitCode = prevExit;
97
97
  }
98
98
  });
99
+
100
+ test('parseJumpArgs and jump in-page helpers talk through window[debug]', () => {
101
+ assert.deepEqual(parseJumpArgs(['location/harbour', 'arrive', '5', '2']), {
102
+ address: 'location/harbour',
103
+ script: 'arrive',
104
+ arrive: true,
105
+ seconds: 5,
106
+ stretches: 2,
107
+ });
108
+ assert.deepEqual(parseJumpArgs(['', 'APP.env.time = 0.2']), {
109
+ address: '',
110
+ script: 'APP.env.time = 0.2',
111
+ arrive: false,
112
+ seconds: 8,
113
+ stretches: 3,
114
+ });
115
+
116
+ let cleared = 0;
117
+ globalThis.window = { APP: { clearLog: () => cleared++ } };
118
+ const origPerf = globalThis.performance;
119
+ globalThis.performance = { getEntriesByName: name => (name === 'jump:entered' ? [{ startTime: 412.5 }] : []) };
120
+ try {
121
+ clearLogInPage({ debug: 'APP' });
122
+ assert.equal(cleared, 1);
123
+ assert.equal(readEnteredMarkInPage({ markName: 'jump:entered' }), 412.5);
124
+ } finally {
125
+ delete globalThis.window;
126
+ globalThis.performance = origPerf;
127
+ }
128
+ });