@null3d/engine 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/README.md +109 -0
  2. package/THIRD-PARTY-NOTICES.txt +0 -1
  3. package/dist/wasm/single/null3d.js +19 -6
  4. package/dist/wasm/single/null3d_bg.wasm +0 -0
  5. package/dist/wasm/threaded/null3d.js +19 -6
  6. package/dist/wasm/threaded/null3d_bg.wasm +0 -0
  7. package/docs/api/animation.md +23 -67
  8. package/docs/api/assets.md +42 -26
  9. package/docs/api/cameras.md +8 -6
  10. package/docs/api/controls.md +46 -44
  11. package/docs/api/debug.md +13 -8
  12. package/docs/api/engine.md +17 -11
  13. package/docs/api/feature-draws.md +3 -3
  14. package/docs/api/feature-effects.md +3 -3
  15. package/docs/api/feature-instances.md +2 -2
  16. package/docs/api/features.md +14 -15
  17. package/docs/api/geometry.md +56 -75
  18. package/docs/api/grass.md +1 -1
  19. package/docs/api/impostors.md +120 -9
  20. package/docs/api/input.md +4 -11
  21. package/docs/api/lights.md +14 -38
  22. package/docs/api/lines.md +8 -25
  23. package/docs/api/materials.md +69 -70
  24. package/docs/api/math.md +6 -7
  25. package/docs/api/objects.md +13 -13
  26. package/docs/api/particles.md +2 -14
  27. package/docs/api/points.md +3 -25
  28. package/docs/api/post.md +22 -23
  29. package/docs/api/quality.md +11 -6
  30. package/docs/api/raycast.md +13 -32
  31. package/docs/api/reference/animation.md +9 -9
  32. package/docs/api/reference/assets.md +18 -18
  33. package/docs/api/reference/cameras.md +5 -2
  34. package/docs/api/reference/controls.md +75 -23
  35. package/docs/api/reference/debug.md +23 -8
  36. package/docs/api/reference/engine.md +22 -10
  37. package/docs/api/reference/geometry.md +161 -82
  38. package/docs/api/reference/grass.md +1 -1
  39. package/docs/api/reference/impostors.md +92 -1
  40. package/docs/api/reference/input.md +3 -3
  41. package/docs/api/reference/lights.md +9 -9
  42. package/docs/api/reference/lines.md +7 -7
  43. package/docs/api/reference/materials.md +48 -48
  44. package/docs/api/reference/math.md +22 -22
  45. package/docs/api/reference/objects.md +9 -9
  46. package/docs/api/reference/points.md +4 -4
  47. package/docs/api/reference/post.md +18 -18
  48. package/docs/api/reference/quality.md +7 -3
  49. package/docs/api/reference/raycast.md +6 -6
  50. package/docs/api/reference/render.md +2 -2
  51. package/docs/api/reference/scene.md +29 -26
  52. package/docs/api/reference/sketch.md +4 -0
  53. package/docs/api/reference/sound.md +203 -0
  54. package/docs/api/reference/sprites.md +5 -5
  55. package/docs/api/reference/terrain.md +2 -1
  56. package/docs/api/reference/textures.md +4 -4
  57. package/docs/api/reference/ui.md +3 -3
  58. package/docs/api/reference/vertex-draws.md +3 -3
  59. package/docs/api/reference/water.md +77 -6
  60. package/docs/api/reference/wind.md +2 -2
  61. package/docs/api/render.md +12 -10
  62. package/docs/api/scene.md +40 -29
  63. package/docs/api/sketch.md +64 -3
  64. package/docs/api/sound.md +169 -0
  65. package/docs/api/splats.md +7 -0
  66. package/docs/api/sprites.md +4 -20
  67. package/docs/api/tasks.md +2 -2
  68. package/docs/api/terrain.md +2 -14
  69. package/docs/api/textures.md +9 -9
  70. package/docs/api/ui.md +3 -15
  71. package/docs/api/water.md +198 -15
  72. package/docs/api/wind.md +5 -5
  73. package/docs/cli/null3d.md +93 -18
  74. package/docs/concepts/architecture.md +10 -10
  75. package/docs/concepts/assets.md +2 -19
  76. package/docs/concepts/backends.md +7 -5
  77. package/docs/concepts/color-management.md +15 -26
  78. package/docs/concepts/culling.md +1 -1
  79. package/docs/concepts/instances.md +5 -5
  80. package/docs/concepts/large-worlds.md +1 -1
  81. package/docs/concepts/lighting.md +50 -55
  82. package/docs/concepts/lod.md +2 -15
  83. package/docs/concepts/materials.md +16 -16
  84. package/docs/concepts/post-processing.md +7 -29
  85. package/docs/concepts/quality-preset-tables.md +53 -50
  86. package/docs/concepts/quality-presets.md +56 -27
  87. package/docs/concepts/render-graph.md +19 -14
  88. package/docs/concepts/render-layers.md +3 -17
  89. package/docs/concepts/shadows.md +10 -28
  90. package/docs/concepts/static-dynamic.md +2 -2
  91. package/docs/cookbook/index.md +1 -1
  92. package/docs/data/threejs-mapping.json +136 -102
  93. package/docs/errors/E1214.md +3 -3
  94. package/docs/errors/E1307.md +23 -0
  95. package/docs/errors/E1420.md +3 -3
  96. package/docs/errors/index.md +3 -2
  97. package/docs/getting-started/cdn.md +17 -1
  98. package/docs/getting-started/first-scene.md +1 -1
  99. package/docs/getting-started/hosting.md +50 -9
  100. package/docs/getting-started/install.md +8 -7
  101. package/docs/getting-started/network-use.md +10 -2
  102. package/docs/getting-started/project-structure.md +15 -6
  103. package/docs/getting-started/third-party-notices.md +8 -6
  104. package/docs/guides/accessibility.md +1 -1
  105. package/docs/guides/add-ons.md +3 -2
  106. package/docs/guides/agents.md +16 -5
  107. package/docs/guides/assets-pipeline.md +13 -12
  108. package/docs/guides/audio.md +109 -124
  109. package/docs/guides/car-paint.md +1 -1
  110. package/docs/guides/content-pages.md +10 -6
  111. package/docs/guides/custom-passes.md +9 -8
  112. package/docs/guides/custom-shaders.md +6 -3
  113. package/docs/guides/debugging.md +78 -4
  114. package/docs/guides/deploying.md +105 -5
  115. package/docs/guides/deterministic-simulation.md +1 -1
  116. package/docs/guides/first-use-shaders.md +4 -4
  117. package/docs/guides/loading-screens.md +78 -33
  118. package/docs/guides/multiple-views.md +41 -2
  119. package/docs/guides/performance.md +6 -3
  120. package/docs/guides/phones.md +12 -1
  121. package/docs/guides/physics.md +1 -1
  122. package/docs/guides/screens.md +7 -5
  123. package/docs/guides/start-time.md +328 -0
  124. package/docs/guides/testing.md +23 -5
  125. package/docs/guides/ui-overlays.md +3 -3
  126. package/docs/index.md +12 -8
  127. package/docs/pages.md +26 -23
  128. package/docs/porting/react-three-fiber.md +228 -5
  129. package/docs/porting/threejs-loop-and-threads.md +220 -6
  130. package/docs/porting/threejs-mapping.md +86 -84
  131. package/docs/porting/threejs-materials.md +212 -5
  132. package/docs/porting/threejs-overview.md +218 -5
  133. package/docs/porting/threejs-postprocessing.md +2 -2
  134. package/docs/porting/threejs-shaders.md +298 -5
  135. package/docs/porting/threejs-unsupported.md +82 -6
  136. package/docs/porting/verification.md +181 -5
  137. package/docs/shaders/builtins.md +1 -1
  138. package/docs/shaders/library.md +63 -39
  139. package/docs/shaders/surface-functions.md +11 -10
  140. package/docs/shaders/wgsl-rules.md +1 -1
  141. package/lib/debug/channel.d.ts +103 -0
  142. package/lib/debug/channel.js +269 -0
  143. package/lib/debug/debug.d.ts +9 -7
  144. package/lib/debug/draw.d.ts +9 -0
  145. package/lib/debug/draw.js +49 -2
  146. package/lib/debug/inspector.d.ts +60 -0
  147. package/lib/debug/inspector.js +475 -0
  148. package/lib/debug/stats-panel.d.ts +1 -1
  149. package/lib/debug/stats.d.ts +2 -3
  150. package/lib/errors/codes.js +8 -2
  151. package/lib/errors/engine-error.js +25 -10
  152. package/lib/errors/fixes.d.ts +1 -0
  153. package/lib/errors/fixes.js +3 -2
  154. package/lib/generated/core.d.ts +1 -1
  155. package/lib/generated/core.js +1 -1
  156. package/lib/gpu/early-builds.d.ts +68 -0
  157. package/lib/gpu/early-builds.js +158 -0
  158. package/lib/gpu/pipeline-name.d.ts +6 -0
  159. package/lib/gpu/pipeline-name.js +23 -0
  160. package/lib/gpu/webgl2/backend.d.ts +63 -2
  161. package/lib/gpu/webgl2/backend.js +226 -8
  162. package/lib/gpu/webgl2/programs.d.ts +18 -0
  163. package/lib/gpu/webgl2/programs.js +4 -1
  164. package/lib/gpu/webgpu/backend.d.ts +89 -2
  165. package/lib/gpu/webgpu/backend.js +255 -8
  166. package/lib/gpu/webgpu/pipelines.d.ts +13 -0
  167. package/lib/gpu/webgpu/pipelines.js +15 -1
  168. package/lib/index.d.ts +6 -4
  169. package/lib/index.js +3 -2
  170. package/lib/math/color.d.ts +5 -5
  171. package/lib/math/color.js +5 -5
  172. package/lib/math/mat4.d.ts +6 -12
  173. package/lib/math/mat4.js +6 -12
  174. package/lib/math/namespaces/quat.d.ts +3 -3
  175. package/lib/math/namespaces/quat.js +3 -3
  176. package/lib/math/quat.d.ts +8 -12
  177. package/lib/math/quat.js +8 -12
  178. package/lib/math/random.d.ts +2 -3
  179. package/lib/math/random.js +2 -3
  180. package/lib/math/types.d.ts +4 -4
  181. package/lib/math/vec3.d.ts +3 -6
  182. package/lib/math/vec3.js +3 -6
  183. package/lib/page/capabilities.d.ts +7 -7
  184. package/lib/page/capabilities.js +39 -25
  185. package/lib/page/check-store.d.ts +14 -2
  186. package/lib/page/check-store.js +34 -11
  187. package/lib/page/engine.d.ts +103 -26
  188. package/lib/page/engine.js +420 -97
  189. package/lib/page/first-frame.d.ts +16 -0
  190. package/lib/page/first-frame.js +35 -0
  191. package/lib/page/frame-stats.d.ts +34 -1
  192. package/lib/page/frame-stats.js +15 -0
  193. package/lib/page/label-loop.d.ts +7 -3
  194. package/lib/page/label-loop.js +17 -10
  195. package/lib/page/labels.d.ts +3 -3
  196. package/lib/page/pipeline-store.d.ts +25 -0
  197. package/lib/page/pipeline-store.js +84 -0
  198. package/lib/page/start-marker.d.ts +4 -1
  199. package/lib/page/start-marker.js +5 -2
  200. package/lib/page/switches.d.ts +32 -2
  201. package/lib/page/switches.js +9 -1
  202. package/lib/quality/check.d.ts +24 -3
  203. package/lib/quality/check.js +21 -7
  204. package/lib/quality/chooser.d.ts +6 -0
  205. package/lib/quality/chooser.js +8 -0
  206. package/lib/quality/governor.d.ts +98 -6
  207. package/lib/quality/governor.js +250 -20
  208. package/lib/quality/preset-docs.d.ts +16 -1
  209. package/lib/quality/preset-docs.js +3 -0
  210. package/lib/quality/presets.d.ts +84 -7
  211. package/lib/quality/presets.js +94 -2
  212. package/lib/render/draw.d.ts +3 -2
  213. package/lib/render/draw.js +15 -5
  214. package/lib/render/load-draw.d.ts +7 -5
  215. package/lib/render/load-draw.js +7 -5
  216. package/lib/render/loss.d.ts +28 -10
  217. package/lib/render/loss.js +50 -22
  218. package/lib/render/recovery.d.ts +20 -0
  219. package/lib/render/recovery.js +44 -4
  220. package/lib/render/renderer.d.ts +85 -9
  221. package/lib/render/renderer.js +181 -42
  222. package/lib/render/scene-renderer.d.ts +19 -1
  223. package/lib/render/scene-renderer.js +25 -1
  224. package/lib/render/webgl2-renderers.js +8 -5
  225. package/lib/render/webgpu-renderers.js +5 -4
  226. package/lib/scene/animation.d.ts +28 -32
  227. package/lib/scene/animation.js +12 -15
  228. package/lib/scene/assets.d.ts +61 -86
  229. package/lib/scene/assets.js +103 -236
  230. package/lib/scene/background.d.ts +14 -18
  231. package/lib/scene/background.js +5 -2
  232. package/lib/scene/color.d.ts +3 -3
  233. package/lib/scene/downloads.d.ts +2 -0
  234. package/lib/scene/downloads.js +371 -0
  235. package/lib/scene/environment.d.ts +7 -7
  236. package/lib/scene/environment.js +1 -1
  237. package/lib/scene/fake-call-values.js +1 -1
  238. package/lib/scene/fog.d.ts +11 -4
  239. package/lib/scene/fog.js +8 -2
  240. package/lib/scene/frame-cameras.d.ts +19 -0
  241. package/lib/scene/frame-cameras.js +58 -0
  242. package/lib/scene/gltf.d.ts +32 -2
  243. package/lib/scene/gltf.js +78 -49
  244. package/lib/scene/grading.d.ts +2 -2
  245. package/lib/scene/grading.js +3 -3
  246. package/lib/scene/ktx2.d.ts +9 -1
  247. package/lib/scene/ktx2.js +3 -2
  248. package/lib/scene/level-rule.d.ts +120 -0
  249. package/lib/scene/level-rule.js +130 -0
  250. package/lib/scene/lines.d.ts +13 -17
  251. package/lib/scene/lines.js +3 -3
  252. package/lib/scene/lut.d.ts +1 -2
  253. package/lib/scene/lut.js +1 -2
  254. package/lib/scene/picks.d.ts +2 -2
  255. package/lib/scene/pointer-events.d.ts +4 -7
  256. package/lib/scene/post.d.ts +38 -43
  257. package/lib/scene/post.js +4 -1
  258. package/lib/scene/prefab.d.ts +7 -8
  259. package/lib/scene/prefab.js +7 -8
  260. package/lib/scene/property-animation.d.ts +1 -1
  261. package/lib/scene/property-animation.js +1 -1
  262. package/lib/scene/queries.d.ts +7 -13
  263. package/lib/scene/resources.d.ts +225 -254
  264. package/lib/scene/resources.js +179 -81
  265. package/lib/scene/scene.d.ts +149 -118
  266. package/lib/scene/scene.js +196 -98
  267. package/lib/scene/serial-loads.d.ts +29 -0
  268. package/lib/scene/serial-loads.js +68 -0
  269. package/lib/scene/shader-preloads.d.ts +34 -0
  270. package/lib/scene/shader-preloads.js +38 -0
  271. package/lib/scene/sprites.d.ts +14 -17
  272. package/lib/scene/sprites.js +5 -6
  273. package/lib/scene/textures.d.ts +11 -12
  274. package/lib/scene/textures.js +9 -10
  275. package/lib/scene/time-of-day.d.ts +3 -4
  276. package/lib/scene/time-of-day.js +2 -3
  277. package/lib/scene/vertex-draws.d.ts +5 -4
  278. package/lib/scene/vertex-draws.js +7 -5
  279. package/lib/shader-artifact.json +1 -0
  280. package/lib/shared/core.d.ts +5 -0
  281. package/lib/shared/core.js +1 -0
  282. package/lib/shared/import-once.d.ts +6 -0
  283. package/lib/shared/import-once.js +19 -0
  284. package/lib/shared/metrics.d.ts +38 -0
  285. package/lib/shared/metrics.js +62 -1
  286. package/lib/shared/run-task.js +7 -1
  287. package/lib/shared/task-pending.d.ts +12 -0
  288. package/lib/shared/task-pending.js +61 -1
  289. package/lib/shared/tasks.js +79 -32
  290. package/lib/shared/version.d.ts +17 -1
  291. package/lib/shared/version.js +19 -1
  292. package/lib/shared/wasm.d.ts +12 -4
  293. package/lib/shared/wasm.js +50 -27
  294. package/lib/shared/worker-start.d.ts +7 -0
  295. package/lib/shared/worker-start.js +27 -0
  296. package/lib/sketch/define-sketch.d.ts +35 -0
  297. package/lib/sketch/input.d.ts +2 -2
  298. package/lib/sketch/preset-check.d.ts +20 -6
  299. package/lib/sketch/preset-check.js +42 -17
  300. package/lib/sketch/quality.d.ts +69 -11
  301. package/lib/sketch/quality.js +54 -13
  302. package/lib/sketch/runner.d.ts +76 -9
  303. package/lib/sketch/runner.js +385 -52
  304. package/lib/sketch/ui.d.ts +5 -8
  305. package/lib/workers/probe-worker.d.ts +5 -0
  306. package/lib/workers/probe-worker.js +13 -4
  307. package/lib/workers/protocol.d.ts +61 -13
  308. package/lib/workers/protocol.js +4 -0
  309. package/lib/workers/render-worker.js +25 -4
  310. package/lib/workers/sketch-worker.js +104 -15
  311. package/package.json +2 -2
@@ -2,17 +2,25 @@
2
2
  // and the quality preset, starts the workers, and hands the canvas to the thread that draws. The
3
3
  // page loads the renderer only when it draws itself, and the sketch runner and the scene API only
4
4
  // when it runs the sketch itself: in the single-threaded build, and with sketchThread: 'main'.
5
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
6
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
7
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
8
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
9
+ });
10
+ }
11
+ return path;
12
+ };
5
13
  import { DEV } from '../errors/checks.js';
6
14
  import { EngineError, errorFixesReady, errorOfMessage } from '../errors/engine-error.js';
7
15
  import { messageOf } from '../errors/message.js';
8
16
  import { FORMAT_CANVAS, PERMUTATION_HALF } from '../generated/gpu.js';
9
17
  import { SHADER_FEATURES } from '../generated/shader-features.js';
10
18
  import { recordPermutations, stopRecordingPermutations } from '../gpu/variants.js';
11
- import { maxTargetFps } from '../quality/check.js';
12
- import { choosePreset, crashTier, deviceKind, gpuOcclusionChoice, memoryPreset, textureMemoryCap, withinTier, } from '../quality/chooser.js';
19
+ import { maxTargetFps, } from '../quality/check.js';
20
+ import { choosePreset, crashLowest, crashTier, deviceKind, gpuOcclusionChoice, memoryPreset, textureMemoryCap, withinTier, } from '../quality/chooser.js';
13
21
  import { readDeviceHints } from '../quality/device-hints.js';
14
- import { capTextureMemory, checkedSettings, checkSettings, presetOption, presetValue, targetFpsOption, } from '../quality/presets.js';
15
- import { loadDrawModule, preloadDeviceFiles } from '../render/load-draw.js';
22
+ import { capTextureMemory, checkedSettings, checkSettings, lowestTierSettings, presetCheckOption, presetOption, presetValue, targetFpsOption, } from '../quality/presets.js';
23
+ import { loadDrawModule, preloadDrawing } from '../render/load-draw.js';
16
24
  import { awaitLater } from '../shared/await-later.js';
17
25
  import { controlViews, createControlBuffer, Slot } from '../shared/control.js';
18
26
  import { loadGlue, startCore } from '../shared/core.js';
@@ -25,18 +33,19 @@ import { memoryBytes } from '../shared/memory-views.js';
25
33
  import { createMetricsBuffer, MetricsReader, threadRoles } from '../shared/metrics.js';
26
34
  import { addMeasurementRelease } from '../shared/page-measurement.js';
27
35
  import { clearJobTasks, jobAsker, setJobTasks } from '../shared/task-host.js';
28
- import { onAddonChecked } from '../shared/version.js';
36
+ import { hearAddonsEarly, onAddonChecked } from '../shared/version.js';
29
37
  import { VIDEO_FOLLOW } from '../shared/videos.js';
30
38
  import { notifySlot, setWakeByMessage } from '../shared/wake.js';
31
39
  import { WGSL_UPDATE_EVENT } from '../shared/wgsl-updates.js';
32
- import { spawnWorker, startedWorkerScript, watchWorkerError } from '../shared/worker-start.js';
40
+ import { spawnWorker, startedWorkerScript, watchWorkerError, workerScriptOf, } from '../shared/worker-start.js';
33
41
  import { loadSketch } from '../sketch/define-sketch.js';
34
42
  import { abortable } from './abortable.js';
35
43
  import { checkBrowser } from './browser-check.js';
36
44
  import { watchCanvas } from './canvas-watch.js';
37
45
  import { forgetWorkerProbe, probeCapabilities, } from './capabilities.js';
38
- import { CheckStore, checkConditions } from './check-store.js';
46
+ import { CheckStore, checkConditions, checkEnded, checkedPreset } from './check-store.js';
39
47
  import { watchDisplay } from './display.js';
48
+ import { FirstFrame } from './first-frame.js';
40
49
  import { holdFailure, holdSeconds, publishHold, holdScript as readHoldScript, } from './hold.js';
41
50
  import { captureInput } from './input.js';
42
51
  import { lostIsolationWarning, pageIsolation } from './isolation-check.js';
@@ -47,6 +56,7 @@ import { MainThreadWatch } from './main-thread.js';
47
56
  import { keepMemory, releaseMemories } from './memory-pool.js';
48
57
  import { canvasHold, Holder, parkWorker, takeParkedWorker, takeWhenFree, } from './ownership.js';
49
58
  import { PermutationRecording } from './permutation-recording.js';
59
+ import { PipelineStore, pipelineConditions } from './pipeline-store.js';
50
60
  import { requestPointerLock } from './pointer-lock.js';
51
61
  import { watchPreferences } from './preferences.js';
52
62
  import { NO_HISTORY, StartMarker } from './start-marker.js';
@@ -65,6 +75,8 @@ let warnedFallback = false;
65
75
  let warnedIsolation = false;
66
76
  /** The global where the `?bench` switch publishes the running engine. */
67
77
  const BENCH_GLOBAL = '__null3dEngine';
78
+ /** The global where a development build publishes its inspection bridge, for the MCP server. */
79
+ const INSPECTOR_GLOBAL = '__null3dInspector';
68
80
  /** The GPU the engine asks for on a device with two: the faster one. */
69
81
  const DEFAULT_POWER_PREFERENCE = 'high-performance';
70
82
  /** How often the page reads the frame records while it measures. */
@@ -89,6 +101,19 @@ const MAX_EARLY_MESSAGES = 256;
89
101
  * the page to wait with no end.
90
102
  */
91
103
  export const WORKER_REPLY_LIMIT_MS = 600_000;
104
+ /**
105
+ * How long an inspection call waits for the sketch worker's answer. A call runs between frames, but
106
+ * a quality change waits for the pipelines that it needs, so this is longer than a frame and far
107
+ * shorter than the limit that a start or a capture gets.
108
+ */
109
+ const INSPECT_REPLY_LIMIT_MS = 30_000;
110
+ /**
111
+ * How long a copy of a worker whose script did not load may take to report its first reply. A
112
+ * script that loads reports in about a second on the slowest machines that run the tests, so a
113
+ * copy that has sent nothing by this time never ran: the page fails the start with E1405 rather
114
+ * than waiting for a worker that may never speak.
115
+ */
116
+ export const RETRY_REPLY_MS = 10_000;
92
117
  /** Picks the GPU tier from feature tests, never from browser or GPU names. */
93
118
  export function chooseTier(report, wanted, inWorker) {
94
119
  const worker = 'failure' in report.worker ? undefined : report.worker;
@@ -147,13 +172,19 @@ function loadFrameStats() {
147
172
  return import('./frame-stats.js');
148
173
  }
149
174
  /**
150
- * The error of a GPU that ran out of memory (E1304) or rejected a command (E1305), on `thread`, such
151
- * as "the render worker".
175
+ * The error of a GPU that ran out of memory (E1304), rejected a command (E1305), or whose driver
176
+ * could not build a pipeline of the scene's objects (E1307), on `thread`, such as "the render
177
+ * worker". `message` names the pipeline for E1307.
152
178
  */
153
- export function gpuFailure(thread, outOfMemory, message) {
154
- return outOfMemory
155
- ? new EngineError('E1304', `${thread}'s GPU ran out of memory: ${message}.`)
156
- : new EngineError('E1305', `${thread}'s GPU rejected a command: ${message}.`);
179
+ export function gpuFailure(thread, kind, message) {
180
+ switch (kind) {
181
+ case 'memory':
182
+ return new EngineError('E1304', `${thread}'s GPU ran out of memory: ${message}.`);
183
+ case 'rejected':
184
+ return new EngineError('E1305', `${thread}'s GPU rejected a command: ${message}.`);
185
+ case 'pipeline':
186
+ return new EngineError('E1307', `${thread}'s GPU driver could not build the pipeline of ${message}.`);
187
+ }
157
188
  }
158
189
  /**
159
190
  * A worker whose replies are routed: events to the page's handlers, answers to the oldest request.
@@ -165,6 +196,12 @@ export class EngineWorker {
165
196
  script;
166
197
  restart;
167
198
  waiting = [];
199
+ /**
200
+ * The inspection calls that wait for their answers, by their id. A production build never makes
201
+ * one, so the map is made at the first call.
202
+ */
203
+ inspectWaiters;
204
+ nextInspect = 1;
168
205
  readyPromise;
169
206
  stoppedPromise;
170
207
  worker;
@@ -178,6 +215,8 @@ export class EngineWorker {
178
215
  scriptLoaded = false;
179
216
  /** True once the page replaced a worker whose script did not load. */
180
217
  retried = false;
218
+ /** Clears the wait for the replacement worker's first reply, or undefined once it has one. */
219
+ retryTimer;
181
220
  /**
182
221
  * The messages that the page sent before the worker reported that its script loaded. A worker
183
222
  * that has not run its script cannot take them, so they wait here: a copy that replaces a
@@ -228,6 +267,9 @@ export class EngineWorker {
228
267
  };
229
268
  const listen = (worker) => {
230
269
  worker.onmessage = (event) => {
270
+ // A worker that answers at all has run its script: the replacement no longer needs
271
+ // its error's wait, and its own error listener names whatever fails next.
272
+ this.heardReply();
231
273
  const reply = event.data;
232
274
  switch (reply.type) {
233
275
  case 'recorded':
@@ -262,12 +304,15 @@ export class EngineWorker {
262
304
  case 'recording':
263
305
  events.recording?.(reply.bytes);
264
306
  return;
307
+ case 'inspect-reply':
308
+ this.answerInspect(reply);
309
+ return;
265
310
  case 'lost':
266
311
  forgetWorkerProbe();
267
312
  events.failure(new EngineError('E1302', `the ${reply.role} worker lost its GPU: ${reply.reason}.`));
268
313
  return;
269
314
  case 'gpu-error':
270
- events.failure(gpuFailure(`the ${reply.role} worker`, reply.outOfMemory, reply.message), false);
315
+ events.failure(gpuFailure(`the ${reply.role} worker`, reply.kind, reply.message), false);
271
316
  return;
272
317
  case 'fault':
273
318
  // A job worker that failed has left the job system, so a stop need not wait for it.
@@ -275,6 +320,9 @@ export class EngineWorker {
275
320
  markStopped();
276
321
  failed(reply.message);
277
322
  return;
323
+ case 'pipeline-list':
324
+ events.pipelineList?.(reply.list);
325
+ return;
278
326
  case 'progress':
279
327
  // The first step says that the worker's script and the files that it imports
280
328
  // ran, so the worker can now take the messages held for it.
@@ -305,6 +353,7 @@ export class EngineWorker {
305
353
  };
306
354
  this.unwatch?.();
307
355
  this.unwatch = watchWorkerError(worker, (message) => {
356
+ this.heardReply();
308
357
  // A worker whose script, or a file that the script imports, did not load fails before
309
358
  // it reports its first step. That fault comes and goes, so the worker gets one more
310
359
  // copy before the page reports it, whatever the browser's message says. A failure
@@ -312,12 +361,22 @@ export class EngineWorker {
312
361
  // the copy the same way, so it is reported at once.
313
362
  if (!this.scriptLoaded && this.restart && !this.retried && !errorOfMessage(message)) {
314
363
  this.retried = true;
315
- worker.terminate();
364
+ // The copy starts while the failed worker still runs. A browser can keep a
365
+ // stopped module worker's failed script load in its cache, and a copy started
366
+ // after that stop then waits for a script that never arrives.
316
367
  try {
317
368
  const copy = this.restart();
318
369
  this.worker = copy;
319
370
  listen(copy);
371
+ // A copy that never speaks fails the start with E1405, rather than leaving
372
+ // the page to wait for a worker that may never answer.
373
+ this.retryTimer = setTimeout(() => {
374
+ this.retryTimer = undefined;
375
+ failed(this.stalledFailure());
376
+ this.answerStop?.();
377
+ }, RETRY_REPLY_MS);
320
378
  events.workerRestart?.(this.role, this.script === undefined ? '' : String(this.script));
379
+ worker.terminate();
321
380
  return;
322
381
  }
323
382
  catch {
@@ -347,11 +406,31 @@ export class EngineWorker {
347
406
  : 'its script, or a file that it imports, did not load';
348
407
  return this.retried ? `${at}, and a second copy failed too` : at;
349
408
  }
409
+ /**
410
+ * What the page reports when the copy that replaced a worker whose script did not load has sent
411
+ * nothing within the wait. The first failure named the script; the copy's silence names it too,
412
+ * so a wrong path stays visible and a stall is not read as a wrong path.
413
+ */
414
+ stalledFailure() {
415
+ const script = this.script === undefined ? '' : String(this.script);
416
+ const at = script
417
+ ? `its script at ${script}, or a file that it imports, did not load`
418
+ : 'its script, or a file that it imports, did not load';
419
+ return `${at}, and a second copy sent nothing within ${RETRY_REPLY_MS / 1000} s`;
420
+ }
421
+ /** Ends the wait for a replacement worker's first reply, once one arrives or the worker fails. */
422
+ heardReply() {
423
+ if (this.retryTimer === undefined)
424
+ return;
425
+ clearTimeout(this.retryTimer);
426
+ this.retryTimer = undefined;
427
+ }
350
428
  /**
351
429
  * Drops the handlers that reach this engine, so a worker that the page keeps, such as a drawing
352
430
  * worker parked with its canvas, holds none of the engine or its shared memory alive.
353
431
  */
354
432
  detach() {
433
+ this.heardReply();
355
434
  this.unwatch?.();
356
435
  this.unwatch = undefined;
357
436
  this.worker.onmessage = null;
@@ -417,9 +496,49 @@ export class EngineWorker {
417
496
  }
418
497
  /** Stops the worker, and fails each request that still waits for its answer. */
419
498
  terminate() {
499
+ this.heardReply();
420
500
  this.worker.terminate();
421
501
  for (const pending of this.waiting.splice(0))
422
502
  pending.reject(new Error('the engine stopped'));
503
+ const waiters = this.inspectWaiters;
504
+ if (waiters !== undefined) {
505
+ for (const waiter of waiters.values()) {
506
+ clearTimeout(waiter.timer);
507
+ waiter.reject(new Error('the engine stopped'));
508
+ }
509
+ waiters.clear();
510
+ }
511
+ }
512
+ /**
513
+ * Runs a development build's inspection call in this worker, and waits for its answer. The
514
+ * worker answers with the value of the call, or why it failed.
515
+ */
516
+ inspect(call, args) {
517
+ if (this.inspectWaiters === undefined)
518
+ this.inspectWaiters = new Map();
519
+ const waiters = this.inspectWaiters;
520
+ return new Promise((resolve, reject) => {
521
+ const id = this.nextInspect++;
522
+ const timer = setTimeout(() => {
523
+ waiters.delete(id);
524
+ reject(new Error(`the ${this.role} worker did not answer the ${call} inspection within ${INSPECT_REPLY_LIMIT_MS / 1000} s`));
525
+ }, INSPECT_REPLY_LIMIT_MS);
526
+ waiters.set(id, { resolve, reject, timer });
527
+ this.send({ type: 'inspect', id, call, args });
528
+ });
529
+ }
530
+ /** Gives an inspection call its answer. */
531
+ answerInspect(reply) {
532
+ const waiters = this.inspectWaiters;
533
+ const waiter = waiters?.get(reply.id);
534
+ if (waiter === undefined)
535
+ return;
536
+ waiters?.delete(reply.id);
537
+ clearTimeout(waiter.timer);
538
+ if (reply.ok)
539
+ waiter.resolve(reply.result);
540
+ else
541
+ waiter.reject(new Error(reply.error ?? 'the inspection call failed'));
423
542
  }
424
543
  /**
425
544
  * Sends a request and waits for the worker's answer, which ends with a failure once the answer
@@ -565,12 +684,9 @@ function allWorkers(workers) {
565
684
  function startJobWorker(index, slots, events, started) {
566
685
  const failed = (error) => {
567
686
  if (Atomics.load(slots, Slot.Running) !== 0)
568
- events.failure(error instanceof EngineError ? error : startError(`job ${index}`, messageOf(error)), false);
687
+ events.failure(error instanceof EngineError ? error : startError(`job ${index}`, messageOf(error)), false, false);
569
688
  };
570
- const start = () => new Worker(new URL('../workers/job-worker.js', import.meta.url), {
571
- type: 'module',
572
- name: `null3d-job-${index}`,
573
- });
689
+ const start = () => newJobWorker(index);
574
690
  try {
575
691
  const first = startEngineWorker(start);
576
692
  const job = new EngineWorker(first.worker, `job ${index}`, first.script, events, () => startEngineWorker(start).worker);
@@ -582,6 +698,13 @@ function startJobWorker(index, slots, events, started) {
582
698
  return undefined;
583
699
  }
584
700
  }
701
+ /** Constructs job worker `index`, in the form that bundlers read. */
702
+ function newJobWorker(index) {
703
+ return new Worker(new URL('../workers/job-worker.js', import.meta.url), {
704
+ type: 'module',
705
+ name: `null3d-job-${index}`,
706
+ });
707
+ }
585
708
  /**
586
709
  * Starts an engine worker from a start function, with the engine's own error codes for a failure
587
710
  * of a worker's bootstrap from another origin.
@@ -819,6 +942,10 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
819
942
  const replay = modes.replay === undefined ? undefined : await readReplay(modes.replay, sketchUrl);
820
943
  // A replay records nothing of its own: it runs a file that already holds the frames and input.
821
944
  const record = modes.record && replay === undefined;
945
+ // A live start loads the sketch's module while the core downloads, so the module's imports and
946
+ // its top-level code run meanwhile. Hold mode, a replay and a recording load it once the runner
947
+ // has seeded the thread's random numbers, so that code draws the same numbers on every run.
948
+ const moduleFirst = hold === undefined && replay === undefined && !record;
822
949
  // The quality preset follows the device hints and the crash marker, which the page has at once,
823
950
  // so its memory maximum is known before the core loads. Hold mode and the ?preset= switch fix
824
951
  // the preset for tests, so they neither read nor write the marker.
@@ -830,6 +957,8 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
830
957
  // The highest frame rate that the preset check, the governor and the stats overlay aim for.
831
958
  const optionTarget = targetFpsOption(options.targetFps);
832
959
  const maxTarget = maxTargetFps(switches.targetFps ?? optionTarget, switches.fps);
960
+ const optionCheck = presetCheckOption(options.presetCheck);
961
+ const checkTiming = switches.presetCheck ?? optionCheck ?? 'during-play';
833
962
  const pageSettings = {
834
963
  maxPixelRatio: options.maxPixelRatio,
835
964
  antialias: options.antialias,
@@ -877,19 +1006,16 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
877
1006
  }));
878
1007
  // A page that runs the sketch itself needs the core's loader, the sketch runner and the sketch
879
1008
  // module right after the core, so they download while the core does: each later start delays the
880
- // first frame by a round trip on a slow network. The sketch module's top-level code then runs when
881
- // the module arrives. Hold mode loads the module once the runner has seeded the thread's random
882
- // numbers, so that code draws the same numbers on every run.
1009
+ // first frame by a round trip on a slow network. A live sketch module's top-level code then runs
1010
+ // when the module arrives.
883
1011
  if (sketchOnPage)
884
1012
  void awaitLater(loadGlue(build));
885
1013
  const runnerModule = sketchOnPage ? loadRunnerModule() : undefined;
886
1014
  // A development build with input off hears each add-on that the sketch's module loads, such as
887
1015
  // @null3d/controls, from before the load begins, and hands them to the runner once it exists.
888
- let earlyAddons;
889
- if (DEV && sketchOnPage && hold === undefined && options.input === false) {
890
- const heard = [];
891
- earlyAddons = heard;
892
- stopEarlyAddons = onAddonChecked((name) => heard.push(name));
1016
+ const earlyAddons = DEV && sketchOnPage && moduleFirst && options.input === false ? hearAddonsEarly() : undefined;
1017
+ if (earlyAddons) {
1018
+ stopEarlyAddons = earlyAddons.stop;
893
1019
  // The start runs on with no wait to the try below, whose failure stops the engine and this
894
1020
  // hearing with it. A start that throws before that try ends the hearing here.
895
1021
  queueMicrotask(() => {
@@ -897,7 +1023,12 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
897
1023
  stopEarlyAddons?.();
898
1024
  });
899
1025
  }
900
- const sketchModule = sketchOnPage && hold === undefined ? awaitLater(loadSketch(sketchUrl)) : undefined;
1026
+ const sketchModule = sketchOnPage && moduleFirst ? awaitLater(loadSketch(sketchUrl)) : undefined;
1027
+ // The files that a live sketch lists start downloading once its module and the runner's code
1028
+ // have loaded, unless the runner's setup begins them first.
1029
+ const listed = {};
1030
+ if (sketchModule && runnerModule)
1031
+ Promise.all([sketchModule, runnerModule]).then(([sketch, runner]) => runner.startListedFiles(listed, sketch, pageUrl ?? sketchUrl), () => { });
901
1032
  const powerPreference = options.powerPreference ?? DEFAULT_POWER_PREFERENCE;
902
1033
  const messageHandlers = new Set();
903
1034
  if (options.onSketchMessage)
@@ -929,7 +1060,22 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
929
1060
  handler(name, data);
930
1061
  };
931
1062
  const failureHandlers = new Set();
1063
+ /** Ends hold mode's read-back of its frame, while it reads the frame back. */
1064
+ let endHold;
932
1065
  const stopHandlers = new Set();
1066
+ /**
1067
+ * Resolves `engine.presetChecked`: once the check ends, at once where none runs, and once the
1068
+ * engine draws no new frames, which ends a check that measures them.
1069
+ */
1070
+ let endCheck = () => { };
1071
+ const presetChecked = new Promise((resolve) => {
1072
+ endCheck = resolve;
1073
+ });
1074
+ const firstFrame = new FirstFrame();
1075
+ /** The metrics' header, where the thread that draws writes when the GPU finished the first frame. */
1076
+ let header;
1077
+ /** True once the GPU has finished the first frame. */
1078
+ const firstFrameDone = () => (header?.firstFrameDoneTime ?? 0) > 0;
933
1079
  /** True once the engine draws no new frames, which each stop handler hears once. */
934
1080
  let drawingEnded = false;
935
1081
  /** Runs a stop handler. One that throws is the page's error, which the console shows. */
@@ -941,10 +1087,16 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
941
1087
  console.error(error);
942
1088
  }
943
1089
  };
944
- const endDrawing = () => {
1090
+ /**
1091
+ * Ends the engine's frames: with the failure that ended them, which `engine.firstFrame` then
1092
+ * rejects with when the GPU has not finished the first frame, or with none for a stop.
1093
+ */
1094
+ const endDrawing = (failure) => {
945
1095
  if (drawingEnded)
946
1096
  return;
947
1097
  drawingEnded = true;
1098
+ endCheck();
1099
+ firstFrame.stopped(firstFrameDone(), failure);
948
1100
  const handlers = [...stopHandlers];
949
1101
  stopHandlers.clear();
950
1102
  // The other handlers and the stop go on past one that throws.
@@ -966,6 +1118,8 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
966
1118
  sketchErrorHandlers.add(options.onSketchError);
967
1119
  /** Where a start that checks its preset keeps the check's result for later starts. */
968
1120
  let checkStore;
1121
+ /** The stored list of the first frame's pipelines, on a start that keeps one. */
1122
+ let pipelineStore;
969
1123
  /**
970
1124
  * Ends the start when the caller cancels it, or when a thread fails before the engine has
971
1125
  * started. A thread that fails then, such as the one that draws, leaves the start waiting for
@@ -975,7 +1129,7 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
975
1129
  let starting = true;
976
1130
  const cancelStart = () => start.abort(signal?.reason);
977
1131
  signal?.addEventListener('abort', cancelStart, { once: true });
978
- const onFailure = (error, endsStart = true) => {
1132
+ const onFailure = (error, endsStart = true, endsHold = true) => {
979
1133
  if (reported.has(error.message))
980
1134
  return;
981
1135
  reported.add(error.message);
@@ -983,12 +1137,18 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
983
1137
  start.abort(error);
984
1138
  return;
985
1139
  }
1140
+ // Hold mode reads its frame back after the start. A failure ends that read-back, which then
1141
+ // reports it, unless the frames never needed the thread that failed.
1142
+ const hold = endsHold ? endHold : undefined;
1143
+ hold?.(error);
986
1144
  // The failure reaches its handlers, or the console, before the stop handlers hear that the
987
1145
  // frames ended, so a page hears why before it hears that.
988
1146
  try {
989
1147
  if (failureHandlers.size === 0) {
990
- earlyFailures.push(error);
991
- console.error(error);
1148
+ if (!hold) {
1149
+ earlyFailures.push(error);
1150
+ console.error(error);
1151
+ }
992
1152
  }
993
1153
  else
994
1154
  for (const handler of failureHandlers)
@@ -996,7 +1156,7 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
996
1156
  }
997
1157
  finally {
998
1158
  if (FAILURES_THAT_END_DRAWING.has(error.code))
999
- endDrawing();
1159
+ endDrawing(error);
1000
1160
  }
1001
1161
  };
1002
1162
  // The GPU path, the mode and the threads, which the start sets once the probe has run. The
@@ -1015,16 +1175,21 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1015
1175
  sketchError: onSketchError,
1016
1176
  failure: onFailure,
1017
1177
  // The page applies the settings that it owns: the pixel ratio cap sizes the canvas. The
1018
- // engine's mode reports the preset and the preset check, which the page stores for later
1019
- // starts.
1178
+ // engine's mode reports the preset and the preset check's result, which the page stores for
1179
+ // later starts. It also stores the check's rounds at each lowering, so a page that closes
1180
+ // before the check ends keeps them.
1020
1181
  quality: (update) => {
1021
1182
  canvasWatch?.setMaxPixelRatio(update.settings.maxPixelRatio);
1022
1183
  mode.preset = update.preset;
1023
- if (!update.check)
1024
- return;
1025
- mode.presetCheck = update.check;
1026
- checkStore?.save(update.check, maxTarget);
1184
+ if (update.check) {
1185
+ if (update.checked)
1186
+ mode.presetCheck = update.check;
1187
+ checkStore?.save(update.check, maxTarget);
1188
+ }
1189
+ if (update.checked)
1190
+ endCheck();
1027
1191
  },
1192
+ pipelineList: (list) => pipelineStore?.save(list),
1028
1193
  stats: (show) => statsSwitch.show(show),
1029
1194
  labelSlot: (id, table, slot, generation) => pageLabels?.setSlot(id, table, slot, generation),
1030
1195
  jobsWanted: (count) => growJobs?.(count),
@@ -1057,6 +1222,7 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1057
1222
  const control = createControlBuffer(threaded, labelCapacity(options.maxLabels), labelCapacity3d(options.maxLabels3d));
1058
1223
  const expectedObjects = expectedObjectCount(options.expectedObjects);
1059
1224
  const metrics = createMetricsBuffer(threaded, jobWorkers);
1225
+ header = new MetricsReader(metrics);
1060
1226
  // The frame figures go on the page as the start makes them, so a test tool can time a start
1061
1227
  // that stalls before it publishes anything, and read the sketch's growth, the first draw's
1062
1228
  // pipelines and the first frame beside the steps it has noted.
@@ -1124,16 +1290,31 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1124
1290
  let drawModule = renderThread === 'main' ? loadDrawModule() : undefined;
1125
1291
  /** The worker that keeps the canvas from an engine before, which draws for this one. */
1126
1292
  const keptWorker = movedTo ? takeParkedWorker(options.canvas, canvasHold) : undefined;
1127
- // With worker threads the page starts the workers now. A sketch worker gets the sketch module
1128
- // into the browser's cache, and still runs the module only after it has started the core.
1293
+ // With worker threads the page starts the workers now. A live sketch's worker imports the sketch
1294
+ // module as soon as its script runs, while the core downloads. In hold mode, a replay and a
1295
+ // recording it imports the module only after it has started the core and the runner, so the page
1296
+ // gets the module into the browser's cache meanwhile. A live start leaves that download to the
1297
+ // worker's own import, which a second request of the same file would only delay, or double where
1298
+ // the browser does not join two requests of one file.
1129
1299
  const threads = threaded
1130
1300
  ? startWorkers(!sketchOnPage, renderThread === 'render-worker', events, keptWorker && movedTo && { worker: keptWorker, role: movedTo })
1131
1301
  : undefined;
1132
1302
  if (threads?.sketch) {
1133
- prefetch(sketchUrl);
1134
1303
  // In low-latency mode the sketch worker draws, so it loads the renderer now too.
1135
1304
  if (renderThread === 'sketch-worker')
1136
1305
  threads.sketch.send({ type: 'load-renderer' });
1306
+ if (moduleFirst)
1307
+ threads.sketch.send({ type: 'load-sketch', url: sketchUrl, pageUrl: pageUrl ?? sketchUrl });
1308
+ else
1309
+ prefetch(sketchUrl);
1310
+ }
1311
+ // The job workers start later, as the sketch's tasks and frames ask for them, and a setup that
1312
+ // loads a model asks at once. Their script downloads now, so the first of them start from the
1313
+ // browser's cache.
1314
+ if (jobWorkers > 0) {
1315
+ const jobScript = workerScriptOf(() => newJobWorker(0));
1316
+ if (jobScript)
1317
+ prefetch(jobScript.href);
1137
1318
  }
1138
1319
  // What the start sets up, which a stop takes down again, from any point of the start.
1139
1320
  let coreMemory;
@@ -1162,6 +1343,8 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1162
1343
  /** The worker that holds the canvas, or will once the start moves it there. */
1163
1344
  let canvasWorker = movedTo === 'render' ? threads?.render : movedTo ? threads?.sketch : undefined;
1164
1345
  let localDrawing;
1346
+ /** What the page started for its renderer right after the probe, until the renderer takes it. */
1347
+ let pageEarly;
1165
1348
  let localRunner;
1166
1349
  /** Sends the sketch a message, here where the page runs it, or through its worker. */
1167
1350
  const sendToSketch = (name, data, transfer = []) => {
@@ -1256,6 +1439,24 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1256
1439
  stopJobs();
1257
1440
  waitForJobWorkersToLeave(slots);
1258
1441
  };
1442
+ /**
1443
+ * Gives the GPU back while the browser keeps the page in its back/forward cache, and takes a new
1444
+ * device when the page shows again, as after a GPU loss. Without it, the cached page holds every
1445
+ * texture and buffer, and a phone or tablet can lack the memory for the next page: a repeat
1446
+ * visit of the same page meets the cached one's GPU memory (D-390). The engine listens only where
1447
+ * it keeps texture copies, which bring every map back on the new device.
1448
+ */
1449
+ const pageCached = (event) => {
1450
+ if (!event.persisted)
1451
+ return;
1452
+ const cached = event.type === 'pagehide';
1453
+ if (!localDrawing)
1454
+ rendererHost?.send({ type: 'page-cache', cached });
1455
+ else if (cached)
1456
+ localDrawing.enterPageCache();
1457
+ else
1458
+ void localDrawing.leavePageCache();
1459
+ };
1259
1460
  /** On the dev server, hands each hot update of WGSL to the thread that runs the sketch. */
1260
1461
  const updateShaders = (event) => {
1261
1462
  const updates = event.detail;
@@ -1283,6 +1484,8 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1283
1484
  stopJobs();
1284
1485
  removeMeasurementRelease();
1285
1486
  globalThis.removeEventListener?.('pagehide', stopJobsAsPageLeaves);
1487
+ globalThis.removeEventListener?.('pagehide', pageCached);
1488
+ globalThis.removeEventListener?.('pageshow', pageCached);
1286
1489
  globalThis.removeEventListener?.(WGSL_UPDATE_EVENT, updateShaders);
1287
1490
  statsSwitch.show(false);
1288
1491
  for (const slot of [
@@ -1294,6 +1497,8 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1294
1497
  ])
1295
1498
  notifySlot(slots, slot, threads?.sketch?.handle);
1296
1499
  await localDrawing?.stop();
1500
+ // A start that stops before the page's renderer took its early device destroys it.
1501
+ void pageEarly?.then((early) => early?.release());
1297
1502
  localRunner?.dispose();
1298
1503
  videos?.dispose();
1299
1504
  input?.listen(false);
@@ -1408,7 +1613,9 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1408
1613
  // The engine checks a preset that it chose itself, when a lighter one exists. A preset that the
1409
1614
  // page, a switch or hold mode fixes stays as it is. A start after a crash measures again, and
1410
1615
  // so does one that ?check=fresh asks to. Otherwise the result of an earlier check of the sketch
1411
- // on this device and browser gives the preset at once, while it applies.
1616
+ // on this device and browser gives the preset at once, while it applies. The rounds of an
1617
+ // earlier check that never ended give the preset that they lowered to, and this start's check
1618
+ // goes on from them.
1412
1619
  const checks = optionPreset === 'auto' &&
1413
1620
  switches.preset === undefined &&
1414
1621
  hold === undefined &&
@@ -1418,14 +1625,26 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1418
1625
  const conditions = checkConditions(report, tier, chosen, switches.fps, maxTarget);
1419
1626
  checkStore = new CheckStore(sketchUrl, conditions, width * height);
1420
1627
  }
1421
- const storedCheck = switches.freshCheck ? undefined : checkStore?.read();
1422
- const preset = storedCheck?.rounds.at(-1)?.preset ?? chosen;
1628
+ const stored = switches.freshCheck ? undefined : checkStore?.read();
1629
+ const storedCheck = stored && checkEnded(stored) ? stored : undefined;
1630
+ const preset = stored ? checkedPreset(stored) : chosen;
1423
1631
  // Occlusion culling on the GPU needs WebGPU's compute passes. Phones and tablets run it only
1424
1632
  // when the page asks.
1425
1633
  const gpuOcclusion = tier === 'webgl2'
1426
1634
  ? false
1427
1635
  : gpuOcclusionChoice(deviceKind(presetRequest.hints), pageSettings.gpuOcclusion);
1428
- const tierSettings = { ...pageSettings, gpuOcclusion };
1636
+ // A start that crashed the tab twice begins in the lowest tier, as a page's switch does: the
1637
+ // engine has already lowered the preset, and the tier is the last step down (D-382).
1638
+ // The `?tier=off` switch keeps the governor out of the tier, and a start keeps its values.
1639
+ const lowestAllowed = switches.lowestTier !== 'off';
1640
+ const startLowest = lowestAllowed &&
1641
+ (switches.lowestTier === 'lowest' ||
1642
+ (switches.preset === undefined && crashLowest(history.crashed)));
1643
+ const tierSettings = {
1644
+ ...pageSettings,
1645
+ gpuOcclusion,
1646
+ ...(startLowest ? lowestTierSettings(tier) : {}),
1647
+ };
1429
1648
  const textureCapMiB = textureMemoryCap(deviceKind(presetRequest.hints));
1430
1649
  const quality = {
1431
1650
  preset,
@@ -1434,7 +1653,12 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1434
1653
  textureCapMiB,
1435
1654
  keepCopies: keepTextureCopies,
1436
1655
  highest: withinTier('ultra', tier),
1437
- check: checks && !storedCheck,
1656
+ // A replay steps through its recording, which leaves no frames of play to measure.
1657
+ check: checks && !storedCheck && replay === undefined ? checkTiming : undefined,
1658
+ resume: storedCheck ? undefined : stored,
1659
+ lowest: startLowest,
1660
+ lowestAllowed,
1661
+ tier,
1438
1662
  };
1439
1663
  mode = {
1440
1664
  build,
@@ -1450,6 +1674,8 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1450
1674
  renderFallback,
1451
1675
  keepTextureCopies,
1452
1676
  };
1677
+ if (quality.check === undefined)
1678
+ endCheck();
1453
1679
  /**
1454
1680
  * The preset that the first frame draws at: the one the engine starts with, because its own
1455
1681
  * preset check draws that frame before it can step down. The page can end on a lighter preset,
@@ -1521,15 +1747,32 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1521
1747
  expectedObjects,
1522
1748
  gpuOcclusion: quality.settings.gpuOcclusion,
1523
1749
  });
1524
- // The GPU path and the device's fixed bits choose the renderers and the shader file that the
1525
- // thread that draws loads first, so it starts their downloads now, while the core downloads.
1526
- const shaderPreload = { type: 'load-shaders', tier, bits: device.shaderBits };
1750
+ // A live start keeps the list of its first frame's pipelines, and builds the list that the last
1751
+ // start at the same preset kept as soon as the thread that draws can. A hold, a replay and a
1752
+ // recording of permutation words draw what they hold, so they neither read nor keep one.
1753
+ if (hold === undefined && replay === undefined && !rendererSetup.recordPermutations) {
1754
+ pipelineStore = new PipelineStore(sketchUrl, pipelineConditions(tier, device.shaderBits, preset, tier === 'webgl2' ? undefined : (report.webgpu.preferredCanvasFormat ?? undefined)));
1755
+ rendererSetup.keepBuilds = true;
1756
+ if (!switches.freshBuilds)
1757
+ rendererSetup.earlyBuilds = pipelineStore.read();
1758
+ }
1759
+ // The GPU path and the device choose the renderers and the shader files that the thread that
1760
+ // draws loads first, and the GPU device that it asks for, so it starts them now, while the core
1761
+ // downloads.
1762
+ const drawingPreload = {
1763
+ tier,
1764
+ device,
1765
+ forceCompat,
1766
+ powerPreference,
1767
+ preload: options.preload,
1768
+ };
1769
+ const shaderPreload = { type: 'load-shaders', ...drawingPreload };
1527
1770
  if (renderThread === 'render-worker')
1528
1771
  threads?.render?.send(shaderPreload);
1529
1772
  else if (renderThread === 'sketch-worker')
1530
1773
  threads?.sketch?.send(shaderPreload);
1531
1774
  else if (drawModule)
1532
- preloadDeviceFiles(drawModule, tier, device.shaderBits);
1775
+ pageEarly = preloadDrawing(drawModule, drawingPreload);
1533
1776
  const core = await abortable(coreLoad, signal);
1534
1777
  coreMemory = core.memory;
1535
1778
  memoryKey = core.memoryKey;
@@ -1608,11 +1851,14 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1608
1851
  */
1609
1852
  const drawOnPage = async (memory, images, sketch) => {
1610
1853
  draw = await (drawModule ?? loadDrawModule());
1854
+ const early = await pageEarly;
1855
+ pageEarly = undefined;
1611
1856
  // The page's context stays with the canvas: an engine after this one draws on the page too.
1612
1857
  canvasHold.pageContext = true;
1613
1858
  return draw.startDrawing({
1614
1859
  canvas: options.canvas,
1615
1860
  ...rendererSetup,
1861
+ early,
1616
1862
  metrics,
1617
1863
  device,
1618
1864
  scene: memory && { memory, control },
@@ -1620,13 +1866,18 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1620
1866
  sketch,
1621
1867
  ...images,
1622
1868
  presented: () => labels.update(),
1869
+ listBuilds: rendererSetup.keepBuilds ? (list) => pipelineStore?.save(list) : undefined,
1623
1870
  fail: pageLoss,
1624
1871
  fault: (error) => onFailure(failureError('the drawing on the page', messageOf(error))),
1625
- gpuError: (outOfMemory, message) => onFailure(gpuFailure('the page', outOfMemory, message), false),
1872
+ gpuError: (kind, message) => onFailure(gpuFailure('the page', kind, message), false),
1626
1873
  });
1627
1874
  };
1628
1875
  if (threads && jobWorkers > 0)
1629
1876
  globalThis.addEventListener?.('pagehide', stopJobsAsPageLeaves);
1877
+ if (keepTextureCopies && hold === undefined) {
1878
+ globalThis.addEventListener?.('pagehide', pageCached);
1879
+ globalThis.addEventListener?.('pageshow', pageCached);
1880
+ }
1630
1881
  if (DEV)
1631
1882
  globalThis.addEventListener?.(WGSL_UPDATE_EVENT, updateShaders);
1632
1883
  /**
@@ -1642,14 +1893,34 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1642
1893
  const taskPorts = Array.from({ length: jobWorkers }, () => channel());
1643
1894
  /** The job workers that started, by index, which the on-demand loader sends its tasks to. */
1644
1895
  const running = [];
1645
- /** Notes a job worker that started, by its index. */
1646
- const noteStarted = (index) => running.push(index);
1896
+ /**
1897
+ * Tells the thread that runs the sketch which job workers run, in a new list each time. A
1898
+ * sketch on this page reads the news itself, since no sketch worker carries it.
1899
+ */
1900
+ const tell = () => {
1901
+ running.sort((a, b) => a - b);
1902
+ threads?.sketch?.send({ type: 'job-workers', running: [...running] });
1903
+ if (jobTaskHost)
1904
+ jobTaskHost.running = [...running];
1905
+ };
1647
1906
  growJobs = (count) => {
1907
+ // The sketch thread hears of each job worker as soon as it is ready, so its first task
1908
+ // runs on the first that is, and only on workers that run. A batch none of whose workers
1909
+ // started still says so once it has settled, so a task that waits for them goes to a
1910
+ // task worker instead. A batch that started no worker at all, because the browser
1911
+ // refused them or the engine is stopping, stays unheard: the thread then uses the
1912
+ // workers it asked for.
1913
+ let heard = false;
1914
+ const started = (index) => {
1915
+ heard = true;
1916
+ running.push(index);
1917
+ tell();
1918
+ };
1648
1919
  const starting = [];
1649
1920
  for (let index = jobs.length; index < Math.min(count, jobWorkers); index++) {
1650
1921
  if (Atomics.load(slots, Slot.Running) === 0)
1651
1922
  break;
1652
- const job = startJobWorker(index, slots, events, noteStarted);
1923
+ const job = startJobWorker(index, slots, events, started);
1653
1924
  if (!job)
1654
1925
  break;
1655
1926
  jobs.push(job);
@@ -1657,18 +1928,11 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1657
1928
  job.send({ type: 'init', ...handoff, index, taskPort: port }, [port]);
1658
1929
  starting.push(job.ready());
1659
1930
  }
1660
- // The sketch thread hears which of a batch of job workers run once the whole batch has
1661
- // settled, so it never takes a worker for running before the batch is known. A batch
1662
- // that started no worker, because the browser refused them or the engine is stopping,
1663
- // stays unheard: the thread then uses the workers it asked for. A sketch on this page
1664
- // reads the news itself, since no sketch worker carries it.
1665
1931
  if (starting.length === 0)
1666
1932
  return;
1667
1933
  void Promise.allSettled(starting).then(() => {
1668
- running.sort((a, b) => a - b);
1669
- threads?.sketch?.send({ type: 'job-workers', running: [...running] });
1670
- if (jobTaskHost)
1671
- jobTaskHost.running = [...running];
1934
+ if (!heard)
1935
+ tell();
1672
1936
  });
1673
1937
  };
1674
1938
  return taskPorts.map((tasks) => tasks.port2);
@@ -1760,19 +2024,15 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1760
2024
  wantJobs,
1761
2025
  sendLabelSlot: events.labelSlot,
1762
2026
  reportSketchError: (message) => events.sketchError(new Error(message)),
2027
+ listed: sketchModule ? listed : undefined,
1763
2028
  // What the sketch's module loaded before the runner existed, then each later load.
1764
2029
  ...(DEV && {
1765
- hearAddons: (heard) => {
1766
- stopEarlyAddons?.();
1767
- for (const name of earlyAddons ?? [])
1768
- heard(name);
1769
- return onAddonChecked(heard);
1770
- },
2030
+ hearAddons: (heard) => earlyAddons?.hand(heard) ?? onAddonChecked(heard),
1771
2031
  }),
1772
2032
  }, hold, holdScript, replay, record, switches.view);
1773
- // In hold mode the sketch module loads only now, after the runner seeded the random
1774
- // numbers. The renderer starts before the setup, so a warm-up in the setup has a renderer
1775
- // to build its pipelines.
2033
+ // In hold mode, a replay and a recording the sketch module loads only now, after the runner
2034
+ // seeded the random numbers. The renderer starts before the setup, so a warm-up in the
2035
+ // setup has a renderer to build its pipelines.
1776
2036
  const sketchLoad = sketchModule ?? awaitLater(loadSketch(sketchUrl));
1777
2037
  if (!render)
1778
2038
  localDrawing = await abortable(drawOnPage(memory, { imageTable }, localRunner), start.signal);
@@ -1844,24 +2104,23 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1844
2104
  const engineStartMs = performance.now() - startedAt;
1845
2105
  onProgress('sketch');
1846
2106
  // The thread that draws writes the time the GPU finished the first frame; the page checks for
1847
- // it once per animation frame until it appears.
1848
- const header = new MetricsReader(metrics);
1849
- const firstFrame = new Promise((resolve) => {
1850
- const check = () => {
1851
- if (Atomics.load(slots, Slot.Running) === 0)
1852
- return;
1853
- if (header.firstFrameDoneTime > 0) {
1854
- onProgress('first-frame');
1855
- resolve();
1856
- return;
1857
- }
1858
- requestAnimationFrame(check);
1859
- };
2107
+ // it once per animation frame until it appears, or until the engine stops drawing.
2108
+ const check = () => {
2109
+ if (Atomics.load(slots, Slot.Running) === 0)
2110
+ return;
2111
+ if (firstFrameDone()) {
2112
+ onProgress('first-frame');
2113
+ firstFrame.drawn();
2114
+ return;
2115
+ }
1860
2116
  requestAnimationFrame(check);
1861
- });
1862
- marker?.endAfter(firstFrame);
2117
+ };
2118
+ requestAnimationFrame(check);
2119
+ // The note covers the preset check as well as the first seconds of play, so a start whose
2120
+ // check ends in a crash counts as one.
2121
+ marker?.endAfter(Promise.all([firstFrame.promise, presetChecked]).then(() => undefined));
1863
2122
  if (DEV && switches.twoStep)
1864
- void firstFrame.then(() => logTwoStep(slots, false));
2123
+ void firstFrame.promise.then(() => logTwoStep(slots, false), () => { });
1865
2124
  /** Hold mode's frame, read back once. */
1866
2125
  let held;
1867
2126
  /** The error of a thread that draws when it could not capture a frame. */
@@ -1895,13 +2154,40 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1895
2154
  throw captureFailure(reply);
1896
2155
  };
1897
2156
  const stopped = () => Atomics.load(slots, Slot.Running) === 0;
2157
+ /**
2158
+ * The development build's inspection bridge: a capture reads the current frame here, and
2159
+ * every other call runs in the thread that runs the sketch. A release build defines none,
2160
+ * so code that uses it checks for it first.
2161
+ */
2162
+ const inspectCall = DEV
2163
+ ? async (call, args) => {
2164
+ if (call === 'capture') {
2165
+ const blob = await captureImage();
2166
+ const url = await new Promise((resolve, reject) => {
2167
+ const reader = new FileReader();
2168
+ reader.onload = () => resolve(reader.result);
2169
+ reader.onerror = () => reject(reader.error);
2170
+ reader.readAsDataURL(blob);
2171
+ });
2172
+ return { png: url.slice(url.indexOf(',') + 1), bytes: blob.size };
2173
+ }
2174
+ if (localRunner?.inspect !== undefined)
2175
+ return await localRunner.inspect(call, args);
2176
+ const worker = threads?.sketch;
2177
+ if (worker === undefined)
2178
+ throw new Error('the sketch worker is not running, so the inspector has nothing to read');
2179
+ return await worker.inspect(call, args);
2180
+ }
2181
+ : undefined;
1898
2182
  const engine = {
1899
2183
  capabilities,
1900
2184
  report,
1901
2185
  mode,
1902
- firstFrame,
2186
+ firstFrame: firstFrame.promise,
2187
+ presetChecked,
1903
2188
  labels,
1904
2189
  postToSketch: sendToSketch,
2190
+ ...(inspectCall === undefined ? {} : { inspect: inspectCall }),
1905
2191
  registerVideo: (video, videoOptions) => videos.register(video, videoOptions),
1906
2192
  onSketchMessage(handler) {
1907
2193
  messageHandlers.add(handler);
@@ -1956,7 +2242,7 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1956
2242
  // adds an object then builds its pipelines while the figures load.
1957
2243
  const reader = new MetricsReader(metrics);
1958
2244
  reader.begin();
1959
- const { HeapSampler, secondRates, slowFrames, summarizeFrames, wasmDownloadBytes } = await loadFrameStats();
2245
+ const { HeapSampler, drawingStartFigures, secondRates, slowFrames, summarizeFrames, wasmDownloadBytes, } = await loadFrameStats();
1960
2246
  const mainThread = new MainThreadWatch();
1961
2247
  const started = performance.now();
1962
2248
  const heap = new HeapSampler();
@@ -1982,6 +2268,7 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
1982
2268
  firstDrawMs: reader.firstDrawMs,
1983
2269
  firstFramePipelines: reader.firstFramePipelines,
1984
2270
  firstFramePreset,
2271
+ drawingStart: drawingStartFigures(reader),
1985
2272
  },
1986
2273
  gpuLosses: Atomics.load(slots, Slot.GpuEpoch),
1987
2274
  downloadBytes: { wasm: wasmDownloadBytes() },
@@ -2052,6 +2339,36 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
2052
2339
  if (hold === undefined && replay === undefined) {
2053
2340
  if (switches.bench)
2054
2341
  globalThis[BENCH_GLOBAL] = engine;
2342
+ if (DEV && inspectCall !== undefined) {
2343
+ // The page publishes the bridge so the MCP server and a developer's console can call
2344
+ // it. The switch opens the panel, whose code loads on first use. A stopped engine
2345
+ // takes the bridge away, so the page keeps none of its memory.
2346
+ globalThis[INSPECTOR_GLOBAL] = {
2347
+ inspect: inspectCall,
2348
+ engine,
2349
+ };
2350
+ engine.onStop(() => {
2351
+ const current = globalThis[INSPECTOR_GLOBAL];
2352
+ if (current?.engine === engine)
2353
+ delete globalThis[INSPECTOR_GLOBAL];
2354
+ });
2355
+ if (switches.inspect)
2356
+ void (async () => {
2357
+ // The panel's file loads from its source address. A development build runs the source,
2358
+ // whose file is TypeScript; the published package holds the compiled JavaScript. A
2359
+ // production build removes this branch, and emits no file for it.
2360
+ const extension = new URL(import.meta.url).pathname.endsWith('.ts') ? 'ts' : 'js';
2361
+ const source = `../debug/inspector.${extension}`;
2362
+ const url = new URL(source, import.meta.url).href;
2363
+ const module = (await import(__rewriteRelativeImportExtension(
2364
+ /* @vite-ignore */ url)));
2365
+ const inspector = module.openInspector({
2366
+ inspect: inspectCall,
2367
+ canvas: options.canvas,
2368
+ });
2369
+ engine.onStop(() => inspector.remove());
2370
+ })().catch((error) => console.warn('null3D could not show the inspector:', error));
2371
+ }
2055
2372
  // The switch's start state goes on top of the option's corner.
2056
2373
  if (switches.stats !== false) {
2057
2374
  if (options.stats)
@@ -2062,7 +2379,12 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
2062
2379
  return engine;
2063
2380
  }
2064
2381
  try {
2065
- held = await abortable(holdFrame(capture, failureHandlers), signal);
2382
+ held = await abortable(holdFrame(capture, (end) => {
2383
+ endHold = end;
2384
+ return () => {
2385
+ endHold = undefined;
2386
+ };
2387
+ }), signal);
2066
2388
  // The held frame built every pipeline that the scene draws with, so its words are
2067
2389
  // complete here, before the page publishes the frame the tool waits on.
2068
2390
  stopRecording();
@@ -2113,15 +2435,16 @@ async function startEngine(options, switches, modes, { threaded, sketchThread },
2113
2435
  }
2114
2436
  /**
2115
2437
  * Draws the held frame and reads it back through `capture`. The first failure that the engine
2116
- * reports meanwhile, such as a lost GPU, ends the hold instead. A failure without a code becomes
2438
+ * reports meanwhile to the function that `listen` registers, such as a lost GPU, ends the hold
2439
+ * instead. `listen` returns the function that ends the listening. A failure without a code becomes
2117
2440
  * E1408.
2118
2441
  */
2119
- async function holdFrame(capture, failureHandlers) {
2442
+ async function holdFrame(capture, listen) {
2120
2443
  let fail = () => { };
2121
2444
  const failed = new Promise((_, reject) => {
2122
2445
  fail = reject;
2123
2446
  });
2124
- failureHandlers.add(fail);
2447
+ const stopListening = listen(fail);
2125
2448
  try {
2126
2449
  return await Promise.race([capture(), failed]);
2127
2450
  }
@@ -2131,6 +2454,6 @@ async function holdFrame(capture, failureHandlers) {
2131
2454
  throw new EngineError('E1408', `hold mode stopped before it read the held frame back: ${messageOf(error)}.`);
2132
2455
  }
2133
2456
  finally {
2134
- failureHandlers.delete(fail);
2457
+ stopListening();
2135
2458
  }
2136
2459
  }