@wildshard/engine 0.1.19 → 0.1.21

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 (125) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/lint/engine-sides.json +5 -0
  3. package/package.json +5 -2
  4. package/scripts/app-build/gen.ts +11 -0
  5. package/scripts/cell-mem-bench.mjs +2 -0
  6. package/scripts/chaos-proxy-core.mjs +14 -1
  7. package/scripts/chaos-proxy-proof.mjs +22 -0
  8. package/scripts/check-devserver.mjs +1 -1
  9. package/scripts/failmode-cases.d.mts +8 -0
  10. package/scripts/failmode-cases.mjs +97 -0
  11. package/scripts/failmode-proof.mjs +532 -0
  12. package/scripts/grid-crossing-nightly.mjs +5 -4
  13. package/scripts/grid-crossing-report.mjs +5 -2
  14. package/scripts/grid-crossing-tour.mjs +36 -12
  15. package/scripts/grid-crossing-walk-proof.mjs +4 -2
  16. package/scripts/hover-speed-probe.mjs +136 -0
  17. package/scripts/land.mjs +2 -1
  18. package/scripts/loading-flow/benchmax.mjs +34 -11
  19. package/scripts/loading-flow/deskbench.mjs +276 -0
  20. package/scripts/loading-flow/stalls.d.mts +17 -3
  21. package/scripts/loading-flow/stalls.mjs +82 -3
  22. package/scripts/net-lag-proof.mjs +3 -2
  23. package/scripts/nightly-model.ts +9 -6
  24. package/scripts/offline-proof.mjs +7 -1
  25. package/scripts/online-rig.mjs +9 -7
  26. package/scripts/parity/boot-smoke.mjs +13 -2
  27. package/scripts/pin-format.ts +5 -2
  28. package/scripts/pins-reuse.d.mts +1 -0
  29. package/scripts/pins-reuse.mjs +22 -0
  30. package/scripts/release-cook.mjs +109 -0
  31. package/scripts/scratch-dir.mjs +95 -0
  32. package/scripts/scratch-sweep.mjs +182 -0
  33. package/scripts/tsconfig.json +2 -12
  34. package/scripts/vps/harden-prometheus.sh +3 -0
  35. package/scripts/vps/rebuild.sh +35 -9
  36. package/scripts/vps/wildshard-apply.mjs +5 -1
  37. package/scripts/vps/wildshard-config +117 -1
  38. package/scripts/worktree-reap.mjs +54 -8
  39. package/scripts/worktree.mjs +19 -5
  40. package/src/client/engine/anim/rigParser.ts +2 -2
  41. package/src/client/engine/boot/contentRead.ts +54 -5
  42. package/src/client/engine/boot/gpuFiles.ts +3 -3
  43. package/src/client/engine/boot/leaveAfterPaint.ts +4 -1
  44. package/src/client/engine/core/Game.ts +63 -19
  45. package/src/client/engine/core/gpuOnly.ts +10 -0
  46. package/src/client/engine/core/renderBudget.ts +134 -0
  47. package/src/client/engine/core/shadowLayer.ts +18 -0
  48. package/src/client/engine/explore/pick.ts +13 -1
  49. package/src/client/engine/net/predictor.ts +12 -4
  50. package/src/client/engine/net/redial.ts +40 -5
  51. package/src/client/engine/player/TouchControls.ts +3 -2
  52. package/src/client/engine/render/dataLook.ts +70 -7
  53. package/src/client/engine/render/families/pbr.ts +2 -0
  54. package/src/client/engine/render/families/registry.ts +11 -2
  55. package/src/client/engine/render/families/sceneSurface.ts +118 -0
  56. package/src/client/engine/render/look.ts +7 -1
  57. package/src/client/engine/render/precompile.ts +4 -2
  58. package/src/client/engine/render/tiers.ts +4 -1
  59. package/src/client/engine/telemetry/browserErrors.ts +3 -1
  60. package/src/client/engine/ui/ErrorModal.ts +1 -1
  61. package/src/client/engine/ui/Loading.ts +14 -2
  62. package/src/client/engine/ui/errorScreen.ts +51 -9
  63. package/src/client/engine/ui/hoverBoost.ts +31 -4
  64. package/src/client/engine/ui/styles/touch.css +6 -0
  65. package/src/client/engine/world/declaredProps.ts +5 -1
  66. package/src/client/engine/world/skyRig.ts +4 -1
  67. package/src/client/engine/world/terrainTileView.ts +64 -23
  68. package/src/client/game/boot/spawnDownload.ts +44 -6
  69. package/src/client/game/devScene/hook.ts +149 -12
  70. package/src/client/game/devScene/liveLook.ts +21 -0
  71. package/src/client/game/grid/live.ts +47 -10
  72. package/src/client/game/grid/liveSession.ts +25 -6
  73. package/src/client/game/grid/pageEntry.ts +12 -1
  74. package/src/client/game/grid/productInputs.ts +22 -11
  75. package/src/client/game/grid/session.ts +15 -4
  76. package/src/client/game/grid/shardfileFar.ts +13 -2
  77. package/src/client/game/session/finish.ts +4 -1
  78. package/src/client/game/shardfile/client.ts +24 -7
  79. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  80. package/src/client/game/shardfile/clientSource.ts +7 -3
  81. package/src/client/game/shardfile/clientViews.ts +36 -8
  82. package/src/client/game/shardfile/clientWorker.ts +4 -4
  83. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  84. package/src/client/game/shardfile/groundMerge.ts +59 -5
  85. package/src/client/game/shardfile/hybrid.ts +2 -0
  86. package/src/client/game/shardfile/look.ts +1 -1
  87. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  88. package/src/client/game/shardfile/tileContent.ts +1 -1
  89. package/src/client/game/shardfile/tileDriver.ts +38 -11
  90. package/src/client/game/shardfile/wirePage.ts +7 -3
  91. package/src/client/game/shardfile/worldScenes.ts +17 -10
  92. package/src/client/host/online/doctor.ts +20 -7
  93. package/src/client/host/online/doctorView.ts +2 -0
  94. package/src/client/host/online/linkScreens.ts +95 -11
  95. package/src/client/host/online/reconnectStrip.ts +3 -2
  96. package/src/client/host/online/release.ts +87 -16
  97. package/src/client/host/online/releaseScreens.ts +108 -0
  98. package/src/client/host/online/shell.ts +24 -5
  99. package/src/client/host/online/voice.ts +45 -1
  100. package/src/client/host/online/voiceUi.ts +24 -6
  101. package/src/client/host/standalone/shell.ts +37 -1
  102. package/src/server/engine/sim/playerSim.ts +1 -1
  103. package/src/server/game/grid/simulation.ts +12 -6
  104. package/src/server/game/quest/eliteDrops.ts +7 -3
  105. package/src/server/game/riding/nativeTaming.ts +13 -2
  106. package/src/server/host/dedicated/cellHost.ts +21 -2
  107. package/src/server/host/dedicated/cellProtocol.ts +2 -0
  108. package/src/server/host/dedicated/cellWorker.ts +1 -1
  109. package/src/server/host/dedicated/dedicatedRoom.ts +38 -8
  110. package/src/server/host/dedicated/roadRoom.ts +3 -0
  111. package/src/server/host/dedicated/serverMetrics.ts +9 -0
  112. package/src/server/host/dedicated/workerTable.ts +31 -24
  113. package/src/server/host/standalone/gridServer.ts +1 -1
  114. package/src/server/host/standalone/serverHost.ts +56 -10
  115. package/src/server/host/standalone/serverProduct.ts +9 -7
  116. package/src/server/host/standalone/serverRuntime.ts +1 -1
  117. package/src/shared/engine/boot/loadingWaits.ts +10 -2
  118. package/src/shared/engine/core/config.ts +3 -0
  119. package/src/shared/engine/core/framePacing.ts +12 -1
  120. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  121. package/src/shared/engine/player/hoverSpeed.ts +3 -3
  122. package/src/shared/engine/strings.ts +12 -1
  123. package/src/shared/game/devColliders.ts +60 -0
  124. package/src/shared/game/devGameplay.ts +41 -0
  125. package/src/shared/game/grid/rules.ts +12 -0
@@ -7,8 +7,8 @@
7
7
  // picks another; when a cell has no arc left it goes back over crossings that worked (scored too, marked `repeat`), and when none
8
8
  // leads anywhere (a cell it can't leave) it enters again by the title.
9
9
  // Per crossing, from the in-page samples (every 100 ms) and every frame: border to control, the longest run under 90 % of the
10
- // approach speed (slow) and under 0.1 m per 100 ms with the key held (freeze), the time held at an unready neighbour (wall: phase
11
- // preparing or blocked while frozen), the time the cell step screen shows, and frames over 33 and 50 ms within 3 s of the border.
10
+ // approach speed (slow) and under 0.1 m per 100 ms with the key held (freeze), the time held at an unready neighbour (wall: phase preparing, blocked or ready, the last a world built whose entry still prepares, GC6;
11
+ // while frozen), the time the cell step screen shows, and frames over 33 and 50 ms within 3 s of the border.
12
12
  // Not measured: grey stand-ins within 60 m (no reader yet).
13
13
  // scripts/browser-lane.sh node scripts/grid-crossing-tour.mjs --base=https://preview.wildshard.io --out=<dir> [--engine=chromium|webkit]
14
14
  // [--layout=phone] [--arcs=<from>:<to>,…] [--limit=<n crossings>] [--cold] [--lane=<name>] [--hold=<ms>] [--laps=<n>]
@@ -31,7 +31,10 @@ const base = flag('base', '').replace(/\/$/u, ''), out = absolute(flag('out', ''
31
31
  if (!/^https:\/\/preview\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base) || out === absolute('')) throw new Error('usage: grid-crossing-tour.mjs --base=<preview or loopback url> --out=<dir> [--engine=chromium|webkit] [--layout=phone] [--arcs=a:b,…] [--limit=n]');
32
32
  if (engineName !== 'chromium' && engineName !== 'webkit') throw new Error(`No engine ${engineName}`);
33
33
  const limit = Number(flag('limit', '400')), only = flag('arcs', '').split(',').filter(Boolean), cold = process.argv.includes('--cold'), lane = flag('lane', 'opus-gcm2'), hold = Number(flag('hold', '0')), laps = Number(flag('laps', '1'));
34
+ // --viewport=<w>x<h>@<dpr> (desktop): Jake's window is 2992x1434@2 (QA 11-14 row 6)
35
+ const desk = (/^(\d+)x(\d+)@([\d.]+)$/u.exec(flag('viewport', '1440x900@1')) ?? [0, '1440', '900', '1']).slice(1).map(Number);
34
36
  let currentLap = 1;
37
+ const profileFirst = process.argv.includes('--profile'), latency = Number(flag('latency', '0'));
35
38
  mkdirSync(out, { recursive: true });
36
39
  const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
37
40
 
@@ -52,11 +55,12 @@ for (const cell of cells) for (const [dx, dz] of [[1, 0], [-1, 0], [0, 1], [0, -
52
55
  if (next !== undefined) arcs.push({ from: cell.instance, to: next.instance, dx, dz, boost: dx + dz < 0 });
53
56
  }
54
57
  const wanted = only.length === 0 ? arcs : arcs.filter(arc => only.includes(`${arc.from}:${arc.to}`));
55
- const HOME = 'driftwood-isle', HOME_CARD = 'Driftwood Isle', EDGE_IN = 238, LEG_MS = 90_000, STUCK_MS = 1500;
58
+ // --in=<m>: how far inside its cell's edge each walk starts (default 12 m), so a walk from deeper in measures the pre-warm (GC6)
59
+ const HOME = 'driftwood-isle', HOME_CARD = 'Driftwood Isle', EDGE_IN = 250 - Number(flag('in', '12')), LEG_MS = 90_000, STUCK_MS = 1500;
56
60
 
57
61
  /** @type {Record<string, unknown>[]} */
58
62
  const crossings = [];
59
- const result = { lane, base, build, cold, engine: engineName, layout: phone ? 'phone 402x874 touch' : 'desktop 1440x900', at: new Date().toISOString(), arcs: wanted.length, crossings, errors: /** @type {string[]} */ ([]), reloads: 0, reentries: 0, lostPage: /** @type {Record<string, unknown>[]} */ ([]), note: '', untried: /** @type {string[]} */ ([]) };
63
+ const result = { lane, base, build, cold, engine: engineName, layout: phone ? 'phone 402x874 touch' : `desktop ${String(desk[0])}x${String(desk[1])}@${String(desk[2])}`, at: new Date().toISOString(), arcs: wanted.length, crossings, errors: /** @type {string[]} */ ([]), console: /** @type {string[]} */ ([]), reloads: 0, reentries: 0, lostPage: /** @type {Record<string, unknown>[]} */ ([]), note: '', untried: /** @type {string[]} */ ([]) };
60
64
  const save = () => writeFileSync(join(out, `${engineName}-${phone ? 'phone' : 'desktop'}-tour.json`), `${JSON.stringify(result, null, 2)}\n`);
61
65
  const browser = await (engineName === 'webkit' ? webkit : chromium).launch({ headless: true, args: engineName === 'chromium' ? [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist', '--enable-precise-memory-info'] : [] });
62
66
  let code = 1;
@@ -70,14 +74,18 @@ try {
70
74
  await context?.close();
71
75
  context = await browser.newContext(phone ? { viewport: { width: 402, height: 874 }, deviceScaleFactor: 3, isMobile: engineName === 'chromium', hasTouch: true,
72
76
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Mobile/15E148 Safari/604.1', ...cold ? { serviceWorkers: 'block' } : {} }
73
- : { viewport: { width: 1440, height: 900 }, ...cold ? { serviceWorkers: 'block' } : {} });
77
+ : { viewport: { width: desk[0], height: desk[1] }, deviceScaleFactor: desk[2], ...cold ? { serviceWorkers: 'block' } : {} });
74
78
  await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
75
79
  await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
76
80
  await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: phone ? { tier: 'phone', volume: 0 } : { volume: 0 } });
77
81
  page = await context.newPage();
78
82
  if (cold && engineName === 'chromium') await (await context.newCDPSession(page)).send('Network.setCacheDisabled', { cacheDisabled: true });
83
+ // --latency=<ms> (GC6): a CDN's round trip on every request of a loopback page (Chromium), so a local build's fetches cost what a site's do
84
+ if (latency > 0 && engineName === 'chromium') { const cdp = await context.newCDPSession(page); await cdp.send('Network.enable'); await cdp.send('Network.emulateNetworkConditions', { offline: false, latency, downloadThroughput: 25e6, uploadThroughput: 5e6 }); }
79
85
  const opened = page;
80
86
  page.on('pageerror', error => { if (result.errors.length < 20) result.errors.push(error.message.slice(0, 240)); });
87
+ // GC6: the page's own warnings name a stuck entry preparation (`[grid] <cell>: entry preparation on the road`)
88
+ page.on('console', message => { if ((message.type() === 'warning' || message.type() === 'error') && result.console.length < 60) result.console.push(`${message.type()} ${message.text().slice(0, 300)}`); });
81
89
  page.on('framenavigated', frame => { if (frame === opened.mainFrame()) navigations++; });
82
90
  };
83
91
  /** Into the grid by Driftwood's deck card, and the sampler on: at the start, and again when the tour is stranded in a cell it can't leave. */
@@ -107,7 +115,7 @@ try {
107
115
  q.samples.push({ t: Math.round(performance.now() - t0), x: Number(p.position.x.toFixed(2)), y: Number(p.position.y.toFixed(2)), z: Number(p.position.z.toFixed(2)), inside: st.inside,
108
116
  phase: lv?.crossing?.phase, ready: lv?.live?.gameplayReady, loading: st.cellLoading, step: st.cellStep?.step ?? null,
109
117
  // GC6: whether the crossing's target world (colliders and sim) is resident yet, and the world built ahead (GC5)
110
- built: q.target === undefined ? null : lv?.live?.residents?.includes(q.target) === true, ahead: lv?.live?.ahead?.instance ?? null,
118
+ built: q.target === undefined ? null : lv?.live?.residents?.includes(q.target) === true, ahead: lv?.live?.ahead?.instance ?? null, refused: lv?.live?.ahead?.refused ?? null, hy: st.hybrid ?? null, fc: W.__wildshard.world?.game?.frameCount ?? null, deferred: lv?.live?.ahead?.deferred ?? null, env: st.envelopeMB ?? null, pending: lv?.live?.pending ?? null,
111
119
  // GC13: the cells whose worlds the page holds, and what playing costs
112
120
  res: lv?.live?.residents ?? null, mb: st.playingMB ?? null,
113
121
  // GC12: how many closed walls show (only the ones the walker stands at)
@@ -142,6 +150,9 @@ try {
142
150
  const { at_: placed, ok: placedOk } = await place(EDGE_IN);
143
151
  row.placed = { x: placed.x, y: placed.y, z: placed.z, inside: placed.inside };
144
152
  if (!placedOk) { row.why = `not placed on ${arc.from}'s entryway (inside ${String(placed.inside)})`; return row; }
153
+ // --profile (GC6): a CPU profile of the first crossing (Chromium), for what its preparation spends
154
+ const profiler = profileFirst && crossings.length === 1 && engineName === 'chromium' ? await page.context().newCDPSession(page) : null;
155
+ if (profiler !== null) { await profiler.send('Profiler.enable'); await profiler.send('Profiler.setSamplingInterval', { interval: 500 }); await profiler.send('Profiler.start'); row.profileStartPageMs = await page.evaluate(() => performance.now()); }
145
156
  await face(yaw);
146
157
  const t1 = Date.now(), tFrom = (await sample()).t;
147
158
  await page.keyboard.down('KeyW'); if (arc.boost) await page.keyboard.down('ShiftLeft');
@@ -159,13 +170,18 @@ try {
159
170
  controlAt = now; controlT = s.t;
160
171
  // GC14: the page's memory at each control, so the tour doubles as the long-walk soak
161
172
  row.memory = await page.evaluate(() => { const W = /** @type {any} */ (window); let st = null; try { st = W.__wildshard.shard.grid.state(); } catch { /* no grid yet */ }
162
- const perf = /** @type {any} */ (performance); return { playingMB: st?.playingMB ?? null, residentMB: st?.residentMB ?? null, heapMB: perf.memory ? Math.round(perf.memory.usedJSHeapSize / 1048576) : null }; }).catch(() => null);
173
+ // GC13: what the playing cost is made of (the allocator's input per category, MB) and the biggest owners' claims
174
+ let parts = null, owners = null; try { const r = W.__wildshard.shard.grid.residency(); parts = Object.fromEntries(Object.entries(r.cost.input).map(([k, v]) => [k, typeof v === 'number' ? Math.round(v / 1e5) / 10 : v]));
175
+ /** @type {Record<string, number>} */ const by = {}; for (const c of r.claims) { const key = `${String(c.owner)}:${String(c.category)}`; by[key] = (by[key] ?? 0) + (c.accountedBytes ?? c.bytes) / 1e6; }
176
+ owners = Object.fromEntries(Object.entries(by).sort((a, b) => b[1] - a[1]).slice(0, 16).map(([k, v]) => [k, Math.round(v * 10) / 10])); } catch { /* no residency probe */ }
177
+ const perf = /** @type {any} */ (performance); return { playingMB: st?.playingMB ?? null, residentMB: st?.residentMB ?? null, heapMB: perf.memory ? Math.round(perf.memory.usedJSHeapSize / 1048576) : null, parts, owners }; }).catch(() => null);
163
178
  }
164
179
  } else if (now - controlAt > 2500) break;
165
180
  last = s;
166
181
  if (jumps >= 4 && stuckSince !== 0 && now - stuckSince > 10_000) break;
167
182
  }
168
183
  await page.keyboard.up('KeyW'); if (arc.boost) await page.keyboard.up('ShiftLeft');
184
+ if (profiler !== null) { const stopped = await profiler.send('Profiler.stop'); writeFileSync(join(out, `${engineName}-${arc.from}-${arc.to}.cpuprofile`), JSON.stringify(stopped.profile)); await profiler.detach(); }
169
185
  // GC13 `--hold`: stand in the cell reached, so the page can let the cell behind go
170
186
  await sleep(controlAt === 0 ? 400 : Math.max(400, hold));
171
187
  const rows =/** @type {any[]} */ (await page.evaluate(t => /** @type {any} */ (window).__gc3.samples.filter((/** @type {any} */ r) => r.err === undefined && r.t >= t), tFrom));
@@ -191,11 +207,13 @@ try {
191
207
  const border = entered?.t ?? Infinity, near = frames.filter(f => Math.abs((f[0] ?? 0) - border) <= 3000).map(f => f[1] ?? 0);
192
208
  Object.assign(row, { ok: controlAt !== 0, why: controlAt !== 0 ? '' : fell ? `fell off ${arc.from}'s entryway (no ground there)` : entered === undefined ? (roadAt === undefined ? `never left ${arc.from}` : `held on the road (${String(last.phase)})`) : 'in the cell, no control',
193
209
  borderToControlMs: entered === undefined || controlAt === 0 ? null : controlT - entered.t, controlMs: controlAt === 0 ? null : controlAt, approachMps: Number(approach.toFixed(2)),
194
- slowMs: approach > 0 ? longest(s => s.v < approach * 0.9) : null, freezeMs: longest(s => s.v * 0.1 < 0.1), wallMs: sum(s => (s.r.phase === 'preparing' || s.r.phase === 'blocked') && s.v * 0.1 < 0.1),
210
+ slowMs: approach > 0 ? longest(s => s.v < approach * 0.9) : null, freezeMs: longest(s => s.v * 0.1 < 0.1), wallMs: sum(s => (s.r.phase === 'preparing' || s.r.phase === 'blocked' || s.r.phase === 'ready') && s.v * 0.1 < 0.1),
195
211
  stepScreenMs: sum(s => s.r.loading !== null && s.r.loading !== undefined && s.r.loading !== false), over33: near.filter(ms => ms > 33).length, over50: near.filter(ms => ms > 50).length,
196
212
  // GC8: how long each `cell` step stood on the loading screen in this crossing (samples every 100 ms; a build before GC8 reads none)
197
213
  steps: speeds.reduce((/** @type {Record<string, number>} */ onScreen, x) => { if (x.t <= untilT && typeof x.r.step === 'string' && x.r.step !== '') onScreen[x.r.step] = (onScreen[x.r.step] ?? 0) + 100; return onScreen; }, {}),
198
214
  worstFrameMs: Math.max(0, ...near), jumps, lowestY: Math.min(...rows.map(r => r.y)), end: { inside: last.inside, x: last.x, y: last.y, z: last.z, phase: last.phase } });
215
+ // GC6: each crossing keeps its samples (every 500 ms), so its cause can be read from the json
216
+ row.trace = rows.filter((_, i) => i % 5 === 0).map(r => ({ t: r.t - tFrom, x: r.x, z: r.z, inside: r.inside, phase: r.phase, ready: r.ready, step: r.step, built: r.built, ahead: r.ahead, refused: r.refused, hy: r.hy, fc: r.fc, deferred: r.deferred, mb: r.mb, env: r.env, pending: r.pending, res: r.res }));
199
217
  // a failed crossing held on the road boosts back into the cell it left, so the tour goes on from there
200
218
  if (!row.ok && last.inside !== arc.from && last.inside !== arc.to) {
201
219
  await face(yaw + Math.PI); await page.keyboard.down('KeyW'); await page.keyboard.down('ShiftLeft');
@@ -206,15 +224,21 @@ try {
206
224
  // GC8: what preparing the target cost in this window: its `wildshard.prepare:<slug>:<step>` spans (wall ms, developer pages
207
225
  // only), the main thread's long tasks, and the bytes fetched under its shardfile folder (resource timing transfer sizes)
208
226
  const slug = cells.find(cell => cell.instance === arc.to)?.slug ?? arc.to;
209
- Object.assign(row, await page.evaluate(([from, name]) => {
227
+ Object.assign(row, await page.evaluate(([from, name, target]) => {
210
228
  const W = /** @type {any} */ (window), end = performance.now();
211
229
  const spans = performance.getEntriesByType('measure').filter(entry => entry.name.startsWith(`wildshard.prepare:${name}:`) && entry.startTime >= from)
212
230
  .map(entry => [entry.name.slice(`wildshard.prepare:${name}:`.length), Math.round(entry.startTime - from), Math.round(entry.duration)]);
213
231
  const tasks = /** @type {number[][]} */ (W.__gc3.longTasks ?? []).filter(task => (task[0] ?? 0) >= from && (task[0] ?? 0) <= end);
214
232
  const files = /** @type {PerformanceResourceTiming[]} */ (performance.getEntriesByType('resource')).filter(entry => entry.startTime >= from && entry.name.includes(`/${name}/`));
215
- return { prepare: { windowMs: Math.round(end - from), spans: spans.slice(0, 200), longTasks: tasks.length, longTaskMs: tasks.reduce((total, task) => total + (task[1] ?? 0), 0),
216
- files: files.length, bytes: files.reduce((total, entry) => total + (entry.transferSize || 0), 0), decodedBytes: files.reduce((total, entry) => total + (entry.decodedBodySize || 0), 0) }, windowEnd: end };
217
- }, /** @type {[number, string]} */ ([windowStart, slug])).then(({ prepare, windowEnd }) => { lastWindowEnd = windowEnd; return { prepare }; }).catch(() => ({})));
233
+ // GC6: the hybrid hooks run for this cell in the window ([hook, start, ms, outcome]; the grid probe's `hookTimings`, the last 32)
234
+ let hooks = /** @type {unknown[]} */ ([]);
235
+ try { hooks = (W.__wildshard.shard.grid.hookTimings?.()?.completed ?? []).filter((/** @type {any} */ h) => h.start >= from && h.instance === target).map((/** @type {any} */ h) => [h.hook, Math.round(h.start - from), Math.round(h.end - h.start), h.outcome]); } catch { /* no live session */ }
236
+ return { prepare: { windowMs: Math.round(end - from), hooks, spans: spans.slice(0, 200), longTasks: tasks.length, longTaskMs: tasks.reduce((total, task) => total + (task[1] ?? 0), 0),
237
+ files: files.length, bytes: files.reduce((total, entry) => total + (entry.transferSize || 0), 0), decodedBytes: files.reduce((total, entry) => total + (entry.decodedBodySize || 0), 0),
238
+ // GC6: every fetch in the window (at most 3000), as [the path's last folders and its name's first 8, start, ms, transfer bytes, initiator], to see what a preparation waits on
239
+ fetches: (/** @type {PerformanceResourceTiming[]} */ (performance.getEntriesByType('resource'))).filter(entry => entry.startTime >= from)
240
+ .slice(-3000).map(entry => { const parts = new URL(entry.name).pathname.split('/'); return [`${parts.slice(-4, -1).join('/')}/${(parts.at(-1) ?? '').slice(0, 8)}`, Math.round(entry.startTime - from), Math.round(entry.duration), entry.transferSize || 0, entry.initiatorType]; }) }, windowEnd: end };
241
+ }, /** @type {[number, string, string]} */ ([windowStart, slug, arc.to])).then(({ prepare, windowEnd }) => { lastWindowEnd = windowEnd; return { prepare }; }).catch(() => ({})));
218
242
  if (!row.ok || row.wallMs > 0) await page.screenshot({ path: join(out, `${engineName}-${arc.from}-${arc.to}.png`) }).catch(() => undefined);
219
243
  console.log(`${row.ok ? 'ok ' : 'FAIL'} ${arc.from} -> ${arc.to}${arc.boost ? ' boost' : ''}${repeat ? ' (repeat)' : ''} ${JSON.stringify({ why: row.why, b2c: row.borderToControlMs, wall: row.wallMs, freeze: row.freezeMs, over50: row.over50 })}`);
220
244
  return row;
@@ -26,6 +26,8 @@ const phone = process.argv.includes('--layout=phone'), solo = process.argv.inclu
26
26
  // it stands: jump into it, jump along it both ways, and boost-jump into it. A case holds when the page never enters the target
27
27
  // while its crossing is unready and the walker stays on the road, standing; entering once the neighbour is ready is the crossing.
28
28
  const breach = process.argv.includes('--breach');
29
+ // GC6: --viewport=<w>x<h>@<dpr> (desktop): Jake's window is 2992x1434@2 (QA 11-14 row 6)
30
+ const desk = (/^--viewport=(\d+)x(\d+)@([\d.]+)$/u.exec(process.argv.find(arg => arg.startsWith('--viewport=')) ?? '') ?? [0, '1440', '900', '1']).slice(1).map(Number);
29
31
  /** The page's memory now: JS heap (Chromium), the grid's resident and playing MB, the owner ledger's totals, the memory warning. */
30
32
  const MEMORY_READ = `(() => { const api = window.__wildshard; let ledger = null; try { const mem = ${pageMemoryAttributionExpression}; ledger = mem?.totals ? { gpuMB: Math.round(mem.totals.gpu / 1048576), ramMB: Math.round(mem.totals.ram / 1048576) } : null; } catch {}
31
33
  let grid = null; try { const st = api.shard.grid.state(); grid = { inside: st.inside, residentMB: st.residentMB, playingMB: st.playingMB }; } catch {}
@@ -33,7 +35,7 @@ const MEMORY_READ = `(() => { const api = window.__wildshard; let ledger = null;
33
35
  return { heapMB: performance.memory ? Math.round(performance.memory.usedJSHeapSize / 1048576) : null, ledger, grid, memoryWarning: warning !== null && warning.getClientRects().length > 0 }; })()`;
34
36
  /** @param {import('playwright').Browser} b */
35
37
  const newContext = b => b.newContext(phone ? { viewport: { width: 402, height: 874 }, deviceScaleFactor: 3, isMobile: engineName === 'chromium', hasTouch: true,
36
- userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Mobile/15E148 Safari/604.1' } : { viewport: { width: 1440, height: 900 } });
38
+ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0.1 Mobile/15E148 Safari/604.1' } : { viewport: { width: desk[0] ?? 1440, height: desk[1] ?? 900 }, deviceScaleFactor: desk[2] ?? 1 });
37
39
  mkdirSync(out, { recursive: true });
38
40
  /** Driftwood is cell [0, 0]; its same-worker neighbours Pine Hollow [0, 1] (+z, across the island from the spawn at z -194) and Sunscar
39
41
  * [-1, 0] (-x). Far Reach [0, -1] is sky islands: arriving at road height falls below its death floor (GC15b). */
@@ -70,7 +72,7 @@ const rig = served !== '' ? { base: served.replace(/\/$/, ''), close: () => Prom
70
72
  : await openRig({ dist, work, keyFile, pgBin: 'memory:', pgData: '', shard: HOME, more: ['pine-hollow', 'far-reach', 'sunscar-dunes', 'nalati-grasslands'], cells: 'grid', crossing: true, workers });
71
73
  let code = 1, browser = /** @type {import('playwright').Browser | null} */ (null);
72
74
  /** @type {Record<string, unknown>} */
73
- const result = { lane: 'opus-gc15c', engine: engineName, layout: phone ? 'phone 402x874 touch' : 'desktop 1440x900', site: served !== '' ? served : 'local rig, WORLD_CELLS=grid, WORLD_CROSSING=worker, WORLD_WORKERS=2 (staging: Nalati alone, Driftwood with Pine Hollow, Sunscar and Far Reach)' };
75
+ const result = { lane: 'opus-gc15c', engine: engineName, layout: phone ? 'phone 402x874 touch' : `desktop ${String(desk[0])}x${String(desk[1])}@${String(desk[2])}`, site: served !== '' ? served : 'local rig, WORLD_CELLS=grid, WORLD_CROSSING=worker, WORLD_WORKERS=2 (staging: Nalati alone, Driftwood with Pine Hollow, Sunscar and Far Reach)' };
74
76
  try {
75
77
  let open = served !== '' ? { cells: 25 } : null;
76
78
  for (let tries = 0; tries < 300 && open === null; tries++) { open = await fetch(`http://127.0.0.1:${String(WORLD_PORT)}/health`).then(found => found.ok ? found.json() : null).catch(() => null); if (open === null) await sleep(200); }
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ // QA 11-15 row 8 (Jake: "what speed is the hoverboard inside the [zone], what speed is it on the road, what speed is it with boost,
3
+ // what speed is it with boost off … We had agreed upon speeds"): a headless page enters Driftwood, steps on the board (H), and
4
+ // drives straight by real input in the four cases, boost off and on (a double tap of H), inside the shard (its west water, x -235)
5
+ // and on the road's deck west of it (x -281.25). Each case prints the page's measured ground speed (median over its last 1.5 s,
6
+ // from the world feet every 50 ms), the page's own board cap (`hoverCap`), and the corrections the server sent meanwhile (a
7
+ // server that caps lower than the page predicts pulls it back: corrections, and a measured speed under the cap).
8
+ // QA 11-15 row 9: `--shots` also shoots the left edge riding with boost off and on (the HOVER tab on a phone, the tag on desktop).
9
+ // scripts/browser-lane.sh node scripts/hover-speed-probe.mjs --base=<staging, preview or loopback url> --out=<dir> [--layout=phone] [--shots]
10
+ // scripts/browser-lane.sh node scripts/hover-speed-probe.mjs --rig=<app dist>,<work dir>,<key.json> --out=<dir> (engine's loopback
11
+ // world, online-rig.mjs: the built dedicated server, 2 workers, crossing on; the dist stamped for its release file)
12
+ // J205: staging, preview or a loopback page only, never production. Chromium runs headless and muted; the page is closed at the end.
13
+ import { mkdirSync, writeFileSync } from 'node:fs';
14
+ import { join, resolve as absolute } from 'node:path';
15
+ import { chromium } from 'playwright';
16
+ import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
17
+ import { saveFixture } from './debug-settings.mjs';
18
+
19
+ /** @param {string} name @param {string} fallback */
20
+ const flag = (name, fallback) => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
21
+ const rigArg = flag('rig', ''), out = absolute(flag('out', 'tmp/hover-speed-probe')), phone = flag('layout', 'desktop') === 'phone', shots = process.argv.includes('--shots');
22
+ let base = flag('base', '').replace(/\/$/u, '');
23
+ if (rigArg === '' && !/^https:\/\/(staging|preview)\.wildshard\.io$|^http:\/\/127\.0\.0\.1:\d+$/u.test(base)) throw new Error('--base takes staging, preview or a loopback page only: never production (J205)');
24
+ const sleep = (/** @type {number} */ ms) => new Promise(resolve => { setTimeout(resolve, ms); });
25
+ mkdirSync(out, { recursive: true });
26
+
27
+ /** Driftwood is cell [0, 0], so its own metres are the world's. The road's deck is the middle 15 m of the 62.5 m between cells. */
28
+ const ZONE_X = -235, DECK_X = -281.25;
29
+
30
+ let rig = /** @type {{ base: string, close: () => Promise<unknown> } | null} */ (null);
31
+ if (rigArg !== '') {
32
+ const [dist = '', work = '', keyFile = ''] = rigArg.split(',');
33
+ const { openRig, WORLD_PORT } = await import('./online-rig.mjs');
34
+ rig = await openRig({ dist, work: absolute(work), keyFile, pgBin: 'memory:', pgData: '', shard: 'driftwood-isle', more: ['pine-hollow', 'far-reach', 'sunscar-dunes', 'nalati-grasslands'], cells: 'grid', crossing: true, workers: 2 });
35
+ for (let tries = 0; tries < 300 && !(await fetch(`http://127.0.0.1:${String(WORLD_PORT)}/health`).then(found => found.ok).catch(() => false)); tries++) await sleep(200);
36
+ base = rig.base;
37
+ }
38
+ const result = { base, rig: rigArg !== '', layout: phone ? 'phone 402x874@3 touch' : 'desktop 1440x900@1', at: new Date().toISOString(), build: '', cases: /** @type {Record<string, unknown>[]} */ ([]), shots: /** @type {string[]} */ ([]), errors: /** @type {string[]} */ ([]), notes: /** @type {string[]} */ ([]) };
39
+ const browser = await chromium.launch({ headless: true, args: [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] });
40
+ let code = 1, shown = /** @type {import('playwright').Page | null} */ (null);
41
+ try {
42
+ result.build = await fetch(`${base}/version.json`).then(async found => String((await found.json()).build)).catch(() => '');
43
+ const context = await browser.newContext(phone ? { viewport: { width: 402, height: 874 }, deviceScaleFactor: 3, isMobile: true, hasTouch: true } : { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 });
44
+ const page = await context.newPage(); shown = page;
45
+ page.on('pageerror', error => { result.errors.push(error.message.slice(0, 240)); });
46
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
47
+ await saveFixture(context, { scope: 'device', key: 'devMode', data: true });
48
+ await saveFixture(context, { scope: 'global', key: 'settings', merge: true, data: phone ? { tier: 'phone', volume: 0 } : { volume: 0 } });
49
+ await page.goto(`${base}/?mute=1&nolock=1`, { waitUntil: 'load' });
50
+ await page.locator('.ws-main-select').click({ timeout: 120_000 });
51
+ if (await page.locator('#ws-name-box input').waitFor({ timeout: 30_000 }).then(() => true).catch(() => false)) { await page.locator('#ws-name-box input').fill('hoverspeed'); await page.locator('#ws-name-box button[type=submit]').click(); }
52
+ await page.locator('.ws-menu-card').first().waitFor({ state: 'visible', timeout: 30_000 });
53
+ const index = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].findIndex(row => (row.textContent ?? '').includes('Driftwood Isle')));
54
+ if (index < 0) throw new Error('No Driftwood Isle card');
55
+ await page.locator('.ws-menu-dots i').nth(index).click();
56
+ await page.locator('.ws-menu-play').click();
57
+ await page.waitForFunction(() => /** @type {any} */ (window).__wildshard?.shard?.grid?.state?.().live?.live?.gameplayReady === true, undefined, { timeout: 180_000, polling: 100 });
58
+ await sleep(2000);
59
+ await page.getByText('DONE', { exact: true }).click({ timeout: 2000 }).catch(() => undefined);
60
+ await page.evaluate(() => {
61
+ const W = /** @type {any} */ (window), q = W.__hoverSpeed = { samples: /** @type {any[]} */ ([]) };
62
+ setInterval(() => { try {
63
+ const st = W.__wildshard.shard.grid.state(), p = W.__wildshard.world.player, wf = st.live?.live?.worldFeet ?? p.position, wire = W.__workerClient?.();
64
+ q.samples.push({ t: Math.round(performance.now()), x: wf.x, y: wf.y, z: wf.z, inside: st.inside ?? null, cap: typeof p.hoverSpeedLimit === 'function' ? Number(p.hoverSpeedLimit().toFixed(2)) : null, hover: p.hover, boost: p.hoverBoost, corrections: wire?.corrections ?? null });
65
+ } catch (error) { q.samples.push({ err: String(error).slice(0, 160) }); } }, 50);
66
+ });
67
+ const sample = () => page.evaluate(() => { const rows = /** @type {any[]} */ (/** @type {any} */ (window).__hoverSpeed.samples); for (let at = rows.length - 1; at >= 0; at--) if (rows[at].err === undefined) return rows[at]; return undefined; });
68
+ const now = () => page.evaluate(() => Math.round(performance.now()));
69
+ const face = (/** @type {number} */ yaw) => page.evaluate(wanted => { /** @type {any} */ (window).__wildshard.world.player.yaw = wanted; }, yaw);
70
+ /** Steer to (x, z) with W held, turning toward it every 100 ms; true when within 3 m. */
71
+ const driveTo = async (/** @type {number} */ x, /** @type {number} */ z, ms = 60_000) => {
72
+ let near = Infinity;
73
+ await page.keyboard.down('KeyW');
74
+ for (const ends = Date.now() + ms; Date.now() < ends && near > 3; await sleep(100)) { const at = await sample(); near = Math.hypot(at.x - x, at.z - z); await face(Math.atan2(at.x - x, at.z - z)); }
75
+ await page.keyboard.up('KeyW'); await sleep(800);
76
+ return near <= 3;
77
+ };
78
+ // The board and its boost through the player's own toggles (what H and a double tap of H call), each checked before it counts.
79
+ const board = async () => {
80
+ for (let tries = 0; tries < 5 && !(await sample())?.hover; tries++) { await page.evaluate(() => { const p = /** @type {any} */ (window).__wildshard.world.player; if (!p.hover) p.setHover(true); }); await sleep(800); }
81
+ };
82
+ const boost = async (/** @type {boolean} */ on) => {
83
+ await board();
84
+ await page.evaluate(wanted => { /** @type {any} */ (window).__wildshard.world.player.setBoost(wanted); }, on); await sleep(300);
85
+ const at = await sample(); if (!at?.hover || Boolean(at?.boost) !== on) result.notes.push(`boost ${String(on)} did not take: ${JSON.stringify(at)}`);
86
+ };
87
+ /** Hold W facing `yaw` for `ms` and read the case: the median speed over the last 1.5 s (0.25 s steps), the page's cap, corrections. */
88
+ const drive = async (/** @type {string} */ name, /** @type {number} */ x, /** @type {number} */ ms) => {
89
+ const from = await now(), before = await sample();
90
+ // north along the line x, turning back onto it every 100 ms (a board drifts off a held yaw over 200 m)
91
+ await page.keyboard.down('KeyW');
92
+ for (const ends = Date.now() + ms; Date.now() < ends; await sleep(100)) { const at = await sample(); await face(Math.atan2(at.x - x, -40)); }
93
+ await page.keyboard.up('KeyW');
94
+ const rows = /** @type {any[]} */ (await page.evaluate(t => /** @type {any} */ (window).__hoverSpeed.samples.filter((/** @type {any} */ row) => row.err === undefined && row.t >= t), from));
95
+ const last = rows.at(-1), tail = rows.filter(row => row.t >= last.t - 1500), speeds = [];
96
+ for (let i = 0; i < tail.length; i++) { const later = tail.find(row => row.t >= tail[i].t + 250); if (later !== undefined) speeds.push(Math.hypot(later.x - tail[i].x, later.z - tail[i].z) / ((later.t - tail[i].t) / 1000)); }
97
+ speeds.sort((a, b) => a - b);
98
+ const row = { name, speed: Number((speeds[Math.floor(speeds.length / 2)] ?? 0).toFixed(2)), top: Number((speeds.at(-1) ?? 0).toFixed(2)), cap: last.cap, hover: last.hover, boost: last.boost,
99
+ inside: last.inside, at: { x: Number(last.x.toFixed(1)), y: Number(last.y.toFixed(2)), z: Number(last.z.toFixed(1)) }, corrections: last.corrections === null || before.corrections === null ? null : last.corrections - before.corrections };
100
+ result.cases.push(row); console.log(JSON.stringify(row));
101
+ await sleep(1200);
102
+ return row;
103
+ };
104
+ const shoot = async (/** @type {string} */ name) => {
105
+ const file = join(out, `${phone ? 'phone' : 'desktop'}-${name}.png`);
106
+ await page.screenshot({ path: file }); result.shots.push(file);
107
+ const edge = join(out, `${phone ? 'phone' : 'desktop'}-${name}-edge.png`), size = page.viewportSize() ?? { width: 1440, height: 900 };
108
+ await page.screenshot({ path: edge, clip: { x: 0, y: Math.round(size.height * 0.46 - 90), width: Math.min(220, size.width), height: 180 } }); result.shots.push(edge);
109
+ };
110
+
111
+ // The approach (not scored): on the board to Driftwood's west water.
112
+ await board();
113
+ if (!await driveTo(ZONE_X, -194)) result.notes.push('the approach to (-235, -194) fell short');
114
+ if (shots) { await boost(false); await shoot('boost-off'); await boost(true); await shoot('boost-on'); }
115
+ await boost(false);
116
+ await drive('zone, boost off', ZONE_X, 7000);
117
+ await boost(false); await driveTo(ZONE_X, -194);
118
+ await boost(true);
119
+ await drive('zone, boost on', ZONE_X, 6500);
120
+ // Onto the road: back to the west entryway's line (z 0), out through it, and onto the deck's middle.
121
+ await boost(false);
122
+ if (!await driveTo(ZONE_X, 0)) result.notes.push('the way to the west entryway fell short');
123
+ if (!await driveTo(DECK_X, 0, 40_000)) result.notes.push('the deck (-281, 0) was not reached');
124
+ await drive('road, boost off', DECK_X, 8000);
125
+ await boost(true);
126
+ await drive('road, boost on', DECK_X, 10_500); // 12 m/s² takes 30 to 120 in 7.5 s
127
+ code = 0;
128
+ } catch (error) {
129
+ result.errors.push(String(error).slice(0, 400)); console.error(error);
130
+ await shown?.screenshot({ path: join(out, `${phone ? 'phone' : 'desktop'}-failed.png`) }).catch(() => undefined);
131
+ } finally {
132
+ writeFileSync(join(out, `hover-speed-${phone ? 'phone' : 'desktop'}.json`), `${JSON.stringify(result, null, 2)}\n`);
133
+ await browser.close();
134
+ await rig?.close();
135
+ }
136
+ process.exit(code);
package/scripts/land.mjs CHANGED
@@ -400,7 +400,8 @@ class Landing{
400
400
  regenerate(){
401
401
  if(!existsSync(join(this.root,GEN[0])))return;
402
402
  const before=this.holds('before gen:inputs');
403
- const ran=spawnSync(process.execPath,[...GEN],{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','pipe'],timeout:300_000,maxBuffer:64<<20});
403
+ // the stamps it writes are committed here, so stale pin output refuses instead of warning (gen.ts, stalePinProducts)
404
+ const ran=spawnSync(process.execPath,[...GEN],{cwd:this.root,env:{...this.env,WS_STALE_PINS:'refuse'},encoding:'utf8',stdio:['ignore','pipe','pipe'],timeout:300_000,maxBuffer:64<<20});
404
405
  const head=this.head();
405
406
  if(head!==before){
406
407
  this.receipt(`STOP ${GEN.join(' ')} moved HEAD ${short(before)} -> ${short(head)}`);
@@ -4,12 +4,13 @@
4
4
  // level download on packs, a cold profile: it enters a shard through the title as Jake does (SHARD SELECT, the card,
5
5
  // ENTER WORLD), then plays (walk 10 s, hoverboard at boost) and prints what Copy diagnostics would name:
6
6
  // · the load: control's time from the world page's navigation, the boot stages longest first, the named waits of 200 ms
7
- // or more, and every stretch of 200 ms or more inside readyFrame that no boot entry covers (NB3's "unlogged");
7
+ // or more, and every stretch of 100 ms or more inside readyFrame that no boot entry covers (NB3's "unlogged");
8
8
  // · the play: each 10 s and the whole window's fps, frame p50 / p95, gpu~ p50 / p95 (the game's own frame ring: a
9
9
  // frame's wait beyond its work and the cap, src/shared/engine/core/frameCost.ts), draws and triangles.
10
10
  // Indicative, not a phone: calibrate against the plan's phone table before trusting a ranking (NB1's done-when).
11
11
  // scripts/browser-lane.sh node scripts/loading-flow/benchmax.mjs --base <url> [--shard 'Nine'] [--throttle 4]
12
12
  // [--seconds 60] [--dpr 2] [--json <out.json>] [--profile <cpuprofile.json>]
13
+ // --window 1496x717@2: a desktop window (Jake's Mac, 2992x1434 device pixels) on the desktop tier instead of the phone (NB5).
13
14
  // --dpr: the render scale the game draws at (Graphics' saved pick; the viewport stays a 2x phone); NB5 reads 1 and 2.
14
15
  // --seconds 600: NINE-DRAGON-BENCHMAX NB5's sustained run, printed per minute.
15
16
  import { writeFileSync } from 'node:fs';
@@ -17,20 +18,24 @@ import { parseArgs } from 'node:util';
17
18
  import { chromium, devices } from 'playwright';
18
19
  import { KEYCHAIN_ARGS } from '../chromium-keychain.mjs';
19
20
  import { NAME_ASKED, developerSettings, saveFixture, levelDownloadFixtures, hideDeveloperOverlays } from '../debug-settings.mjs';
20
- import { bootTimelineEntries, CLOCK_MARK_EXPRESSION, profileAnchor, profileIdle, stageStalls, STALL_IDLE_SHARE, STALL_WINDOW_MS } from './stalls.mjs';
21
+ import { bootTimelineEntries, clockMarkExpression, profileAnchor, profileIdle, stageStalls, STALL_IDLE_SHARE, STALL_WINDOW_MS } from './stalls.mjs';
21
22
 
22
23
  const { values } = parseArgs({ options: { base: { type: 'string' }, shard: { type: 'string', default: 'Nine' }, throttle: { type: 'string', default: '4' },
23
24
  seconds: { type: 'string', default: '60' }, json: { type: 'string' }, profile: { type: 'string' },
24
- dpr: { type: 'string', default: '2' } } });
25
+ dpr: { type: 'string', default: '2' }, window: { type: 'string' } } });
25
26
  if (values.base === undefined) { console.error('usage: benchmax.mjs --base <url> [--shard <card title regex>] [--throttle 4] [--seconds 60] [--dpr 2] [--json <file>] [--profile <file>]'); process.exit(2); }
27
+ // --window <css W>x<css H>@<scale>: a desktop browser window instead of the phone (NB5, Jake's Mac: 1496x717@2 is 2992x1434), desktop tier
28
+ const desktop = /^(\d+)x(\d+)@([\d.]+)$/u.exec(values.window ?? '');
29
+ if (values.window !== undefined && desktop === null) { console.error('--window wants <W>x<H>@<scale>, e.g. 1496x717@2'); process.exit(2); }
26
30
  const base = values.base.replace(/\/$/u, ''), shard = new RegExp(values.shard ?? 'Nine', 'iu'), throttle = Number(values.throttle), seconds = Number(values.seconds);
27
31
  /** @param {number} ms */
28
32
  const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms); });
29
33
 
30
34
  const browser = await chromium.launch({ headless: true, args: [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] });
31
35
  try {
32
- const context = await browser.newContext({ ...devices['iPhone 16 Pro'], viewport: { width: 402, height: 874 }, deviceScaleFactor: 2 });
33
- await developerSettings(context, { tier: 'phone', volume: 0 });
36
+ const context = desktop === null ? await browser.newContext({ ...devices['iPhone 16 Pro'], viewport: { width: 402, height: 874 }, deviceScaleFactor: 2 })
37
+ : await browser.newContext({ viewport: { width: Number(desktop[1]), height: Number(desktop[2]) }, deviceScaleFactor: Number(desktop[3]) });
38
+ await developerSettings(context, { tier: desktop === null ? 'phone' : 'desktop', volume: 0 });
34
39
  await saveFixture(context, { scope: 'global', key: 'gfx', data: { dpr: values.dpr ?? '2', aa: 'auto' } });
35
40
  for (const fixture of levelDownloadFixtures('packs')) await saveFixture(context, fixture);
36
41
  // a phone's first PLAY goes straight to Driftwood's first-play card (MOBILE-GRAPHICS MG5): this device has done it
@@ -69,7 +74,7 @@ try {
69
74
  if (!await until(control, 240_000)) throw new Error('never reached control');
70
75
  if (values.profile !== undefined) {
71
76
  // the profile's end is the page's `performance.now()` read just before the stop (its clock is the profiler's own)
72
- const markPageMs = Number(await page.evaluate(CLOCK_MARK_EXPRESSION)), pageEnd = await page.evaluate('performance.now()');
77
+ const markPageMs = Number(await page.evaluate(clockMarkExpression())), pageEnd = await page.evaluate('performance.now()');
73
78
  const { profile } = await cdp.send('Profiler.stop');
74
79
  writeFileSync(values.profile, JSON.stringify({ pageEnd, profile }));
75
80
  // NB6: the ring-1 stall ratchet's own reading of this load (stalls.mjs), every load stage
@@ -90,8 +95,8 @@ try {
90
95
  const inside = done.filter(e => e !== ready && !e.op.startsWith('stage:') && e.start < ready.start + ready.ms && e.start + e.ms > ready.start)
91
96
  .map(e => [Math.max(e.start, ready.start), Math.min(e.start + e.ms, ready.start + ready.ms)]).sort((a, b) => a[0] - b[0]);
92
97
  let at = ready.start;
93
- for (const [from, to] of inside) { if (from - at >= 200) gaps.push({ from: at - ready.start, ms: from - at }); at = Math.max(at, to); }
94
- if (ready.start + ready.ms - at >= 200) gaps.push({ from: at - ready.start, ms: ready.start + ready.ms - at });
98
+ for (const [from, to] of inside) { if (from - at >= 100) gaps.push({ from: at - ready.start, ms: from - at }); at = Math.max(at, to); }
99
+ if (ready.start + ready.ms - at >= 100) gaps.push({ from: at - ready.start, ms: ready.start + ready.ms - at });
95
100
  }
96
101
  const control = entries.find(e => e.operation === 'app:control-ready')?.start ?? Number.NaN, first = Math.min(...stage.map(e => e.start));
97
102
  const timeline = entries.map(e => ({ op: e.operation, realm: e.realm, start: Math.round(e.start), ms: e.end === null ? null : Math.round(e.end - e.start), result: e.result }));
@@ -100,7 +105,20 @@ try {
100
105
  && e.start >= ready.start && e.start < ready.start + ready.ms).map(e => ({ op: e.op, from: e.start - ready.start, ms: e.ms }));
101
106
  // NB4: the boot's script memory bank against what the page took from it by control (fixedMemory.ts census)
102
107
  const scriptMemory = window.__wildshard?.scriptMemory?.() ?? null;
103
- return { phases: { control, firstStage: first }, stage, waits, readyGaps: gaps, readyParts, scriptMemory, timeline };
108
+ // NB3's cut: the settle's per-tile attaches (tileDriver's DL21 measure), by content: how many, their summed and longest ms
109
+ // (FENCE_LANES run at once, so the sum exceeds the span), and the attaches' own wall span
110
+ const attaches = performance.getEntriesByName('wildshard.tile.attach'), byContent = new Map();
111
+ for (const a of attaches) for (const [id, ms] of Object.entries(a.detail?.contents ?? {})) {
112
+ const row = byContent.get(id) ?? { id, n: 0, ms: 0, max: 0 }; row.n++; row.ms += ms; row.max = Math.max(row.max, ms); byContent.set(id, row); }
113
+ const attachSpan = attaches.length === 0 ? 0 : Math.max(...attaches.map(a => a.startTime + a.duration)) - Math.min(...attaches.map(a => a.startTime));
114
+ // DL21's Developer split of each slab part's geometry warm (Game.warmSceneRoots): its prepare and its parked draws
115
+ const warm = Object.fromEntries(['prepare', 'draws'].map(part => { const list = performance.getEntriesByName('wildshard.warm.geometry-' + part);
116
+ return [part, { n: list.length, ms: list.reduce((sum, e) => sum + e.duration, 0) }]; }));
117
+ const raw = ['wildshard.tile.attach', 'wildshard.warm.geometry-prepare', 'wildshard.warm.geometry-draws'].flatMap(n => performance.getEntriesByName(n)
118
+ .map(e => ({ n: n.split('.').pop(), start: Math.round(e.startTime), ms: Math.round(e.duration), key: e.detail?.key, layer: e.detail?.layer })));
119
+ const tileAttach = { raw, warm, tiles: attaches.length, span: attachSpan, contents: [...byContent.values()].sort((a, b) => b.ms - a.ms),
120
+ slowest: [...attaches].sort((a, b) => b.duration - a.duration).slice(0, 5).map(a => ({ key: a.detail?.key, layer: a.detail?.layer, ms: Math.round(a.duration), contents: a.detail?.contents })) };
121
+ return { phases: { control, firstStage: first }, stage, waits, readyGaps: gaps, readyParts, scriptMemory, tileAttach, timeline };
104
122
  })()`);
105
123
 
106
124
  // the play: walk 10 s, then the hoverboard at boost; the game's own frame ring, read every 250 ms
@@ -164,14 +182,19 @@ try {
164
182
  const s = ms => `${(ms / 1000).toFixed(1)} s`;
165
183
  /** @param {number} n */
166
184
  const f = n => n.toFixed(1);
167
- console.log(`benchmax: ${titles[target]} at ${base}, Chromium headless, CPU x${throttle}, 402x874 @2, packs, cold`);
185
+ console.log(`benchmax: ${titles[target]} at ${base}, Chromium headless, CPU x${throttle}, ${desktop === null ? '402x874 @2 (phone)' : `${desktop[1]}x${desktop[2]} @${desktop[3]} (desktop)`}, packs, cold`);
168
186
  console.log(`control ${s(load.phases.control)} after the world page's navigation · its first boot stage at ${s(load.phases.firstStage)}`);
169
187
  console.log('stages, longest first:'); for (const e of load.stage.slice(0, 10)) console.log(` ${e.op.slice(6).padEnd(16)} ${s(e.ms)}`);
170
188
  console.log('named waits >= 200 ms:'); for (const e of load.waits.slice(0, 10)) console.log(` ${e.op.slice(5, 90).padEnd(60)} ${s(e.ms)}`);
171
189
  console.log('readyFrame parts >= 100 ms:'); for (const e of load.readyParts.slice(0, 12)) console.log(` +${s(e.from)} ${e.op.slice(0, 60).padEnd(60)} ${s(e.ms)}`);
190
+ const ta = load.tileAttach;
191
+ console.log(`spawn-view tile attaches: ${ta.tiles} measures over ${s(ta.span)}, by content (count · sum · longest):`);
192
+ for (const row of ta.contents.slice(0, 12)) console.log(` ${String(row.id).padEnd(40)} ${String(row.n).padStart(3)} · ${s(row.ms)} · ${s(row.max)}`);
193
+ console.log(` geometry warms: prepare ${ta.warm.prepare.n} · ${s(ta.warm.prepare.ms)} · parked draws ${ta.warm.draws.n} · ${s(ta.warm.draws.ms)}`);
194
+ for (const row of ta.slowest.slice(0, 2)) console.log(` slowest tile ${row.key} ${row.layer} ${s(row.ms)}: ${Object.entries(row.contents ?? {}).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([id, ms]) => `${id.slice(0, 28)} ${ms} ms`).join(', ')}`);
172
195
  const bank = (/** @type {{ hits: number, misses: number, retained: number } | null} */ m) => m === null ? 'n/a' : `hits ${m.hits} · misses ${m.misses} · retained ${m.retained}`;
173
196
  console.log(`script memory bank: at control ${bank(load.scriptMemory)} · after play ${bank(play.scriptMemory)}`);
174
- console.log(`readyFrame unlogged >= 200 ms: ${load.readyGaps.length === 0 ? 'none' : load.readyGaps.map((/** @type {{ ms: number, from: number }} */ g) => `${s(g.ms)} at +${s(g.from)}`).join(', ')}`);
197
+ console.log(`readyFrame unlogged >= 100 ms: ${load.readyGaps.length === 0 ? 'none' : load.readyGaps.map((/** @type {{ ms: number, from: number }} */ g) => `${s(g.ms)} at +${s(g.from)}`).join(', ')}`);
175
198
  console.log(`play ${seconds} s: ${f(play.all.fps)} fps · frame p50 ${f(play.all.p50)} / p95 ${f(play.all.p95)} ms · gpu~ p50 ${f(play.all.gpu50)} / p95 ${f(play.all.gpu95)} ms · ${play.draws} draws · ${(play.triangles / 1e6).toFixed(2)} M tris · pixel ratio ${play.pixelRatio}`);
176
199
  console.log('triangles by material (visible, in view):'); for (const row of where) console.log(` ${row.name.padEnd(48)} ${(row.tris / 1e6).toFixed(3)} M · ${row.draws} draws`);
177
200
  console.log(`shadow pass: ${shadow.draws} of ${shadow.allDraws} draws · ${(shadow.triangles / 1e6).toFixed(2)} of ${(shadow.allTriangles / 1e6).toFixed(2)} M tris`);