roamwright 0.61.21 → 0.61.23
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/examples/fliers.html +1 -0
- package/examples/fliers.js +41 -1
- package/examples/town-fittings.js +17 -8
- package/geometry/crawl-shapes.js +86 -1
- package/geometry/crawler-giant-spider.js +100 -0
- package/geometry/harbour-kit.js +178 -8
- package/geometry/plant-garden.js +88 -0
- package/geometry/road-bridges.js +74 -0
- package/geometry/town-garden.js +3 -44
- package/index.js +18 -4
- package/motion/crawler-pack.js +110 -0
- package/package.json +1 -1
- package/rendering/crawler-pack.js +91 -0
- package/scripts/bundle.mjs +17 -5
- package/scripts/vendor.mjs +209 -36
- package/tools/README.md +34 -25
- package/tools/cpu-profile.cjs +117 -0
- package/tools/cpu-profile.test.cjs +31 -1
- package/tools/figure-inspect.cjs +475 -0
- package/tools/figure-inspect.test.cjs +153 -0
- package/tools/geometry-hash.cjs +361 -0
- package/tools/geometry-hash.test.cjs +146 -0
- package/tools/load-audit.cjs +199 -2
- package/tools/load-audit.test.cjs +68 -0
- package/tools/quiet-bench.cjs +202 -0
- package/tools/quiet-bench.test.cjs +91 -0
- package/tools/scene-detail.cjs +355 -0
- package/tools/scene-detail.test.cjs +162 -0
- package/tools/scrub-clear.cjs +191 -0
- package/tools/scrub-clear.test.cjs +100 -0
- package/tools/tree-inspect.cjs +271 -0
- package/tools/tree-inspect.test.cjs +123 -0
- package/tools/world-tour.cjs +223 -0
- package/tools/world-tour.test.cjs +77 -0
package/scripts/vendor.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Self-hosted Three.js and Roamwright engine vendor bundling helpers.
|
|
2
2
|
// Bundles the locked Three.js core module and tree-shaken Roamwright groups (engine, worker, jobs, optional)
|
|
3
3
|
// into `vendor/` so a world update can reuse cached engine and Three.js bundles across deployments.
|
|
4
|
-
import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
4
|
+
import { copyFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
7
7
|
import { walkReach } from './module-graph.mjs';
|
|
@@ -102,6 +102,152 @@ export function pruneEngine(files, vendorRoot = 'vendor/roamwright') {
|
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Assigns non-startup, non-worker optional engine subpaths into separate vendor groups so each land loads only its own
|
|
107
|
+
* optional modules rather than one monolithic `optional` bundle:
|
|
108
|
+
* - `optional-land-<i>`: reached solely by land `i` and imported statically by it
|
|
109
|
+
* - `optional`: statically imported by a land and shared across more than one land
|
|
110
|
+
* - `optional-lazy`: dynamically imported only (scenes, interiors, crawlers, and lazy features)
|
|
111
|
+
*
|
|
112
|
+
* @param {Iterable<string>} all All engine subpaths imported by the world.
|
|
113
|
+
* @param {object} [options]
|
|
114
|
+
* @param {Set<string>} [options.excluded] Engine subpaths already assigned to `worker`, `jobs`, or `engine` startup groups.
|
|
115
|
+
* @param {Array<Set<string>>} [options.lands=[]] Per-land full engine subpath sets (static + dynamic reach).
|
|
116
|
+
* @param {Array<Set<string>>} [options.staticLands] Per-land static engine subpath sets (defaults to `lands`).
|
|
117
|
+
* @returns {Map<string, string>} Map from engine subpath to optional vendor group name.
|
|
118
|
+
*/
|
|
119
|
+
export function partitionOptionalEngine(all, { excluded = new Set(), lands = [], staticLands = lands } = {}) {
|
|
120
|
+
const groups = new Map();
|
|
121
|
+
for (const id of all) {
|
|
122
|
+
if (excluded.has(id)) continue;
|
|
123
|
+
let fullCount = 0;
|
|
124
|
+
let staticCount = 0;
|
|
125
|
+
let firstStaticLand = -1;
|
|
126
|
+
for (let i = 0; i < lands.length; i++) {
|
|
127
|
+
if (lands[i].has(id)) fullCount++;
|
|
128
|
+
}
|
|
129
|
+
for (let i = 0; i < staticLands.length; i++) {
|
|
130
|
+
if (staticLands[i].has(id)) {
|
|
131
|
+
if (firstStaticLand < 0) firstStaticLand = i;
|
|
132
|
+
staticCount++;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (staticCount === 1 && fullCount === 1) groups.set(id, `optional-land-${firstStaticLand}`);
|
|
136
|
+
else if (staticCount > 0) groups.set(id, 'optional');
|
|
137
|
+
else groups.set(id, 'optional-lazy');
|
|
138
|
+
}
|
|
139
|
+
return groups;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function linkEngineGroups({ directory, groups, shaders, revision, rollup, terser, resolveModule }) {
|
|
143
|
+
const entryPrefix = 'engine-group:';
|
|
144
|
+
const groupNames = [...groups.keys()];
|
|
145
|
+
const optionalNames = groupNames.filter(name => name.startsWith('optional'));
|
|
146
|
+
const chunkFor = new Map();
|
|
147
|
+
const bundle = await rollup({
|
|
148
|
+
input: Object.fromEntries(groupNames.map(group => [group, entryPrefix + group])),
|
|
149
|
+
treeshake: 'recommended',
|
|
150
|
+
external: id => id === THREE_URL,
|
|
151
|
+
makeAbsoluteExternalsRelative: false,
|
|
152
|
+
onwarn(warning, warn) {
|
|
153
|
+
if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') warn(warning);
|
|
154
|
+
},
|
|
155
|
+
plugins: [
|
|
156
|
+
{
|
|
157
|
+
name: 'engine-groups',
|
|
158
|
+
resolveId(id, importer) {
|
|
159
|
+
if (id.startsWith(entryPrefix)) return id;
|
|
160
|
+
if (id === 'three') return { id: THREE_URL, external: true };
|
|
161
|
+
if (id.startsWith('roamwright/')) return resolveModule(id);
|
|
162
|
+
if (importer && !importer.startsWith(entryPrefix)) return resolve(dirname(importer), id);
|
|
163
|
+
return null;
|
|
164
|
+
},
|
|
165
|
+
load(id) {
|
|
166
|
+
if (id.startsWith(entryPrefix)) return groups.get(id.slice(entryPrefix.length)).join('\n');
|
|
167
|
+
if (shaders[id] !== undefined) return shaders[id];
|
|
168
|
+
return readFileSync(id, 'utf8');
|
|
169
|
+
},
|
|
170
|
+
buildEnd() {
|
|
171
|
+
// Strict 4-level DAG (shared-worker -> shared-jobs -> shared-engine -> shared-optional)
|
|
172
|
+
// keeps worker chunks free of browser-only modules and avoids shared-chunk fragmentation.
|
|
173
|
+
const reachFrom = group => {
|
|
174
|
+
const seen = new Set();
|
|
175
|
+
const entry = entryPrefix + group;
|
|
176
|
+
if (!groups.has(group)) return seen;
|
|
177
|
+
const queue = [entry];
|
|
178
|
+
while (queue.length) {
|
|
179
|
+
const id = queue.pop();
|
|
180
|
+
if (seen.has(id)) continue;
|
|
181
|
+
seen.add(id);
|
|
182
|
+
const info = this.getModuleInfo(id);
|
|
183
|
+
if (!info) continue;
|
|
184
|
+
for (const dep of info.importedIds) {
|
|
185
|
+
if (dep !== THREE_URL && !seen.has(dep)) queue.push(dep);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return seen;
|
|
189
|
+
};
|
|
190
|
+
const inWorker = reachFrom('worker');
|
|
191
|
+
const inJobs = reachFrom('jobs');
|
|
192
|
+
const inEngine = reachFrom('engine');
|
|
193
|
+
const inOptional = optionalNames.map(name => reachFrom(name));
|
|
194
|
+
for (const id of this.getModuleIds()) {
|
|
195
|
+
if (id.startsWith(entryPrefix) || id === THREE_URL) continue;
|
|
196
|
+
const isW = inWorker.has(id);
|
|
197
|
+
const isJ = inJobs.has(id);
|
|
198
|
+
const isE = inEngine.has(id);
|
|
199
|
+
let optCount = 0;
|
|
200
|
+
for (let i = 0; i < inOptional.length; i++) {
|
|
201
|
+
if (inOptional[i].has(id)) optCount++;
|
|
202
|
+
}
|
|
203
|
+
if (isW && (isJ || isE || optCount > 0)) chunkFor.set(id, 'shared-worker');
|
|
204
|
+
else if (!isW && isJ && (isE || optCount > 0)) chunkFor.set(id, 'shared-jobs');
|
|
205
|
+
else if (!isW && !isJ && isE && optCount > 0) chunkFor.set(id, 'shared-engine');
|
|
206
|
+
else if (!isW && !isJ && !isE && optCount > 1) chunkFor.set(id, 'shared-optional');
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
],
|
|
211
|
+
});
|
|
212
|
+
try {
|
|
213
|
+
const { output } = await bundle.generate({
|
|
214
|
+
format: 'esm',
|
|
215
|
+
entryFileNames: '[name]-[hash].js',
|
|
216
|
+
chunkFileNames: '[name]-[hash].js',
|
|
217
|
+
hashCharacters: 'hex',
|
|
218
|
+
hoistTransitiveImports: false,
|
|
219
|
+
manualChunks: id => chunkFor.get(id),
|
|
220
|
+
plugins: [
|
|
221
|
+
terser({
|
|
222
|
+
ecma: 2022,
|
|
223
|
+
module: true,
|
|
224
|
+
compress: { passes: 2, module: true },
|
|
225
|
+
mangle: { module: true },
|
|
226
|
+
format: { comments: false, preamble: `/* Three.js r${revision} */` },
|
|
227
|
+
maxWorkers: 2,
|
|
228
|
+
}),
|
|
229
|
+
],
|
|
230
|
+
});
|
|
231
|
+
mkdirSync(directory, { recursive: true });
|
|
232
|
+
const files = new Set(output.map(chunk => chunk.fileName));
|
|
233
|
+
const outputs = {};
|
|
234
|
+
for (const chunk of output) {
|
|
235
|
+
const file = join(directory, chunk.fileName);
|
|
236
|
+
const entryPoint = chunk.facadeModuleId?.startsWith(entryPrefix) ? chunk.facadeModuleId : undefined;
|
|
237
|
+
const imports = (paths, kind) =>
|
|
238
|
+
paths.map(path => (files.has(path) ? { path: join(directory, path), kind } : { path, kind, external: true }));
|
|
239
|
+
outputs[file] = {
|
|
240
|
+
entryPoint,
|
|
241
|
+
imports: [...imports(chunk.imports, 'import-statement'), ...imports(chunk.dynamicImports, 'dynamic-import')],
|
|
242
|
+
};
|
|
243
|
+
writeFileSync(file, chunk.code);
|
|
244
|
+
}
|
|
245
|
+
return outputs;
|
|
246
|
+
} finally {
|
|
247
|
+
await bundle.close();
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
105
251
|
/**
|
|
106
252
|
* Bundles the tree-shaken Roamwright engine subpaths used by a world into grouped ESM files under
|
|
107
253
|
* `vendor/roamwright/<version>/`, returning an esbuild rewrite plugin and preload manifest.
|
|
@@ -113,6 +259,9 @@ export function pruneEngine(files, vendorRoot = 'vendor/roamwright') {
|
|
|
113
259
|
* @param {Set<string>} options.startup Engine subpaths required at page startup.
|
|
114
260
|
* @param {Set<string>} options.workerStartup Engine subpaths required at worker startup.
|
|
115
261
|
* @param {Set<string>} options.workerJobs Engine subpaths required by lazy worker jobs.
|
|
262
|
+
* @param {Map<string, string> | null} [options.optionalGroups=null] Optional group names for non-startup, non-worker subpaths.
|
|
263
|
+
* @param {Function | null} [options.rollup=null] Rollup's `rollup` function for DAG chunk linking (falls back to esbuild).
|
|
264
|
+
* @param {Function | null} [options.terser=null] `@rollup/plugin-terser` factory paired with `rollup`.
|
|
116
265
|
* @param {string | number} options.revision Three.js `REVISION` stamped into the bundle banner.
|
|
117
266
|
* @param {(sources: Record<string, string>) => Record<string, string>} options.compactShaders Shader compactor callback.
|
|
118
267
|
* @param {(specifier: string) => string} [options.resolveModule] Module resolver from the consumer root.
|
|
@@ -120,7 +269,19 @@ export function pruneEngine(files, vendorRoot = 'vendor/roamwright') {
|
|
|
120
269
|
*/
|
|
121
270
|
export async function buildRoamwright(
|
|
122
271
|
esbuild,
|
|
123
|
-
{
|
|
272
|
+
{
|
|
273
|
+
all,
|
|
274
|
+
used,
|
|
275
|
+
startup,
|
|
276
|
+
workerStartup,
|
|
277
|
+
workerJobs,
|
|
278
|
+
optionalGroups = null,
|
|
279
|
+
rollup = null,
|
|
280
|
+
terser = null,
|
|
281
|
+
revision,
|
|
282
|
+
compactShaders,
|
|
283
|
+
resolveModule = defaultRequire.resolve,
|
|
284
|
+
},
|
|
124
285
|
) {
|
|
125
286
|
const root = dirname(resolveModule('roamwright'));
|
|
126
287
|
const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
@@ -131,7 +292,13 @@ export async function buildRoamwright(
|
|
|
131
292
|
{
|
|
132
293
|
id,
|
|
133
294
|
prefix: `m${index}_`,
|
|
134
|
-
group: workerStartup.has(id)
|
|
295
|
+
group: workerStartup.has(id)
|
|
296
|
+
? 'worker'
|
|
297
|
+
: workerJobs.has(id)
|
|
298
|
+
? 'jobs'
|
|
299
|
+
: startup.has(id)
|
|
300
|
+
? 'engine'
|
|
301
|
+
: (optionalGroups?.get(id) ?? 'optional'),
|
|
135
302
|
},
|
|
136
303
|
]),
|
|
137
304
|
);
|
|
@@ -162,39 +329,45 @@ export async function buildRoamwright(
|
|
|
162
329
|
const list = m.names.map(name => `${name} as ${m.prefix}${name}`).join(', ');
|
|
163
330
|
groups.get(m.group).push(`export { ${list} } from ${JSON.stringify(m.id)};`);
|
|
164
331
|
}
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
332
|
+
const outputs =
|
|
333
|
+
rollup && terser
|
|
334
|
+
? await linkEngineGroups({ directory, groups, shaders, revision, rollup, terser, resolveModule })
|
|
335
|
+
: (
|
|
336
|
+
await esbuild.build({
|
|
337
|
+
entryPoints: [...groups.keys()].map(group => ({ in: 'engine-group:' + group, out: group })),
|
|
338
|
+
outdir: directory,
|
|
339
|
+
entryNames: '[name]-[hash]',
|
|
340
|
+
chunkNames: 'shared-[hash]',
|
|
341
|
+
banner: { js: `/* Three.js r${revision} */` },
|
|
342
|
+
format: 'esm',
|
|
343
|
+
target: 'es2022',
|
|
344
|
+
bundle: true,
|
|
345
|
+
splitting: true,
|
|
346
|
+
treeShaking: true,
|
|
347
|
+
minify: true,
|
|
348
|
+
legalComments: 'none',
|
|
349
|
+
metafile: true,
|
|
350
|
+
plugins: [
|
|
351
|
+
{
|
|
352
|
+
name: 'engine-groups',
|
|
353
|
+
setup(build) {
|
|
354
|
+
build.onLoad({ filter: /\.js$/ }, args =>
|
|
355
|
+
shaders[args.path] === undefined ? undefined : { contents: shaders[args.path] },
|
|
356
|
+
);
|
|
357
|
+
build.onResolve({ filter: /^engine-group:/ }, args => ({
|
|
358
|
+
path: args.path.slice('engine-group:'.length),
|
|
359
|
+
namespace: 'engine-group',
|
|
360
|
+
}));
|
|
361
|
+
build.onLoad({ filter: /.*/, namespace: 'engine-group' }, args => ({
|
|
362
|
+
contents: groups.get(args.path).join('\n'),
|
|
363
|
+
resolveDir: root,
|
|
364
|
+
}));
|
|
365
|
+
build.onResolve({ filter: /^three$/ }, () => ({ path: THREE_URL, external: true }));
|
|
366
|
+
},
|
|
367
|
+
},
|
|
368
|
+
],
|
|
369
|
+
})
|
|
370
|
+
).metafile.outputs;
|
|
198
371
|
const entries = new Map();
|
|
199
372
|
for (const [file, output] of Object.entries(outputs)) {
|
|
200
373
|
if (output.entryPoint) entries.set(output.entryPoint.slice('engine-group:'.length), file);
|
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`)
|
|
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`),
|
|
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`
|
|
84
|
-
| `
|
|
85
|
-
|
|
|
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()`. |
|
package/tools/cpu-profile.cjs
CHANGED
|
@@ -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
|
+
});
|