@wildshard/engine 0.1.18 → 0.1.20

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 (334) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +18 -0
  5. package/lint/ratchet.json +0 -68
  6. package/lint/ratchet.mjs +1 -4
  7. package/package.json +19 -15
  8. package/scripts/agent-sync.mjs +27 -8
  9. package/scripts/app-build/appCook.ts +8 -2
  10. package/scripts/app-build/catalogue.ts +10 -7
  11. package/scripts/app-build/gen.ts +33 -2
  12. package/scripts/app-build/isolation.d.mts +10 -0
  13. package/scripts/app-build/isolation.mjs +47 -0
  14. package/scripts/app-build/outputProducts.mjs +4 -0
  15. package/scripts/app-build/previousDeploy.d.mts +2 -0
  16. package/scripts/app-build/previousDeploy.mjs +10 -1
  17. package/scripts/app-build/serviceWorker.ts +10 -3
  18. package/scripts/app-build/splitOutput.mjs +4 -2
  19. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  20. package/scripts/app-build/standaloneOutput.mjs +5 -3
  21. package/scripts/app-build/titlePreloads.d.mts +8 -0
  22. package/scripts/app-build/titlePreloads.mjs +69 -0
  23. package/scripts/app-build/worldMapAtlas.ts +10 -6
  24. package/scripts/app-build-pipeline.mjs +31 -3
  25. package/scripts/built-product.mjs +1 -1
  26. package/scripts/cell-mem-bench.mjs +83 -23
  27. package/scripts/check-custom-sections-zero.mjs +1 -1
  28. package/scripts/check-devserver.mjs +2 -0
  29. package/scripts/check-models.mjs +2 -0
  30. package/scripts/check-paths.allow.json +0 -115
  31. package/scripts/check-paths.mjs +2 -2
  32. package/scripts/check-platform-ratchets.mjs +2 -3
  33. package/scripts/chromium-keychain.d.mts +1 -1
  34. package/scripts/ci-static.sh +1 -1
  35. package/scripts/committed-fast-checks.mjs +0 -2
  36. package/scripts/content-sw-proof.mjs +2 -1
  37. package/scripts/cook-worker.mjs +9 -3
  38. package/scripts/cook.mjs +18 -5
  39. package/scripts/docs-inputs-proof.mjs +6 -6
  40. package/scripts/e7-voice-staging-proof.mjs +1 -1
  41. package/scripts/gate-related-tests.mjs +1 -1
  42. package/scripts/git-source-view.mjs +1 -1
  43. package/scripts/goldens/capture.mjs +17 -5
  44. package/scripts/grid-crossing-nightly.mjs +59 -0
  45. package/scripts/grid-crossing-qa.mjs +44 -0
  46. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  47. package/scripts/grid-crossing-ratchet.mjs +52 -0
  48. package/scripts/grid-crossing-report.mjs +122 -0
  49. package/scripts/grid-crossing-stages.mjs +47 -0
  50. package/scripts/grid-crossing-tour.mjs +284 -0
  51. package/scripts/grid-crossing-walk-proof.mjs +126 -17
  52. package/scripts/host-ruler/roots.mjs +2 -2
  53. package/scripts/host-ruler.d.mts +91 -0
  54. package/scripts/host-ruler.mjs +565 -0
  55. package/scripts/land.mjs +2 -1
  56. package/scripts/live-prepush.py +3 -5
  57. package/scripts/loading-flow/benchmax.mjs +37 -12
  58. package/scripts/loading-flow/deskbench.mjs +276 -0
  59. package/scripts/loading-flow/stalls.d.mts +17 -3
  60. package/scripts/loading-flow/stalls.mjs +82 -3
  61. package/scripts/look-loop/test_look_loop.py +1 -38
  62. package/scripts/memory-proof.mjs +61 -6
  63. package/scripts/mmo-bots.mjs +8 -2
  64. package/scripts/net-lag-proof.mjs +219 -0
  65. package/scripts/night-market-kit-budget.mjs +2 -2
  66. package/scripts/nightly-model.ts +9 -6
  67. package/scripts/offline-proof-rules.d.mts +2 -2
  68. package/scripts/offline-proof-rules.mjs +15 -4
  69. package/scripts/offline-proof.mjs +80 -13
  70. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  71. package/scripts/page-release/content.d.mts +9 -1
  72. package/scripts/page-release/content.mjs +131 -17
  73. package/scripts/page-release/flow.mjs +36 -10
  74. package/scripts/page-release/stamp-content.mjs +24 -0
  75. package/scripts/page-release.mjs +28 -6
  76. package/scripts/page-size.mjs +2 -1
  77. package/scripts/parity/boot-smoke.mjs +13 -2
  78. package/scripts/pin-format.ts +5 -2
  79. package/scripts/pin-packs.ts +1 -1
  80. package/scripts/pins-reuse.d.mts +1 -0
  81. package/scripts/pins-reuse.mjs +22 -0
  82. package/scripts/pins.ts +4 -4
  83. package/scripts/precommit-checks.mjs +1 -7
  84. package/scripts/precommit-jobs.mjs +0 -1
  85. package/scripts/precommit-source.py +1 -9
  86. package/scripts/program-discovery.mjs +1 -1
  87. package/scripts/ring-cook.mjs +2 -1
  88. package/scripts/ring-step.ts +1 -1
  89. package/scripts/scratch-dir.mjs +95 -0
  90. package/scripts/scratch-sweep.mjs +182 -0
  91. package/scripts/script-scenario-metrics.mjs +1 -1
  92. package/scripts/shard-output-content.d.mts +1 -1
  93. package/scripts/shard-output-content.mjs +2 -2
  94. package/scripts/shard-outputs.mjs +1 -1
  95. package/scripts/shard-public.mjs +1 -1
  96. package/scripts/shard-wire-meter.mjs +24 -9
  97. package/scripts/side-parity.mjs +4 -2
  98. package/scripts/standalone-smoke.mjs +8 -3
  99. package/scripts/tier-textures.mjs +22 -4
  100. package/scripts/tile-bake-report.mjs +1 -1
  101. package/scripts/tile-bakes.mjs +1 -1
  102. package/scripts/title-assets.generated.json +2 -0
  103. package/scripts/tsconfig.json +2 -14
  104. package/scripts/vendor/basisu/LICENSE +201 -0
  105. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  106. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  107. package/scripts/vitest-push-guards.config.ts +1 -1
  108. package/scripts/vps/harden-apply.sh +4 -1
  109. package/scripts/vps/harden-prometheus.sh +179 -0
  110. package/scripts/vps/harden.sh +16 -0
  111. package/scripts/vps/rebuild.sh +18 -0
  112. package/scripts/vps/wildshard-config +6 -2
  113. package/scripts/worker-client-play.mjs +6 -2
  114. package/scripts/worktree-reap.mjs +59 -13
  115. package/scripts/worktree.mjs +19 -5
  116. package/src/.oxlintrc.json +3 -182
  117. package/src/client/app/entry.ts +10 -2
  118. package/src/client/engine/anim/rigParser.ts +2 -2
  119. package/src/client/engine/boot/bootCache.ts +2 -2
  120. package/src/client/engine/boot/bootTrace.ts +12 -4
  121. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  122. package/src/client/engine/boot/clearDownloads.ts +5 -2
  123. package/src/client/engine/boot/contentRead.ts +11 -0
  124. package/src/client/engine/boot/gpuFiles.ts +4 -2
  125. package/src/client/engine/boot/lastEnd.ts +99 -12
  126. package/src/client/engine/boot/texturePack.ts +2 -2
  127. package/src/client/engine/core/Game.ts +63 -19
  128. package/src/client/engine/core/gpuOnly.ts +10 -0
  129. package/src/client/engine/core/renderBudget.ts +134 -0
  130. package/src/client/engine/net/netPlayer.ts +19 -2
  131. package/src/client/engine/net/otherPlayers.ts +55 -8
  132. package/src/client/engine/net/predictor.ts +33 -9
  133. package/src/client/engine/net/redial.ts +68 -10
  134. package/src/client/engine/pwa/cacheNames.ts +58 -1
  135. package/src/client/engine/pwa/sw.js +41 -11
  136. package/src/client/engine/render/dataLook.ts +219 -44
  137. package/src/client/engine/render/families/detail.ts +89 -0
  138. package/src/client/engine/render/families/pbr.ts +9 -1
  139. package/src/client/engine/render/families/registry.ts +11 -2
  140. package/src/client/engine/render/families/sceneSurface.ts +116 -0
  141. package/src/client/engine/render/look.ts +12 -0
  142. package/src/client/engine/render/lookLight.ts +103 -11
  143. package/src/client/engine/render/lookRender.ts +105 -0
  144. package/src/client/engine/render/precompile.ts +4 -2
  145. package/src/client/engine/render/tiers.ts +4 -1
  146. package/src/client/engine/saves/indexed.ts +2 -2
  147. package/src/client/engine/telemetry/browserErrors.ts +24 -3
  148. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  149. package/src/client/engine/ui/debugOptions.ts +1 -1
  150. package/src/client/engine/ui/lookLightOption.ts +10 -6
  151. package/src/client/engine/ui/namePrompt.ts +7 -0
  152. package/src/client/engine/world/declaredProps.ts +5 -1
  153. package/src/client/engine/world/skyRig.ts +4 -1
  154. package/src/client/engine/world/terrainTileView.ts +64 -23
  155. package/src/client/game/boot/audio.generated.ts +114 -114
  156. package/src/client/game/boot/bytes.generated.ts +118 -220
  157. package/src/client/game/boot/placedSpawn.ts +35 -0
  158. package/src/client/game/boot/spawnDownload.ts +25 -6
  159. package/src/client/game/boot/versions.generated.ts +7 -5
  160. package/src/client/game/devScene/hook.ts +428 -0
  161. package/src/client/game/devScene/liveLook.ts +21 -0
  162. package/src/client/game/grid/cellLoading.ts +12 -2
  163. package/src/client/game/grid/live.ts +152 -19
  164. package/src/client/game/grid/liveSession.ts +53 -3
  165. package/src/client/game/grid/mapAtlas.ts +18 -4
  166. package/src/client/game/grid/minimapBlend.ts +15 -5
  167. package/src/client/game/grid/oneWayIn.ts +5 -1
  168. package/src/client/game/grid/pageEntry.ts +12 -1
  169. package/src/client/game/grid/placedCells.ts +114 -12
  170. package/src/client/game/grid/placedContent.ts +85 -0
  171. package/src/client/game/grid/prefetch.ts +9 -1
  172. package/src/client/game/grid/productInputs.ts +23 -10
  173. package/src/client/game/grid/productLeases.ts +4 -1
  174. package/src/client/game/grid/products.ts +8 -4
  175. package/src/client/game/grid/roadLook.ts +24 -15
  176. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  177. package/src/client/game/grid/roadResources.ts +24 -0
  178. package/src/client/game/grid/roadSign.worker.ts +4 -3
  179. package/src/client/game/grid/roadSignPaint.ts +16 -5
  180. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  181. package/src/client/game/grid/roadSignScale.ts +8 -0
  182. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  183. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  184. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  185. package/src/client/game/grid/roadTileWriter.ts +2 -1
  186. package/src/client/game/grid/screenReports.ts +39 -0
  187. package/src/client/game/grid/session.ts +32 -7
  188. package/src/client/game/grid/softWallLook.ts +25 -8
  189. package/src/client/game/mainMenu.ts +6 -2
  190. package/src/client/game/plugin/context.ts +2 -1
  191. package/src/client/game/plugin/followedMovers.ts +7 -1
  192. package/src/client/game/quest/figures.ts +2 -0
  193. package/src/client/game/session/finish.ts +9 -0
  194. package/src/client/game/shardfile/assetCache.ts +4 -4
  195. package/src/client/game/shardfile/client.ts +28 -8
  196. package/src/client/game/shardfile/clientAssets.ts +9 -5
  197. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  198. package/src/client/game/shardfile/clientPropMaterials.ts +4 -1
  199. package/src/client/game/shardfile/clientViews.ts +36 -8
  200. package/src/client/game/shardfile/clientWater.ts +51 -9
  201. package/src/client/game/shardfile/clientWorker.ts +19 -7
  202. package/src/client/game/shardfile/constructionCheckpoint.ts +2 -2
  203. package/src/client/game/shardfile/groundMerge.ts +57 -5
  204. package/src/client/game/shardfile/hybrid.ts +2 -0
  205. package/src/client/game/shardfile/look.ts +8 -3
  206. package/src/client/game/shardfile/product.ts +34 -7
  207. package/src/client/game/shardfile/productChecks.ts +2 -2
  208. package/src/client/game/shardfile/productCost.ts +2 -2
  209. package/src/client/game/shardfile/readAsset.ts +2 -2
  210. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  211. package/src/client/game/shardfile/seatGrace.ts +9 -0
  212. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  213. package/src/client/game/shardfile/slabLibrary.ts +115 -49
  214. package/src/client/game/shardfile/tileContent.ts +1 -1
  215. package/src/client/game/shardfile/tileDriver.ts +38 -11
  216. package/src/client/game/shardfile/wirePage.ts +7 -3
  217. package/src/client/game/shardfile/worldScenes.ts +17 -10
  218. package/src/client/game/systems/npc/figureRows.ts +9 -0
  219. package/src/client/host/online/doctor.ts +22 -7
  220. package/src/client/host/online/doctorView.ts +2 -0
  221. package/src/client/host/online/linkScreens.ts +109 -5
  222. package/src/client/host/online/shell.ts +13 -4
  223. package/src/client/host/standalone/shell.ts +40 -0
  224. package/src/cook/game/astc6Encode.ts +55 -0
  225. package/src/cook/game/astc6Wasm.ts +176 -0
  226. package/src/cook/game/cookJob.ts +30 -6
  227. package/src/cook/game/cookWorker.ts +38 -11
  228. package/src/cook/game/entryTotals.ts +51 -24
  229. package/src/cook/game/shardCook.ts +35 -7
  230. package/src/cook/game/spawnParts.ts +33 -8
  231. package/src/cook/game/tierTextures.ts +87 -14
  232. package/src/server/engine/ai/bossContenders.ts +27 -3
  233. package/src/server/engine/ai/phases.ts +1 -1
  234. package/src/server/engine/entities/creatureRefill.ts +9 -2
  235. package/src/server/engine/net/ledgerBook.ts +2 -0
  236. package/src/server/engine/net/room.ts +15 -0
  237. package/src/server/engine/sim/respawn.ts +8 -0
  238. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  239. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  240. package/src/server/game/boss/native.ts +2 -1
  241. package/src/server/game/boss/nativeWake.ts +9 -5
  242. package/src/server/game/boss/openArenaNative.ts +2 -2
  243. package/src/server/game/boss/openArenaRoom.ts +3 -1
  244. package/src/server/game/grid/room.ts +44 -3
  245. package/src/server/game/grid/simulation.ts +23 -0
  246. package/src/server/game/population/mixedRoster.ts +11 -3
  247. package/src/server/game/population/nativeBake.ts +8 -3
  248. package/src/server/game/population/nativeReturns.ts +6 -3
  249. package/src/server/game/population/roster.ts +5 -3
  250. package/src/server/game/quest/eliteDrops.ts +18 -3
  251. package/src/server/game/quest/nativeChapter.ts +1 -1
  252. package/src/server/game/quest/nativeComposition.ts +5 -1
  253. package/src/server/game/riding/nativeTaming.ts +22 -7
  254. package/src/server/game/riding/wildRefill.ts +3 -2
  255. package/src/server/game/shardfile/bossRow.ts +4 -2
  256. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  257. package/src/server/host/bake/headlessWorker.ts +1 -1
  258. package/src/server/host/dedicated/cellHost.ts +112 -18
  259. package/src/server/host/dedicated/cellProtocol.ts +18 -1
  260. package/src/server/host/dedicated/cellWorker.ts +8 -5
  261. package/src/server/host/dedicated/dedicatedRoom.ts +38 -11
  262. package/src/server/host/dedicated/gridCells.ts +15 -6
  263. package/src/server/host/dedicated/loopLag.ts +21 -0
  264. package/src/server/host/dedicated/main.ts +13 -5
  265. package/src/server/host/dedicated/packReader.ts +3 -3
  266. package/src/server/host/dedicated/placementFile.ts +3 -2
  267. package/src/server/host/dedicated/roadRoom.ts +34 -4
  268. package/src/server/host/dedicated/serverMetrics.ts +135 -0
  269. package/src/server/host/dedicated/socketPump.ts +21 -4
  270. package/src/server/host/dedicated/workerTable.ts +32 -14
  271. package/src/server/host/dedicated/world.ts +65 -7
  272. package/src/server/host/headless.ts +1 -1
  273. package/src/server/host/headlessRuntime.ts +1 -1
  274. package/src/server/host/standalone/roadWorld.ts +15 -3
  275. package/src/server/host/standalone/serverHost.ts +57 -8
  276. package/src/server/host/standalone/serverProduct.ts +48 -16
  277. package/src/server/host/standalone/serverRuntime.ts +1 -1
  278. package/src/shared/engine/ai/BossBrain.ts +8 -0
  279. package/src/shared/engine/core/framePacing.ts +12 -1
  280. package/src/shared/engine/physics/terrainTiles.ts +20 -4
  281. package/src/shared/game/boss/wake.ts +6 -0
  282. package/src/shared/game/devColliders.ts +107 -0
  283. package/src/shared/game/devGameplay.ts +41 -0
  284. package/src/shared/game/eliteSystem.ts +8 -0
  285. package/src/shared/game/grid/allocator.ts +3 -0
  286. package/src/shared/game/grid/placementRows.ts +5 -2
  287. package/src/shared/game/plugin/bossRecord.ts +3 -2
  288. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  289. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  290. package/src/shared/game/shardfile/packReads.ts +28 -3
  291. package/src/shared/game/shardfile/serverPack.ts +9 -0
  292. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  293. package/src/shared/host/formatJsonSchema.ts +2 -2
  294. package/src/tsconfig.json +1 -27
  295. package/lint/host-reviews.json +0 -14
  296. package/lint/listed-view-code.json +0 -13
  297. package/lint/platform-pending-users.json +0 -2520
  298. package/lint/platform-pending-users.md +0 -18
  299. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  300. package/scripts/check-closed-components.d.mts +0 -7
  301. package/scripts/check-closed-components.mjs +0 -87
  302. package/scripts/g571-hosts.d.mts +0 -3
  303. package/scripts/g571-hosts.mjs +0 -54
  304. package/scripts/host-ruler/register-migrate.mjs +0 -242
  305. package/scripts/listed-view-code.d.mts +0 -7
  306. package/scripts/listed-view-code.mjs +0 -93
  307. package/scripts/look-loop/fit-lut.py +0 -142
  308. package/scripts/look-loop/palette-delta.py +0 -183
  309. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  310. package/scripts/look-loop/regions/far-reach.json +0 -225
  311. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  312. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  313. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  314. package/scripts/platform-chargebacks.d.mts +0 -9
  315. package/scripts/platform-chargebacks.mjs +0 -135
  316. package/scripts/shard-component-spans.d.mts +0 -15
  317. package/scripts/shard-component-spans.mjs +0 -18
  318. package/scripts/shard-components.d.mts +0 -16
  319. package/scripts/shard-components.mjs +0 -363
  320. package/scripts/shard-platform-hosts.d.mts +0 -2
  321. package/scripts/shard-platform-hosts.mjs +0 -93
  322. package/scripts/shard-platform-sections.d.mts +0 -2
  323. package/scripts/shard-platform-sections.mjs +0 -9
  324. package/scripts/shard-platform.d.mts +0 -76
  325. package/scripts/shard-platform.mjs +0 -1072
  326. package/src/.oxfmtrc.json +0 -48
  327. package/src/scripts/ask-new.sh +0 -29
  328. package/src/scripts/asks.mjs +0 -142
  329. package/src/scripts/herdr-prompt.sh +0 -34
  330. package/src/scripts/herdr-question-open.sh +0 -67
  331. package/src/scripts/md-wrap.mjs +0 -229
  332. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  333. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  334. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -4,37 +4,44 @@
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';
16
17
  import { parseArgs } from 'node:util';
17
18
  import { chromium, devices } from 'playwright';
18
19
  import { KEYCHAIN_ARGS } from '../chromium-keychain.mjs';
19
- import { 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';
20
+ import { NAME_ASKED, developerSettings, saveFixture, levelDownloadFixtures, hideDeveloperOverlays } from '../debug-settings.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
37
42
  await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
43
+ // MP2.4: a page with a world asks for the Name before it joins; a bench never answers it, so it never reached control
44
+ await saveFixture(context, NAME_ASKED);
38
45
  await context.addInitScript(hideDeveloperOverlays);
39
46
  const page = await context.newPage();
40
47
  page.setDefaultTimeout(240_000);
@@ -67,7 +74,7 @@ try {
67
74
  if (!await until(control, 240_000)) throw new Error('never reached control');
68
75
  if (values.profile !== undefined) {
69
76
  // the profile's end is the page's `performance.now()` read just before the stop (its clock is the profiler's own)
70
- 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()');
71
78
  const { profile } = await cdp.send('Profiler.stop');
72
79
  writeFileSync(values.profile, JSON.stringify({ pageEnd, profile }));
73
80
  // NB6: the ring-1 stall ratchet's own reading of this load (stalls.mjs), every load stage
@@ -88,8 +95,8 @@ try {
88
95
  const inside = done.filter(e => e !== ready && !e.op.startsWith('stage:') && e.start < ready.start + ready.ms && e.start + e.ms > ready.start)
89
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]);
90
97
  let at = ready.start;
91
- for (const [from, to] of inside) { if (from - at >= 200) gaps.push({ from: at - ready.start, ms: from - at }); at = Math.max(at, to); }
92
- 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 });
93
100
  }
94
101
  const control = entries.find(e => e.operation === 'app:control-ready')?.start ?? Number.NaN, first = Math.min(...stage.map(e => e.start));
95
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 }));
@@ -98,7 +105,20 @@ try {
98
105
  && e.start >= ready.start && e.start < ready.start + ready.ms).map(e => ({ op: e.op, from: e.start - ready.start, ms: e.ms }));
99
106
  // NB4: the boot's script memory bank against what the page took from it by control (fixedMemory.ts census)
100
107
  const scriptMemory = window.__wildshard?.scriptMemory?.() ?? null;
101
- 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 };
102
122
  })()`);
103
123
 
104
124
  // the play: walk 10 s, then the hoverboard at boost; the game's own frame ring, read every 250 ms
@@ -162,14 +182,19 @@ try {
162
182
  const s = ms => `${(ms / 1000).toFixed(1)} s`;
163
183
  /** @param {number} n */
164
184
  const f = n => n.toFixed(1);
165
- 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`);
166
186
  console.log(`control ${s(load.phases.control)} after the world page's navigation · its first boot stage at ${s(load.phases.firstStage)}`);
167
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)}`);
168
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)}`);
169
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(', ')}`);
170
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}`;
171
196
  console.log(`script memory bank: at control ${bank(load.scriptMemory)} · after play ${bank(play.scriptMemory)}`);
172
- 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(', ')}`);
173
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}`);
174
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`);
175
200
  console.log(`shadow pass: ${shadow.draws} of ${shadow.allDraws} draws · ${(shadow.triangles / 1e6).toFixed(2)} of ${(shadow.allTriangles / 1e6).toFixed(2)} M tris`);
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env node
2
+ // NINE-DRAGON-BENCHMAX NB5, widened (meta QA-FEEDBACK-2026-11-14 rows 2, 3 and 5): the desktop frame on Jake's window.
3
+ // Headless Chromium (ANGLE Metal, vsync and the frame-rate limit off, so a frame shows its real cost), 1496x717 CSS px at
4
+ // device scale 2 by default (Jake's Chrome on his Mac: 2992x1434 device pixels), the desktop tier, entering a shard
5
+ // through the title as he does (SHARD SELECT, the card, ENTER WORLD: the grid at the shard's cell). At each pose it prints
6
+ // the drawn frame (median / p95 / max), the game's main-thread work in it (update, render), the draws and triangles and
7
+ // the drawing buffer (pixel ratio, megapixels).
8
+ // scripts/browser-lane.sh node scripts/loading-flow/deskbench.mjs --base <url> [--shards Nine,Nalati,Driftwood]
9
+ // [--frames 240] [--poses 6] [--width 1496 --height 717 --scale 2] [--gfx-dpr 1|1.5|2|native] [--json <out.json>]
10
+ // [--shots <dir>] [--profile <dir>] [--census] [--ab] [--capped] [--stalls]
11
+ // --stalls: NB6's play-stall ratchet at each pose (exits 1 on a stall); with --capped, the desktop check Ring 1 can't run.
12
+ // --ab: at the last pose, each lever against the baseline, interleaved over 6 rounds so a busy machine's drift cancels
13
+ // (render scale 1 and 0.75, the shadow maps held, AO off, the post passes off, the viewmodel hidden).
14
+ // --hide <regex>: at each pose a second shot with every object whose name matches and everything under it drawn on no layer (what is behind it).
15
+ // --census: one frame's renderer.render calls (target, draws, CPU ms) and the scene graph's size.
16
+ // --profile: a Chromium CPU profile of each pose's sample. GPU timer queries are left out: ANGLE Metal's TIME_ELAPSED
17
+ // read 17-24 ms for frames drawn every 7-10 ms (2026-11-14), so a cost here is a drawn interval or a subtraction.
18
+ import { mkdirSync, writeFileSync } from 'node:fs';
19
+ import { join } from 'node:path';
20
+ import { parseArgs } from 'node:util';
21
+ import { chromium } from 'playwright';
22
+ import { KEYCHAIN_ARGS } from '../chromium-keychain.mjs';
23
+ import { finishPlayProfile, startStallProfile } from './stalls.mjs';
24
+ import { NAME_ASKED, developerSettings, saveFixture, levelDownloadFixtures, hideDeveloperOverlays, harnessPins } from '../debug-settings.mjs';
25
+
26
+ const { values } = parseArgs({ options: { base: { type: 'string' }, shards: { type: 'string', default: 'Nine,Nalati,Driftwood' },
27
+ frames: { type: 'string', default: '240' }, poses: { type: 'string', default: '6' }, width: { type: 'string', default: '1496' },
28
+ height: { type: 'string', default: '717' }, scale: { type: 'string', default: '2' }, json: { type: 'string' }, shots: { type: 'string' },
29
+ 'gfx-dpr': { type: 'string' }, extra: { type: 'string' }, walk: { type: 'string', default: '0' }, ab: { type: 'boolean', default: false }, capped: { type: 'boolean', default: false }, stalls: { type: 'boolean', default: false }, census: { type: 'boolean', default: false }, profile: { type: 'string' }, hide: { type: 'string' }, settle: { type: 'string', default: '2500' } } });
30
+ if (values.base === undefined) { console.error('usage: deskbench.mjs --base <url> [--shards Nine,Nalati,Driftwood] [--frames 240] [--poses 6] [--json <file>] [--shots <dir>] [--profile <dir>] [--census] [--ab]'); process.exit(2); }
31
+ // --stalls reads busy time: an uncapped frame loop keeps the main thread busy by design and would fault every pose
32
+ if (values.stalls && !values.capped) { console.error('deskbench: --stalls needs --capped (an uncapped frame loop is busy by design)'); process.exit(2); }
33
+ const base = values.base.replace(/\/$/u, ''), frames = Number(values.frames), maxPoses = Number(values.poses), settle = Number(values.settle);
34
+ const walkSeconds = Number(values.walk);
35
+ const viewport = { width: Number(values.width), height: Number(values.height) }, scale = Number(values.scale);
36
+ /** @param {number} ms */
37
+ const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms); });
38
+ if (values.shots !== undefined) mkdirSync(values.shots, { recursive: true });
39
+
40
+ /** Browser side: `n` drawn frames by rAF timestamp (the frame interval, uncapped), with the game's work per frame. */
41
+ function sampleFrames(/** @type {number} */ n) {
42
+ const g = /** @type {any} */ (window).__wildshard.world.game;
43
+ return new Promise((resolve, reject) => {
44
+ /** @type {number[]} */ const intervals = [];
45
+ /** @type {number[]} */ const work = [];
46
+ /** @type {number[]} */ const update = [];
47
+ /** @type {number[]} */ const render = [];
48
+ let count = g.frameCount, last = -1;
49
+ const timeout = setTimeout(() => { reject(new Error('sampler stalled')); }, 60_000);
50
+ const tick = (/** @type {number} */ t) => {
51
+ if (g.frameCount !== count) {
52
+ if (last >= 0) { const i = (g.frameI + g.frameMs.length - 1) % g.frameMs.length; intervals.push(t - last); work.push(g.workMs[i]); update.push(g.updateMs[i]); render.push(g.renderMs[i]); }
53
+ count = g.frameCount; last = t;
54
+ }
55
+ if (intervals.length < n) { requestAnimationFrame(tick); return; }
56
+ clearTimeout(timeout);
57
+ const pct = (/** @type {number[]} */ v, /** @type {number} */ p) => { const s = [...v].sort((a, b) => a - b); return s[Math.max(0, Math.ceil(s.length * p) - 1)] ?? 0; };
58
+ const r = (/** @type {number} */ v) => Math.round(v * 10) / 10;
59
+ const r2 = g.renderer, size = { x: g.canvas.width, y: g.canvas.height };
60
+ resolve({ p50: r(pct(intervals, 0.5)), p95: r(pct(intervals, 0.95)), max: r(Math.max(...intervals)), mean: r(intervals.reduce((a, b) => a + b, 0) / intervals.length),
61
+ workP50: r(pct(work, 0.5)), workP95: r(pct(work, 0.95)), updateP50: r(pct(update, 0.5)), renderP50: r(pct(render, 0.5)), calls: g.lastFrame.calls, triangles: g.lastFrame.triangles,
62
+ pixelRatio: r2.getPixelRatio(), buffer: [size.x, size.y], mpx: Math.round(size.x * size.y / 1e4) / 100 });
63
+ };
64
+ requestAnimationFrame(tick);
65
+ });
66
+ }
67
+
68
+ /** Browser side: two drawn frames' renderer.render calls (scene, camera, target, draws, CPU ms) and the scene graph's size. */
69
+ function frameCensus() {
70
+ const g = /** @type {any} */ (window).__wildshard.world.game, r = g.renderer;
71
+ /** @type {any[]} */
72
+ const calls = [];
73
+ const own = Object.getOwnPropertyDescriptor(r, 'render'), main = r.render.bind(r);
74
+ r.render = function render(/** @type {any} */ scene, /** @type {any} */ camera) {
75
+ const t = r.getRenderTarget(), before = r.info.render.calls, start = performance.now();
76
+ main(scene, camera);
77
+ calls.push({ scene: scene.name === '' ? scene.type : scene.name, camera: camera.name === '' ? camera.type : camera.name, target: t ? `${t.width}x${t.height}` : 'screen', draws: r.info.render.calls - before, ms: Math.round((performance.now() - start) * 100) / 100 });
78
+ };
79
+ let objects = 0, meshes = 0, visibleMeshes = 0, autoUpdate = 0, lights = 0, skinned = 0;
80
+ g.rootScene.traverse((/** @type {any} */ o) => { objects++; if (o.matrixAutoUpdate) autoUpdate++; if (o.isLight) lights++; if (o.isSkinnedMesh) skinned++; if (o.isMesh || o.isPoints || o.isLine) meshes++; });
81
+ g.rootScene.traverseVisible((/** @type {any} */ o) => { if (o.isMesh || o.isPoints || o.isLine) visibleMeshes++; });
82
+ return new Promise((resolve) => {
83
+ const start = g.frameCount;
84
+ const tick = () => {
85
+ if (g.frameCount - start < 2) { requestAnimationFrame(tick); return; }
86
+ if (own === undefined) Reflect.deleteProperty(r, 'render'); else Object.defineProperty(r, 'render', own);
87
+ resolve({ objects, meshes, visibleMeshes, autoUpdate, lights, skinned, programs: r.info.programs?.length ?? -1, calls: calls.slice(0, 80), perFrame: calls.length / (g.frameCount - start) });
88
+ };
89
+ requestAnimationFrame(tick);
90
+ });
91
+ }
92
+
93
+ /** Browser side: walk `seconds` from where the player stands, recording drawn intervals and long animation frames. */
94
+ function walkHitches(/** @type {number} */ seconds) {
95
+ const w = /** @type {any} */ (window).__wildshard.world, g = w.game, input = g.app.input, p = w.player;
96
+ /** @type {any[]} */
97
+ const loafs = [];
98
+ const t0 = performance.now();
99
+ const observer = new PerformanceObserver((list) => { for (const e of /** @type {any[]} */ (list.getEntries())) loafs.push(e); });
100
+ try { observer.observe({ type: 'long-animation-frame', buffered: false }); } catch { /* no LoAF: intervals only */ }
101
+ return new Promise((resolve) => {
102
+ /** @type {number[]} */
103
+ const intervals = [];
104
+ let count = g.frameCount, last = -1;
105
+ const step = () => { if (performance.now() - t0 < seconds * 1000) { input.setHeld('move.forward', true); p.yaw += 0.004; setTimeout(step, 16); } };
106
+ step();
107
+ const tick = (/** @type {number} */ t) => {
108
+ if (g.frameCount !== count) { if (last >= 0) intervals.push(t - last); count = g.frameCount; last = t; }
109
+ if (performance.now() - t0 < seconds * 1000) { requestAnimationFrame(tick); return; }
110
+ input.setHeld('move.forward', false); observer.disconnect();
111
+ const s = [...intervals].sort((a, b) => a - b), at = (/** @type {number} */ q) => Math.round((s[Math.min(s.length - 1, Math.floor(s.length * q))] ?? 0) * 10) / 10;
112
+ const r = (/** @type {number} */ v) => Math.round(v);
113
+ resolve({ frames: intervals.length, p50: at(0.5), p95: at(0.95), p99: at(0.99), max: r(s.at(-1) ?? 0),
114
+ over33: intervals.filter((v) => v > 33).length, over50: intervals.filter((v) => v > 50).length, over100: intervals.filter((v) => v > 100).length,
115
+ loafs: loafs.sort((a, b) => b.duration - a.duration).slice(0, 12).map((e) => ({ at: Math.round((e.startTime - t0) / 100) / 10, duration: r(e.duration), blocking: r(e.blockingDuration ?? 0),
116
+ scripts: (e.scripts ?? []).sort((/** @type {any} */ a, /** @type {any} */ b) => b.duration - a.duration).slice(0, 3).map((/** @type {any} */ x) => ({ fn: x.sourceFunctionName === "" ? x.invoker : x.sourceFunctionName, src: `${String(x.sourceURL).split('/').pop()}:${x.sourceCharPosition}`, ms: r(x.duration) })) })) });
117
+ };
118
+ requestAnimationFrame(tick);
119
+ });
120
+ }
121
+
122
+ /** Browser side: each variant against the baseline, interleaved (A B A B …) so a busy machine's drift cancels. */
123
+ async function abCosts(/** @type {any} */ sampler) {
124
+ const g = /** @type {any} */ (window).__wildshard.world.game, r = g.renderer, ratio = r.getPixelRatio();
125
+ const wait = (/** @type {number} */ ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
126
+ const setRatio = (/** @type {number} */ v) => { r.setPixelRatio(v); g.resize(); };
127
+ /** @type {any[]} */
128
+ let held = [];
129
+ /** @type {any[]} */
130
+ const hidden = [];
131
+ const passes = () => g.composer.passes.slice(1).filter((/** @type {any} */ p) => p.enabled);
132
+ /** @type {[string, () => void, () => void][]} */
133
+ const variants = [
134
+ ['render scale 1.0', () => { setRatio(1); }, () => { setRatio(ratio); }],
135
+ ['render scale 0.75', () => { setRatio(0.75); }, () => { setRatio(ratio); }],
136
+ ['shadow maps held', () => { r.shadowMap.autoUpdate = false; }, () => { r.shadowMap.autoUpdate = true; }],
137
+ ['AO off', () => { const ao = g.post?.ao; if (ao) { ao.enabled = false; } }, () => { const ao = g.post?.ao; if (ao) ao.enabled = true; }],
138
+ ['post passes off', () => { for (const p of held = passes()) p.enabled = false; }, () => { for (const p of held) p.enabled = true; }],
139
+ ['viewmodel hidden', () => { g.camera.children.forEach((/** @type {any} */ c) => { if (c.visible) { hidden.push(c); c.visible = false; } }); }, () => { for (const c of hidden.splice(0)) c.visible = true; }],
140
+ ];
141
+ /** @type {Map<string, any[]>} */
142
+ const rows = new Map([['baseline', []], ...variants.map(([name]) => /** @type {[string, any[]]} */ ([name, []]))]);
143
+ for (let round = 0; round < 6; round++) {
144
+ for (const [name, off, on] of variants) {
145
+ await wait(150); rows.get('baseline')?.push(await sampler(60));
146
+ off(); await wait(250);
147
+ try { rows.get(name)?.push(await sampler(60)); } finally { on(); }
148
+ }
149
+ }
150
+ const med = (/** @type {number[]} */ v) => { const s = [...v].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] ?? 0; };
151
+ const baseline = med((rows.get('baseline') ?? []).map((x) => x.p50));
152
+ return [...rows].map(([variant, xs]) => { const p50 = med(xs.map((x) => x.p50)); return { variant, p50, saves: Math.round((baseline - p50) * 10) / 10, work: med(xs.map((x) => x.workP50)), render: med(xs.map((x) => x.renderP50)), calls: med(xs.map((x) => x.calls)) }; });
153
+ }
154
+
155
+ // --capped: vsync and the frame-rate limit kept (shots, look checks, CI): Jake plays on this Mac, and an uncapped page halves
156
+ // his frame rate (meta lane rules, opus-deskperf 11-14); uncapped only to read a frame's real cost
157
+ const browser = await chromium.launch({ headless: true, args: [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist',
158
+ ...(values.capped ? [] : ['--disable-gpu-vsync', '--disable-frame-rate-limit'])] });
159
+ /** @type {any[]} */
160
+ const report = [];
161
+ try {
162
+ for (const shardName of (values.shards ?? '').split(',').filter(Boolean)) {
163
+ const shard = new RegExp(shardName, 'iu');
164
+ const context = await browser.newContext({ viewport, deviceScaleFactor: scale });
165
+ await developerSettings(context, { tier: 'desktop', volume: 0 });
166
+ for (const fixture of levelDownloadFixtures('packs')) await saveFixture(context, fixture);
167
+ // --gfx-dpr: Settings ▸ Graphics' saved render scale (1, 1.25, 1.5, 2, native), for a pixel-count sweep at one window
168
+ if (values['gfx-dpr'] !== undefined) await saveFixture(context, { scope: 'global', key: 'gfx', data: { dpr: values['gfx-dpr'], aa: 'auto' } });
169
+ await saveFixture(context, { scope: 'device', key: 'firstPlayDone', data: true });
170
+ await saveFixture(context, NAME_ASKED);
171
+ await context.addInitScript(hideDeveloperOverlays);
172
+ await harnessPins(context, { seed: 357, capture: null }); // frame-floor's pins: the probe's pose control
173
+ const page = await context.newPage();
174
+ page.setDefaultTimeout(240_000);
175
+ /** @type {string[]} */
176
+ const errors = [];
177
+ page.on('pageerror', e => { errors.push(String(e).slice(0, 200)); });
178
+ const until = async (/** @type {string} */ expression, /** @type {number} */ ms) => { try { await page.waitForFunction(expression, null, { timeout: ms, polling: 200 }); return true; } catch { return false; } };
179
+ const tap = (/** @type {string} */ selector) => page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.click()`);
180
+ await page.goto(`${base}/`);
181
+ if (!await until(`!!document.querySelector('.ws-main-select')?.getClientRects().length`, 120_000)) throw new Error('title never ready');
182
+ await sleep(1500);
183
+ await tap('.ws-main-select');
184
+ if (!await until(`!!document.querySelector('.ws-menu-card')?.getClientRects().length`, 30_000)) throw new Error('shard select never ready');
185
+ await sleep(800);
186
+ const titles = await page.evaluate(`[...document.querySelectorAll('.ws-menu-card')].map(c => (c.querySelector('b')?.textContent ?? c.textContent ?? '').trim().slice(0, 40))`);
187
+ const target = titles.findIndex((/** @type {string} */ title) => shard.test(title));
188
+ if (target === -1) throw new Error(`no card matches ${shard} in ${JSON.stringify(titles)}`);
189
+ await tap(`.ws-menu-dots i[data-i="${target}"]`);
190
+ if (!await until(`document.querySelector('.ws-menu-card.selected')?.dataset.i === '${target}' && !document.querySelector('.ws-menu-play')?.disabled`, 15_000)) throw new Error(`${titles[target]} never selectable`);
191
+ await sleep(800);
192
+ const t0 = Date.now();
193
+ await page.evaluate(`setTimeout(() => document.querySelector('.ws-menu-play').click(), 0)`);
194
+ const control = `(() => { const w = window.__wildshard?.world, l = document.querySelector('.ws-load');
195
+ const shown = !!l && l.isConnected && l.getClientRects().length > 0 && getComputedStyle(l).display !== 'none' && Number(getComputedStyle(l).opacity) > .05;
196
+ try { return !!w?.hud.entered && !w.hud.paused && w.game.frameGate() && !shown; } catch { return false; } })()`;
197
+ if (!await until(control, 300_000)) throw new Error(`${titles[target]} never reached control`);
198
+ const controlS = (Date.now() - t0) / 1000;
199
+ await sleep(5000);
200
+ const meta = await page.evaluate(`(() => { const w = window.__wildshard.world, g = w.game, gl = g.renderer.getContext(), ext = gl.getExtension('WEBGL_debug_renderer_info');
201
+ return { level: g.level.id, renderer: ext ? String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL)) : '', dpr: devicePixelRatio, viewport: [innerWidth, innerHeight],
202
+ spawn: { name: 'spawn', x: w.player.position.x, y: w.player.position.y, z: w.player.position.z, yaw: w.player.yaw, pitch: w.player.pitch },
203
+ passes: g.composer.passes.map(p => (p.name || p.constructor.name) + (p.effects ? ' (' + p.effects.map(e => e.name || e.constructor.name).join('+') + ')' : '')) }; })()`);
204
+ const profileDir = values.profile, cdp = profileDir === undefined ? null : await context.newCDPSession(page);
205
+ if (cdp !== null && profileDir !== undefined) { mkdirSync(profileDir, { recursive: true }); await cdp.send('Profiler.enable'); await cdp.send('Profiler.setSamplingInterval', { interval: 200 }); }
206
+ const authored = await page.evaluate(`(async () => { const a = await window.__wildshard.world.game.level.capturePoses?.() ?? {};
207
+ return Object.entries(a).flatMap(([name, c]) => c.probe ? [{ ...c.probe, name: c.probe.name ?? name }] : c.feet ? [{ name, x: c.feet[0], y: c.feet[1], z: c.feet[2], yaw: -c.yaw * Math.PI / 180, pitch: c.pitch * Math.PI / 180 }] : []); })()`);
208
+ // --extra 'forward,right,yawDeg[,pitchDeg];…': more poses from the spawn, in metres along its facing and degrees off it
209
+ const extra = (values.extra ?? '').split(';').filter(Boolean).map((row, i) => {
210
+ const [forward = 0, right = 0, yawDeg = 0, pitchDeg = 0] = row.split(',').map(Number), yaw = meta.spawn.yaw;
211
+ // the probe's yaw faces -z at 0 (three's camera): forward is (-sin, -cos), right is (cos, -sin)
212
+ return { name: `extra-${i}`, x: meta.spawn.x - Math.sin(yaw) * forward + Math.cos(yaw) * right, y: meta.spawn.y, z: meta.spawn.z - Math.cos(yaw) * forward - Math.sin(yaw) * right,
213
+ yaw: yaw + yawDeg * Math.PI / 180, pitch: pitchDeg * Math.PI / 180 };
214
+ });
215
+ const poses = [meta.spawn, { ...meta.spawn, name: 'spawn-reverse', yaw: meta.spawn.yaw + Math.PI }, ...authored].slice(0, maxPoses).concat(extra);
216
+ console.log(`deskbench ${titles[target]} (${meta.level}) at ${base}: control ${controlS.toFixed(1)} s · ${meta.viewport.join('x')} @${meta.dpr} · ${meta.renderer}`);
217
+ console.log(` passes: ${meta.passes.join(' | ')}`);
218
+ /** @type {any[]} */
219
+ const rows = [];
220
+ for (const pose of poses) {
221
+ await page.evaluate(`window.__wildshard.pose(${JSON.stringify(pose)})`);
222
+ await sleep(settle);
223
+ if (cdp !== null) await cdp.send('Profiler.start');
224
+ // --stalls (NB6, desktop): ring 1's play-stall ratchet over this pose's sample (scripts/loading-flow/stalls.mjs)
225
+ const stallSession = values.stalls && cdp === null ? await startStallProfile(page) : null, stallFrom = Number(await page.evaluate('performance.now()'));
226
+ const frame = await page.evaluate(`(${sampleFrames.toString()})(${frames})`);
227
+ if (stallSession !== null) {
228
+ const read = await finishPlayProfile(page, stallSession, stallFrom);
229
+ console.log(` ${pose.name.padEnd(22)} play stall: worst ${(read.stall.busyMs / 1000).toFixed(2)} s busy of a 1.5 s window${read.faults.length === 0 ? '' : ` · ${read.faults.join('; ')} · ${read.leaves.join(', ')}`}`);
230
+ if (read.faults.length > 0) process.exitCode = 1;
231
+ }
232
+ if (cdp !== null && values.profile !== undefined) { const { profile } = await cdp.send('Profiler.stop'); writeFileSync(join(values.profile, `${shardName}-${pose.name}.cpuprofile`.replaceAll(/[^\w.-]+/gu, '_')), JSON.stringify(profile)); }
233
+ rows.push({ pose, frame });
234
+ console.log(` ${pose.name.padEnd(22)} ${(1000 / frame.p50).toFixed(0).padStart(4)} fps · p50 ${frame.p50} p95 ${frame.p95} max ${frame.max} ms · work p50 ${frame.workP50} (update ${frame.updateP50} render ${frame.renderP50}) p95 ${frame.workP95} · ${frame.calls} draws · ${(frame.triangles / 1e6).toFixed(2)} M tris · ratio ${frame.pixelRatio} ${frame.buffer.join('x')} (${frame.mpx} Mpx)`);
235
+ if (values.shots !== undefined) await page.screenshot({ path: join(values.shots, `${shardName}-${pose.name}.jpg`.replaceAll(/[^\w.-]+/gu, '_')), type: 'jpeg', quality: 82, scale: 'css' });
236
+ if (values.shots !== undefined && values.hide !== undefined) {
237
+ // --hide: every scene the frame draws (the shard's own and each region's), matching objects off every layer
238
+ const hidden = await page.evaluate(`(() => { const g = window.__wildshard.world.game, re = new RegExp(${JSON.stringify(values.hide)}, 'u'), names = new Map();
239
+ window.__deskHide = [];
240
+ for (const scene of [g.scene, ...(g.sceneFrames ?? []).map(f => f.scene)]) scene.traverse(o => { if (re.test(o.name)) { o.traverse(c => { window.__deskHide.push([c, c.layers.mask]); c.layers.mask = 0; }); names.set(o.name, (names.get(o.name) ?? 0) + 1); } });
241
+ return [...names].map(([n, c]) => n + ' x' + c).join(', '); })()`);
242
+ await sleep(600);
243
+ await page.screenshot({ path: join(values.shots, `${shardName}-${pose.name}-hidden.jpg`.replaceAll(/[^\w.-]+/gu, '_')), type: 'jpeg', quality: 82, scale: 'css' });
244
+ await page.evaluate(`(() => { for (const [o, m] of window.__deskHide) o.layers.mask = m; })()`);
245
+ console.log(` hidden: ${hidden === '' ? 'nothing matched' : hidden}`);
246
+ }
247
+ }
248
+ if (values.census) {
249
+ const c = await page.evaluate(`(${frameCensus.toString()})()`);
250
+ console.log(` census: ${c.objects} objects (${c.autoUpdate} auto-update), ${c.meshes} meshes (${c.visibleMeshes} visible), ${c.lights} lights, ${c.skinned} skinned, ${c.programs} programs, ${c.perFrame} renderer.render calls a frame`);
251
+ for (const k of c.calls.slice(0, Math.ceil(c.perFrame))) console.log(` ${k.scene} / ${k.camera} to ${k.target}: ${k.draws} draws, ${k.ms} ms`);
252
+ }
253
+ /** @type {any} */
254
+ let walk = null;
255
+ if (walkSeconds > 0) {
256
+ // --walk: from the spawn, walk forward turning slowly for N seconds (benchmax's input), every drawn interval kept, and
257
+ // Chromium's long animation frames (their scripts, by source position) for the hitches
258
+ await page.evaluate(`window.__wildshard.pose(${JSON.stringify(meta.spawn)})`);
259
+ await sleep(settle);
260
+ walk = await page.evaluate(`(${walkHitches.toString()})(${walkSeconds})`);
261
+ console.log(` walk ${walkSeconds} s: ${walk.frames} frames · p50 ${walk.p50} p95 ${walk.p95} p99 ${walk.p99} max ${walk.max} ms · over 33 ms ${walk.over33} · over 50 ms ${walk.over50} · over 100 ms ${walk.over100}`);
262
+ for (const loaf of walk.loafs.slice(0, 8)) console.log(` +${loaf.at} s ${loaf.duration} ms (blocking ${loaf.blocking}): ${loaf.scripts.map((/** @type {any} */ x) => `${x.fn}@${x.src} ${x.ms} ms`).join(' | ')}`);
263
+ }
264
+ /** @type {any} */
265
+ let ab = null;
266
+ if (values.ab) {
267
+ ab = await page.evaluate(`(${abCosts.toString()})(${sampleFrames.toString()})`);
268
+ console.log(' interleaved A/B at the last pose (median of 6 rounds, 60 frames each; saved ms = baseline minus variant):');
269
+ for (const v of ab) console.log(` ${v.variant.padEnd(34)} p50 ${v.p50} (saves ${v.saves}) · work ${v.work} · render ${v.render} · ${v.calls} draws`);
270
+ }
271
+ if (errors.length > 0) console.log(` page errors: ${errors.slice(0, 5).join(' | ')}`);
272
+ report.push({ shard: titles[target], meta, controlS, rows, walk, ab, errors });
273
+ await context.close();
274
+ }
275
+ } finally { await browser.close(); }
276
+ if (values.json !== undefined) writeFileSync(values.json, `${JSON.stringify(report, null, 1)}\n`);
@@ -7,7 +7,7 @@ export interface Span { start: number; end: number }
7
7
  /** A stage's worst window: its unexplained idle (ms) and where the window starts in the stage. */
8
8
  export interface StageStall { stage: string; from: number; idleMs: number; stageMs: number }
9
9
  /** A Chromium CPU profile, as `Profiler.stop` returns it. */
10
- export interface CpuProfile { nodes: readonly { id: number; callFrame: { functionName: string } }[]; samples?: readonly number[]; timeDeltas?: readonly number[]; startTime: number; endTime: number }
10
+ export interface CpuProfile { nodes: readonly { id: number; callFrame: { functionName: string; url?: string } }[]; samples?: readonly number[]; timeDeltas?: readonly number[]; startTime: number; endTime: number }
11
11
 
12
12
  /** The window a stall is judged over (ms). */
13
13
  export const STALL_WINDOW_MS: number;
@@ -17,8 +17,8 @@ export const STALL_IDLE_SHARE: number;
17
17
  export const STALL_STAGES: readonly string[];
18
18
  /** The page function the clock mark runs, by this name in the profile. */
19
19
  export const CLOCK_MARK: string;
20
- /** The page expression that runs the clock mark and returns its start on the page clock. */
21
- export const CLOCK_MARK_EXPRESSION: string;
20
+ /** A fresh page expression (new text each call) that runs the clock mark and returns its start on the page clock. */
21
+ export function clockMarkExpression(): string;
22
22
  /** Idle spans merged, minus holes, cut to [from, to]. */
23
23
  export function idleWithin(spans: readonly Span[], holes: readonly Span[], from: number, to: number): Span[];
24
24
  /** The most of the spans inside any window of `width`, and where that window starts. */
@@ -37,3 +37,17 @@ export function bootTimelineEntries(): StallEntry[];
37
37
  export function startStallProfile(page: Page): Promise<CDPSession | null>;
38
38
  /** End a stall profile at control: the ratcheted stages' worst windows and their faults. */
39
39
  export function finishStallProfile(page: Page, session: CDPSession): Promise<{ stalls: StageStall[]; faults: string[] }>;
40
+ /** NB6, play: a stretch of live frames' worst window of unbroken main-thread work (ms), where it starts, and play's length. */
41
+ export interface PlayStall { from: number; busyMs: number; playMs: number }
42
+ /** The share of the window unbroken main-thread work must reach to be a play stall. */
43
+ export const PLAY_BUSY_SHARE: number;
44
+ /** A profile's main-thread work on the page clock: neither idle, `(program)`, nor a WebGL call's native leaf. */
45
+ export function profileBusy(profile: CpuProfile, anchor: { pageMs: number; profileUs: number }): Span[];
46
+ /** Play's worst window of [from, to]. */
47
+ export function playStall(busy: readonly Span[], from: number, to: number): PlayStall;
48
+ /** A play stall at or over the share, as a fault line. */
49
+ export function playStallFaults(stall: PlayStall): string[];
50
+ /** End a play profile: play's worst window from `fromPageMs` and its fault. */
51
+ export function finishPlayProfile(page: Page, session: CDPSession, fromPageMs: number): Promise<{ stall: PlayStall; faults: string[]; leaves: string[] }>;
52
+ /** The leaves that held a window of a profile, most sampled first (at most three), as `name (file) ms`. */
53
+ export function busiestLeaves(profile: CpuProfile, anchor: { pageMs: number; profileUs: number }, at: number, width: number): string[];
@@ -108,10 +108,16 @@ export function profileIdle(profile, anchor) {
108
108
  return out;
109
109
  }
110
110
 
111
- /** The page expression that runs the clock mark: 30 ms busy inside CLOCK_MARK, returning its start on the page clock. */
112
- export const CLOCK_MARK_EXPRESSION = `(() => { const start = performance.now(), until = start + 30;
111
+ let clockMarks = 0;
112
+ /** The page expression that runs the clock mark: 30 ms busy inside CLOCK_MARK, returning its start on the page clock. Each
113
+ * call's text is new: V8 reuses a repeated eval's compiled script, and a second mark (play's profile after boot's) then
114
+ * ran with CLOCK_MARK inlined into its caller and never sampled by name (NB6).
115
+ * @returns {string} */
116
+ export function clockMarkExpression() {
117
+ return `/* clock mark ${++clockMarks} */ (() => { const start = performance.now(), until = start + 30;
113
118
  function ${CLOCK_MARK}() { while (performance.now() < until) { /* busy: the profiler samples this function */ } }
114
119
  ${CLOCK_MARK}(); return start; })()`;
120
+ }
115
121
 
116
122
  /** Browser-side: the page's boot timeline entries (its own collector, as Copy diagnostics reads it). */
117
123
  export function bootTimelineEntries() {
@@ -133,9 +139,82 @@ export async function startStallProfile(page) {
133
139
  /** End a stall profile at control: pin its clock with the mark, then the ratcheted stages' worst windows and their faults.
134
140
  * @param {import('playwright').Page} page @param {import('playwright').CDPSession} session */
135
141
  export async function finishStallProfile(page, session) {
136
- const markPageMs = Number(await page.evaluate(CLOCK_MARK_EXPRESSION));
142
+ const markPageMs = Number(await page.evaluate(clockMarkExpression()));
137
143
  const { profile } = await session.send('Profiler.stop');
138
144
  await session.detach().catch(() => undefined);
139
145
  const entries = await page.evaluate(bootTimelineEntries), idle = profileIdle(profile, profileAnchor(profile, markPageMs));
140
146
  return { stalls: stageStalls(entries, idle), faults: stallFaults(entries, idle) };
141
147
  }
148
+
149
+ // NINE-DRAGON-BENCHMAX NB6, widened to play (meta QA-FEEDBACK-2026-11-14 rows 2, 3, 5): a play stall is a stretch of live
150
+ // frames in which the page's main thread ran its own work without a break: script, layout, style or GC, but not idle and
151
+ // not a WebGL call waiting on the GPU process. A slow or software GPU (CI's SwiftShader draws a frame every few seconds)
152
+ // makes frames slower and the main thread idler or GPU-bound, not busier; a 2 s busy sleep in a frame is busy for its whole
153
+ // length whatever the GPU. Ring 1's boot smoke refuses one over the ten gameplay frames it already waits on, every case.
154
+ /** The share of a STALL_WINDOW_MS stretch of play that unbroken main-thread work must reach to be a stall. */
155
+ export const PLAY_BUSY_SHARE = 0.8;
156
+ /** Native leaves that are still the page's own work: the clock read a busy loop spins on, and the collector. Every other
157
+ * native leaf (no script url) is left out: on CI's SwiftShader any WebGL entry point can wait seconds on the GPU process
158
+ * (a link finishing under `getUniformLocation`, a fence under `getError`), and a named list missed some (ring 1, sunscar
159
+ * dunes, 2026-11-14: a 1.5 s "stall" 15 s into play at 2.4 s a frame). A page stall is script; its builtins undercount it. */
160
+ const PAGE_NATIVE = new Set(['now', '(garbage collector)']);
161
+
162
+ /** A Chromium CPU profile's main-thread work on the page clock: every sample whose leaf is script (it has a url) or one of
163
+ * PAGE_NATIVE, over [its time, the next sample's).
164
+ * @param {CpuProfile & { nodes: readonly { id: number, callFrame: { functionName: string, url?: string } }[] }} profile
165
+ * @param {{ pageMs: number, profileUs: number }} anchor @returns {Span[]} */
166
+ export function profileBusy(profile, anchor) {
167
+ const quiet = new Set(profile.nodes.filter(node => (node.callFrame.url ?? '') === '' && !PAGE_NATIVE.has(node.callFrame.functionName)).map(node => node.id));
168
+ const samples = profile.samples ?? [], page = (/** @type {number} */ us) => anchor.pageMs + (us - anchor.profileUs) / 1000;
169
+ let at = profile.startTime;
170
+ const times = (profile.timeDeltas ?? []).map(delta => (at += delta));
171
+ /** @type {Span[]} */ const out = [];
172
+ for (let i = 0; i + 1 < samples.length; i++) {
173
+ if (quiet.has(samples[i] ?? -1)) continue;
174
+ out.push({ start: page(times[i] ?? 0), end: page(times[i + 1] ?? 0) });
175
+ }
176
+ return merged(out);
177
+ }
178
+
179
+ /** Play's worst window: the most main-thread work in any STALL_WINDOW_MS stretch of [from, to].
180
+ * @param {readonly Span[]} busy @param {number} from @param {number} to @returns {{ from: number, busyMs: number, playMs: number }} */
181
+ export function playStall(busy, from, to) {
182
+ const worst = busiestWindow(idleWithin(busy, [], from, to), STALL_WINDOW_MS);
183
+ return { from: Math.max(0, worst.at - from), busyMs: worst.ms, playMs: to - from };
184
+ }
185
+
186
+ /** A play stall as a fault line, when its window's work reaches PLAY_BUSY_SHARE of it.
187
+ * @param {{ from: number, busyMs: number, playMs: number }} stall @returns {string[]} */
188
+ export function playStallFaults(stall) {
189
+ return stall.busyMs < STALL_WINDOW_MS * PLAY_BUSY_SHARE ? []
190
+ : [`Play stall: the main thread worked ${(stall.busyMs / 1000).toFixed(2)} s of a ${(STALL_WINDOW_MS / 1000).toFixed(1)} s window without a break (from +${(stall.from / 1000).toFixed(1)} s of ${(stall.playMs / 1000).toFixed(1)} s of play; NINE-DRAGON-BENCHMAX NB6)`];
191
+ }
192
+
193
+ /** End a play profile (started with `startStallProfile` at the first gameplay frame): pin its clock with the mark, then
194
+ * play's worst window and its fault.
195
+ * @param {import('playwright').Page} page @param {import('playwright').CDPSession} session @param {number} fromPageMs */
196
+ export async function finishPlayProfile(page, session, fromPageMs) {
197
+ const markPageMs = Number(await page.evaluate(clockMarkExpression()));
198
+ const { profile } = await session.send('Profiler.stop');
199
+ await session.detach().catch(() => undefined);
200
+ // the clock mark's own 30 ms of busy work ends the window
201
+ const anchor = profileAnchor(profile, markPageMs), stall = playStall(profileBusy(profile, anchor), fromPageMs, markPageMs);
202
+ return { stall, faults: playStallFaults(stall), leaves: busiestLeaves(profile, anchor, fromPageMs + stall.from, STALL_WINDOW_MS) };
203
+ }
204
+
205
+ /** The leaves that held a window of a profile, most sampled first, as `name (file) ms` (at most three): what a stall was.
206
+ * @param {CpuProfile & { nodes: readonly { id: number, callFrame: { functionName: string, url?: string } }[] }} profile
207
+ * @param {{ pageMs: number, profileUs: number }} anchor @param {number} at @param {number} width @returns {string[]} */
208
+ export function busiestLeaves(profile, anchor, at, width) {
209
+ const byId = new Map(profile.nodes.map(node => [node.id, node.callFrame])), held = new Map();
210
+ const samples = profile.samples ?? [];
211
+ let us = profile.startTime;
212
+ const times = (profile.timeDeltas ?? []).map(delta => (us += delta));
213
+ for (let i = 0; i + 1 < samples.length; i++) {
214
+ const start = anchor.pageMs + ((times[i] ?? 0) - anchor.profileUs) / 1000, end = anchor.pageMs + ((times[i + 1] ?? 0) - anchor.profileUs) / 1000;
215
+ if (end <= at || start >= at + width) continue;
216
+ const frame = byId.get(samples[i] ?? -1), name = frame === undefined ? '?' : `${frame.functionName || '(anonymous)'}${frame.url ? ` (${frame.url.split('/').pop()})` : ''}`;
217
+ held.set(name, (held.get(name) ?? 0) + Math.min(end, at + width) - Math.max(start, at));
218
+ }
219
+ return [...held].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([name, ms]) => `${name} ${Math.round(ms)} ms`);
220
+ }
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- """The look loop's Python logic: CIEDE2000 against Sharma, Wu and Dalal's (2005) reference pairs, the sRGB to Lab
3
- conversion, capture-pattern globbing, and targets.py's capture finding and seed-mode prompts. Run by
2
+ """The look loop's Python logic: targets.py's capture finding, seed-mode prompts and job polling. Run by
4
3
  test/look-loop.test.ts; standalone: python3 scripts/look-loop/test_look_loop.py"""
5
4
  import importlib.util
6
5
  import tempfile
@@ -17,47 +16,11 @@ def load(name, file):
17
16
  return mod
18
17
 
19
18
 
20
- try: # palette-delta.py needs numpy and Pillow; hosted CI's Python has neither, so its checks run where they exist
21
- import numpy, PIL # noqa: F401
22
- PD = load('palette_delta', 'palette-delta.py')
23
- except ImportError:
24
- PD = None
25
19
  TG = load('targets', 'targets.py')
26
20
  SCRATCH = HERE.parent.parent / 'tmp' if (HERE.parent.parent / 'tmp').is_dir() else None # the repo's tmp/, not /tmp
27
- NEEDS = unittest.skipUnless(PD, 'numpy and Pillow are not installed')
28
-
29
-
30
- @NEEDS
31
- class DeltaE(unittest.TestCase):
32
- def test_sharma_pairs(self):
33
- pairs = [
34
- ((50.0, 2.6772, -79.7751), (50.0, 0.0, -82.7485), 2.0425),
35
- ((50.0, 0.0, 0.0), (50.0, -1.0, 2.0), 2.3669),
36
- ((50.0, 2.5, 0.0), (73.0, 25.0, -18.0), 27.1492),
37
- ((60.2574, -34.0099, 36.2677), (60.4626, -34.1751, 39.4387), 1.2644),
38
- ]
39
- for a, b, want in pairs:
40
- self.assertAlmostEqual(PD.ciede2000(a, b), want, places=3)
41
- self.assertAlmostEqual(PD.ciede2000(b, a), want, places=3)
42
-
43
- def test_identity_and_lab(self):
44
- self.assertEqual(PD.ciede2000((40, 10, -5), (40, 10, -5)), 0.0)
45
- L, a, b = PD.srgb_to_lab((255, 255, 255))
46
- self.assertAlmostEqual(L, 100, delta=0.05); self.assertAlmostEqual(a, 0, delta=0.05); self.assertAlmostEqual(b, 0, delta=0.05)
47
- L, a, b = PD.srgb_to_lab((255, 0, 0))
48
- self.assertAlmostEqual(L, 53.24, delta=0.1); self.assertAlmostEqual(a, 80.09, delta=0.2); self.assertAlmostEqual(b, 67.20, delta=0.2)
49
21
 
50
22
 
51
23
  class Files(unittest.TestCase):
52
- @NEEDS
53
- def test_frame_path(self):
54
- with tempfile.TemporaryDirectory(dir=SCRATCH) as d:
55
- for name in ['capture-1-fp-front.jpg', 'r2-capture-1-fp-front.jpg']:
56
- (Path(d) / name).write_bytes(b'x')
57
- self.assertEqual(PD.frame_path(f'{d}/capture-{{n}}-*.jpg', 1).name, 'capture-1-fp-front.jpg')
58
- self.assertIsNone(PD.frame_path(f'{d}/capture-{{n}}-*.jpg', 2))
59
- self.assertEqual(PD.frame_path(f'{d}/r2-capture-{{n}}-*.jpg', 1).name, 'r2-capture-1-fp-front.jpg')
60
-
61
24
  def test_captures(self):
62
25
  with tempfile.TemporaryDirectory(dir=SCRATCH) as d:
63
26
  for name in ['capture-1-fp-front.jpg', 'capture-5-top.jpg', 'r2-capture-1-fp-front.jpg', 'mockup-1-fp-front.jpg']: