@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
@@ -8,5 +8,17 @@ export declare function tasksPending(): number;
8
8
  export declare function planStarted(label: string): number;
9
9
  /** Stops counting the level plan with number `plan`, once its levels are in or it ended. */
10
10
  export declare function planEnded(plan: number): void;
11
+ /**
12
+ * Resolves when the level plan with number `plan` may hand over its levels: at once, unless hold
13
+ * mode holds the plans back. Then it resolves once hold mode has let the plans go and every plan
14
+ * that started before this one has ended.
15
+ */
16
+ export declare function planTurn(plan: number): Promise<void>;
17
+ /** Holds every plan's levels back from now on, until `releasePlans`, as hold mode asks. */
18
+ export declare function holdPlans(): void;
19
+ /** Lets the plans that hold mode held back hand over their levels, one at a time in their order. */
20
+ export declare function releasePlans(): void;
21
+ /** Ends hold mode's hold on the plans: each plan hands over its levels as it answers again. */
22
+ export declare function endPlanHold(): void;
11
23
  /** The labels of the level plans that wait. */
12
24
  export declare function plansPending(): string[];
@@ -4,11 +4,22 @@
4
4
  // plans of meshes made in code count as tasks too, each with a label that names its mesh, so a
5
5
  // held frame can wait for them all the way and say which meshes still plan. The count is the
6
6
  // thread's, so the tasks that the sketch's own copy of the engine runs count too.
7
+ //
8
+ // Hold mode also holds the plans' levels back until it lets them go, and then lets one plan hand
9
+ // over its levels at a time, in the order the plans started. A plan answers whenever its job
10
+ // worker finishes, and the meshes of its levels take their places in engine memory as it hands
11
+ // them over, so plans that handed over as they answered would leave the scene's meshes in another
12
+ // order on each run.
7
13
  /** The key of the thread's count on its global object. */
8
14
  const PENDING = Symbol.for('null3d.pendingTasks');
9
15
  const thread = globalThis;
10
16
  /** The thread's count. The first copy of this module in the thread makes it. */
11
- const pending = thread[PENDING] ?? { tasks: 0, plans: new Map(), lastPlan: 0 };
17
+ const pending = thread[PENDING] ?? {
18
+ tasks: 0,
19
+ plans: new Map(),
20
+ lastPlan: 0,
21
+ turns: new Map(),
22
+ };
12
23
  thread[PENDING] = pending;
13
24
  /** Counts a task that waits for its answer. */
14
25
  export function taskStarted() {
@@ -34,6 +45,55 @@ export function planStarted(label) {
34
45
  export function planEnded(plan) {
35
46
  if (pending.plans.delete(plan))
36
47
  taskEnded();
48
+ pending.turns.delete(plan);
49
+ nextTurn();
50
+ }
51
+ /**
52
+ * Resolves when the level plan with number `plan` may hand over its levels: at once, unless hold
53
+ * mode holds the plans back. Then it resolves once hold mode has let the plans go and every plan
54
+ * that started before this one has ended.
55
+ */
56
+ export function planTurn(plan) {
57
+ if (pending.released === undefined)
58
+ return Promise.resolve();
59
+ return new Promise((resolve) => {
60
+ pending.turns.set(plan, resolve);
61
+ nextTurn();
62
+ });
63
+ }
64
+ /** Holds every plan's levels back from now on, until `releasePlans`, as hold mode asks. */
65
+ export function holdPlans() {
66
+ pending.released = false;
67
+ }
68
+ /** Lets the plans that hold mode held back hand over their levels, one at a time in their order. */
69
+ export function releasePlans() {
70
+ if (pending.released === false)
71
+ pending.released = true;
72
+ nextTurn();
73
+ }
74
+ /** Ends hold mode's hold on the plans: each plan hands over its levels as it answers again. */
75
+ export function endPlanHold() {
76
+ pending.released = undefined;
77
+ const waiting = [...pending.turns.values()];
78
+ pending.turns.clear();
79
+ for (const turn of waiting)
80
+ turn();
81
+ }
82
+ /** Gives the turn to the oldest plan that is still pending, once it waits for it. */
83
+ function nextTurn() {
84
+ if (pending.released !== true)
85
+ return;
86
+ let oldest;
87
+ for (const plan of pending.plans.keys())
88
+ if (oldest === undefined || plan < oldest)
89
+ oldest = plan;
90
+ if (oldest === undefined)
91
+ return;
92
+ const turn = pending.turns.get(oldest);
93
+ if (!turn)
94
+ return;
95
+ pending.turns.delete(oldest);
96
+ turn();
37
97
  }
38
98
  /** The labels of the level plans that wait. */
39
99
  export function plansPending() {
@@ -6,12 +6,13 @@
6
6
  // It compiles each WebAssembly module once per page with WebAssembly.compileStreaming, and posts
7
7
  // the compiled module to each worker that runs it, which only instantiates it. Tasks run in the
8
8
  // engine's job workers: a job worker leaves the job loop between frame jobs to run its tasks, and
9
- // with two or more job workers the first never takes tasks, so one always serves frames. The page
10
- // says which job workers run. A worker whose script or its core did not load is left out of the
11
- // tasks, because it would never answer, and where no job worker is left to take them the loader
12
- // starts one task worker with its first task. The glTF worker takes compiled modules from the
13
- // loader too (scene/gltf.ts). When the engine on this thread stops, the loader stops its task
14
- // worker and fails the tasks that wait, and the next engine's tasks start afresh.
9
+ // with two or more job workers the first takes no new task, so one always serves frames. The page
10
+ // says which job workers run, each as soon as it is ready, and the first task runs on the first
11
+ // that is. A worker whose script or its core did not load is left out of the tasks, because it
12
+ // would never answer, and where no job worker is left to take them the loader starts one task
13
+ // worker with its first task. The glTF worker takes compiled modules from the loader too
14
+ // (scene/gltf.ts). When the engine on this thread stops, the loader stops its task worker and fails
15
+ // the tasks that wait, and the next engine's tasks start afresh.
15
16
  //
16
17
  // A thread can hold two copies of this module: in a production build, the sketch worker runs the
17
18
  // engine's worker code, and the sketch's bundle, the add-ons' tasks among it, imports the engine
@@ -29,8 +30,8 @@ import { compileWasm } from './wasm.js';
29
30
  import { bootstrapFailure, spawnWorker, watchWorkerError } from './worker-start.js';
30
31
  /**
31
32
  * How long the first task waits for the page's word on which job workers run, in ms. The word comes
32
- * once the workers that the thread asked for have started, so it follows their downloads. A page
33
- * that never says gives the workers the thread asked for, as before the page could say at all.
33
+ * as soon as the first worker that the thread asked for has started, so it follows its download. A
34
+ * page that never says gives the workers the thread asked for, as before the page could say at all.
34
35
  */
35
36
  const ANNOUNCE_WAIT_MS = 10_000;
36
37
  /** How often it looks for the page's word while it waits, in ms. */
@@ -110,10 +111,23 @@ class Runners {
110
111
  runners;
111
112
  /** The job workers' ports that `runners` were made from. */
112
113
  host;
114
+ /** The page's word on which job workers run that `runners` were made from. */
115
+ heard;
116
+ /**
117
+ * The runner of each job worker that has taken tasks, by its index, which keeps the worker's
118
+ * modules and its count of tasks while the workers that take tasks change.
119
+ */
120
+ jobs = [];
113
121
  /** The task worker, once a task has started it on a thread without job workers. */
114
122
  worker;
115
123
  /** True once the engine on this thread has stopped. */
116
124
  ended = false;
125
+ /**
126
+ * The handler of the workers' answers. It is made once and bound to the loader, so every port
127
+ * shares it, and the browser's heap profiler names it by its method, `answer`, in every build:
128
+ * a production build renames the variable that an inline handler would be named after.
129
+ */
130
+ answers = this.answer.bind(this);
117
131
  constructor(stopped) {
118
132
  this.stopped = stopped;
119
133
  }
@@ -129,6 +143,8 @@ class Runners {
129
143
  // must fall however that call ends.
130
144
  taskStarted();
131
145
  try {
146
+ // The first job workers start while the task's WebAssembly files download and compile.
147
+ const starting = this.starting();
132
148
  const aloneModule = alone === undefined
133
149
  ? undefined
134
150
  : (compiledModule(alone) ?? (await compileOnce(alone, error)));
@@ -139,7 +155,6 @@ class Runners {
139
155
  : NO_MODULES;
140
156
  if (this.ended)
141
157
  throw new TaskFailure('stopped', 'the engine stopped');
142
- const starting = this.starting();
143
158
  if (starting)
144
159
  await starting;
145
160
  if (this.ended)
@@ -217,6 +232,8 @@ class Runners {
217
232
  if (host !== this.host) {
218
233
  this.host = host;
219
234
  this.runners = undefined;
235
+ this.heard = undefined;
236
+ this.jobs.length = 0;
220
237
  }
221
238
  if (this.runners || !host)
222
239
  return undefined;
@@ -232,6 +249,11 @@ class Runners {
232
249
  await new Promise((resolve) => setTimeout(resolve, ANNOUNCE_POLL_MS));
233
250
  }
234
251
  leastBusy(error) {
252
+ const host = this.host;
253
+ // The page's word is a new list each time, so a task in every frame compares, and allocates
254
+ // nothing, until the job workers that run change.
255
+ if (host && this.runners && host.running !== this.heard)
256
+ this.retake(host);
235
257
  this.runners ??= this.start(error);
236
258
  const runners = this.runners;
237
259
  let best = runners[0];
@@ -247,33 +269,53 @@ class Runners {
247
269
  return best;
248
270
  }
249
271
  /**
250
- * Asks for twice the job workers that take tasks, and adds a runner for each new one. Returns
251
- * the first new runner, or undefined when the engine has no more job workers to start.
272
+ * Asks for twice the job workers that take tasks, and takes the new ones that run. Returns the
273
+ * first new runner, or undefined when no more job workers run yet.
252
274
  */
253
275
  addJobRunners(host) {
254
276
  const runners = this.runners;
255
277
  const takers = taskTakers(host.running, host.want(2 * (runners.length + 1)));
256
- const added = this.jobRunners(host, takers, runners.length);
257
- runners.push(...added);
258
- return added[0];
278
+ const next = this.jobRunners(host, takers);
279
+ const added = next.find((runner) => !runners.includes(runner));
280
+ if (added)
281
+ this.runners = next;
282
+ return added;
259
283
  }
260
284
  /**
261
- * Runners for the job workers that take tasks, from position `from` in `takers` on. A job worker
262
- * that the page says did not start is left out of `takers`, so it takes no task.
285
+ * Takes the job workers that the page's newest word says run, once tasks go to some already: a
286
+ * worker that has just started takes tasks from the next one on, and the first of two or more
287
+ * takes no new task. A word that leaves no job worker keeps the runners there are, such as the
288
+ * task worker. A task already sent to a worker answers there, whichever workers take the next.
263
289
  */
264
- jobRunners(host, takers, from) {
265
- return takers.slice(from).map((index) => {
266
- const port = host.ports[index];
267
- port.onmessage = (event) => this.answer(event.data);
268
- return {
269
- modules: new Set(),
270
- running: 0,
271
- send(request, transfer) {
272
- // The call comes first, so the count covers the request by the time it arrives.
273
- host.call(index);
274
- port.postMessage(request, transfer);
275
- },
276
- };
290
+ retake(host) {
291
+ this.heard = host.running;
292
+ // Asking for none returns how many the thread has asked for.
293
+ const runners = this.jobRunners(host, taskTakers(host.running, host.want(0)));
294
+ if (runners.length > 0)
295
+ this.runners = runners;
296
+ }
297
+ /**
298
+ * The runners of the job workers in `takers`. A job worker that the page says did not start is
299
+ * left out of `takers`, so it takes no task.
300
+ */
301
+ jobRunners(host, takers) {
302
+ return takers.map((index) => {
303
+ let runner = this.jobs[index];
304
+ if (!runner) {
305
+ const port = host.ports[index];
306
+ port.onmessage = this.answers;
307
+ runner = {
308
+ modules: new Set(),
309
+ running: 0,
310
+ send(request, transfer) {
311
+ // The call comes first, so the count covers the request by the time it arrives.
312
+ host.call(index);
313
+ port.postMessage(request, transfer);
314
+ },
315
+ };
316
+ this.jobs[index] = runner;
317
+ }
318
+ return runner;
277
319
  });
278
320
  }
279
321
  /** The job workers that take tasks; or, without one, a task worker that starts now. */
@@ -281,7 +323,8 @@ class Runners {
281
323
  const host = this.host;
282
324
  // The tasks start on the first job workers, and ask for more as they pile up.
283
325
  if (host) {
284
- const runners = this.jobRunners(host, taskTakers(host.running, host.want(2)), 0);
326
+ this.heard = host.running;
327
+ const runners = this.jobRunners(host, taskTakers(host.running, host.want(2)));
285
328
  // No job worker takes this thread's tasks, because none started: a task worker answers them
286
329
  // instead, as on a thread without job workers. The frames keep the workers they have.
287
330
  if (runners.length > 0)
@@ -292,7 +335,7 @@ class Runners {
292
335
  name: 'null3d-tasks',
293
336
  }), error);
294
337
  this.worker = worker;
295
- worker.onmessage = (event) => this.answer(event.data);
338
+ worker.onmessage = this.answers;
296
339
  watchWorkerError(worker, (message) => {
297
340
  worker.terminate();
298
341
  this.fail(message || 'its script did not load', error);
@@ -305,7 +348,9 @@ class Runners {
305
348
  },
306
349
  ];
307
350
  }
308
- answer(answer) {
351
+ /** Settles the task that a worker's message answers. */
352
+ answer(event) {
353
+ const answer = event.data;
309
354
  const waiting = this.waiting.get(answer.id);
310
355
  if (!waiting)
311
356
  return;
@@ -344,6 +389,8 @@ class Runners {
344
389
  }
345
390
  this.host = undefined;
346
391
  this.runners = undefined;
392
+ this.heard = undefined;
393
+ this.jobs.length = 0;
347
394
  this.end(new TaskFailure('stopped', 'the engine stopped'));
348
395
  }
349
396
  /** Forgets these runners, so a later task starts afresh, and fails every waiting task. */
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @category api/engine
5
5
  */
6
- export declare const VERSION = "0.0.0";
6
+ export declare const VERSION = "0.1.0";
7
7
  /**
8
8
  * The version of the plugin interface that an add-on from another developer builds against. It is
9
9
  * a whole number, and it changes only when a stable add-on hook changes, never with every engine
@@ -31,6 +31,22 @@ export interface PluginInterfaceRange {
31
31
  * stops it. Development builds only.
32
32
  */
33
33
  export declare function onAddonChecked(heard: (name: string) => void): () => void;
34
+ /** The add-ons that a sketch's module loaded before its runner existed, as `hearAddonsEarly` hears them. */
35
+ export interface EarlyAddons {
36
+ /**
37
+ * Gives `heard` each add-on heard so far, ends this hearing, and hears each later add-on for
38
+ * `heard`. Returns a function that stops that.
39
+ */
40
+ hand(heard: (name: string) => void): () => void;
41
+ /** Ends the hearing, for a runner that never asks for it. */
42
+ stop(): void;
43
+ }
44
+ /**
45
+ * Hears each add-on that checks its version in this thread from now on, for a sketch runner that
46
+ * does not exist yet: a thread that loads the sketch's module before its runner starts hands the
47
+ * runner what the module loaded. Development builds only.
48
+ */
49
+ export declare function hearAddonsEarly(): EarlyAddons;
34
50
  /**
35
51
  * Checks that an add-on, built for `version` of the engine, runs against this engine's version,
36
52
  * and throws E1432 when the two differ. An add-on calls it once, as its module loads, with its own
@@ -11,7 +11,7 @@ import { DEV } from './dev.js';
11
11
  *
12
12
  * @category api/engine
13
13
  */
14
- export const VERSION = '0.0.0';
14
+ export const VERSION = '0.1.0';
15
15
  /**
16
16
  * The version of the plugin interface that an add-on from another developer builds against. It is
17
17
  * a whole number, and it changes only when a stable add-on hook changes, never with every engine
@@ -45,6 +45,24 @@ export function onAddonChecked(heard) {
45
45
  hearers.add(heard);
46
46
  return () => hearers.delete(heard);
47
47
  }
48
+ /**
49
+ * Hears each add-on that checks its version in this thread from now on, for a sketch runner that
50
+ * does not exist yet: a thread that loads the sketch's module before its runner starts hands the
51
+ * runner what the module loaded. Development builds only.
52
+ */
53
+ export function hearAddonsEarly() {
54
+ const names = [];
55
+ const stop = onAddonChecked((name) => names.push(name));
56
+ return {
57
+ hand(heard) {
58
+ stop();
59
+ for (const name of names)
60
+ heard(name);
61
+ return onAddonChecked(heard);
62
+ },
63
+ stop,
64
+ };
65
+ }
48
66
  /**
49
67
  * Checks that an add-on, built for `version` of the engine, runs against this engine's version,
50
68
  * and throws E1432 when the two differ. An add-on calls it once, as its module loads, with its own
@@ -10,10 +10,18 @@ export type WasmError = (code: 'E1405' | 'E1406' | 'E1418' | 'E1422' | 'E1423',
10
10
  export declare function shownAddress(url: URL): string;
11
11
  /**
12
12
  * Downloads a WebAssembly file and compiles it as it arrives. `name` says what the file is, for
13
- * errors. `readHead` reads a copy of the download, such as the start of the module, while the
14
- * browser compiles. `onDownload` hears the bytes as they arrive, with the length that the response
15
- * announced, or 0 when it gave none. Fails with E1406 when the file does not download whole or is
16
- * not WebAssembly, and with E1418 when the page's Content-Security-Policy blocks WebAssembly.
13
+ * errors. `started` is a download of the file that the page has already begun. `readHead` reads a
14
+ * copy of the download, such as the start of the module, while the browser compiles.
15
+ * `onDownload` hears the bytes as they arrive, with the length that the response announced, or 0
16
+ * when it gave none, and hears the last of them before the compile's result returns. Fails with
17
+ * E1406 when the file does not download whole or is not WebAssembly, and with E1418 when the
18
+ * page's Content-Security-Policy blocks WebAssembly.
19
+ *
20
+ * The browser compiles the downloaded response itself whenever its type allows. Chrome keeps the
21
+ * code that it compiles from a response that it downloaded, and a later visit that takes the file
22
+ * from the HTTP cache reads that code rather than compiling again. A file that a host sends with
23
+ * another type compiles through a response that the engine makes with the right type: it still
24
+ * compiles as it arrives, but afresh on every visit.
17
25
  */
18
26
  export declare function compileWasm<T>(url: URL, name: string, error: WasmError, readHead?: (stream: ReadableStream<Uint8Array>) => Promise<T>, started?: Promise<Response>, onDownload?: (loaded: number, total: number) => void): Promise<{
19
27
  module: WebAssembly.Module;
@@ -1,8 +1,10 @@
1
1
  // Downloads WebAssembly files and compiles them as they arrive: the engine core, and the modules
2
- // that the on-demand loader (shared/tasks.ts) loads on first use. A failure names the file by its
3
- // role and gives its cause: a download that failed, a file that is not WebAssembly, or a
4
- // Content-Security-Policy that blocks WebAssembly. A file from another origin, such as a CDN, can
5
- // also fail because the policy does not allow its origin, or because it came without CORS.
2
+ // that the on-demand loader (shared/tasks.ts) loads on first use. The browser compiles the response
3
+ // that it downloaded, so Chrome can keep the compiled code and a later visit skips the compile.
4
+ // A failure names the file by its role and gives its cause: a download that failed, a file that is
5
+ // not WebAssembly, or a Content-Security-Policy that blocks WebAssembly. A file from another origin,
6
+ // such as a CDN, can also fail because the policy does not allow its origin, or because it came
7
+ // without CORS.
6
8
  import { isCrossOrigin, violationFor, watchPolicy } from './policy.js';
7
9
  import { memoryImportLimits } from './wasm-limits.js';
8
10
  export { memoryImportLimits } from './wasm-limits.js';
@@ -32,26 +34,44 @@ export function shownAddress(url) {
32
34
  : url.pathname;
33
35
  }
34
36
  const reason = (thrown) => (thrown instanceof Error ? thrown.message : String(thrown));
37
+ /** The headers that let the browser compile a response as WebAssembly. */
38
+ const WASM_HEADERS = { 'Content-Type': 'application/wasm' };
35
39
  /**
36
- * Calls `report` as each byte range of a body passes through it, with the bytes that have passed
37
- * and the bytes that the response announced. `total` is 0 when the response gave no length.
40
+ * True when the browser compiles `response` as it came: its Content-Type is `application/wasm`
41
+ * alone. Chrome refuses the type with any parameter.
38
42
  */
39
- function counted(body, total, report) {
43
+ function compilesAsSent(response) {
44
+ return response.headers.get('content-type')?.toLowerCase() === 'application/wasm';
45
+ }
46
+ /**
47
+ * Reads `body` to its end and calls `report` as each byte range arrives, with the bytes that have
48
+ * arrived and the bytes that the response announced: 0 when it gave no length. A broken download
49
+ * or `stop` ends the reading quietly, as the compile reports the download's fault.
50
+ */
51
+ function countBytes(body, total, report, stop) {
40
52
  let loaded = 0;
41
- return body.pipeThrough(new TransformStream({
42
- transform(chunk, controller) {
53
+ const counter = new WritableStream({
54
+ write(chunk) {
43
55
  loaded += chunk.byteLength;
44
56
  report(loaded, total);
45
- controller.enqueue(chunk);
46
57
  },
47
- }));
58
+ });
59
+ return body.pipeTo(counter, { signal: stop }).catch(() => { });
48
60
  }
49
61
  /**
50
62
  * Downloads a WebAssembly file and compiles it as it arrives. `name` says what the file is, for
51
- * errors. `readHead` reads a copy of the download, such as the start of the module, while the
52
- * browser compiles. `onDownload` hears the bytes as they arrive, with the length that the response
53
- * announced, or 0 when it gave none. Fails with E1406 when the file does not download whole or is
54
- * not WebAssembly, and with E1418 when the page's Content-Security-Policy blocks WebAssembly.
63
+ * errors. `started` is a download of the file that the page has already begun. `readHead` reads a
64
+ * copy of the download, such as the start of the module, while the browser compiles.
65
+ * `onDownload` hears the bytes as they arrive, with the length that the response announced, or 0
66
+ * when it gave none, and hears the last of them before the compile's result returns. Fails with
67
+ * E1406 when the file does not download whole or is not WebAssembly, and with E1418 when the
68
+ * page's Content-Security-Policy blocks WebAssembly.
69
+ *
70
+ * The browser compiles the downloaded response itself whenever its type allows. Chrome keeps the
71
+ * code that it compiles from a response that it downloaded, and a later visit that takes the file
72
+ * from the HTTP cache reads that code rather than compiling again. A file that a host sends with
73
+ * another type compiles through a response that the engine makes with the right type: it still
74
+ * compiles as it arrives, but afresh on every visit.
55
75
  */
56
76
  export async function compileWasm(url, name, error, readHead, started, onDownload) {
57
77
  const where = shownAddress(url);
@@ -72,33 +92,36 @@ export async function compileWasm(url, name, error, readHead, started, onDownloa
72
92
  }
73
93
  if (!response.ok || !response.body)
74
94
  throw error('E1406', `${name} did not download from ${where}: HTTP ${response.status}.`);
75
- let body = response.body;
95
+ const compiled = compilesAsSent(response)
96
+ ? response
97
+ : new Response(response.body, { headers: WASM_HEADERS });
98
+ // The readers each take a copy of the download. A copy keeps the browser's cache of the compiled
99
+ // code, and the browser hands every copy each byte range as it arrives, without waiting for the
100
+ // slowest reader, so no reader holds up the compile.
101
+ const copy = () => compiled.clone().body;
102
+ const stop = new AbortController();
103
+ let counting;
76
104
  if (onDownload) {
77
105
  const length = Number(response.headers.get('content-length'));
78
106
  const total = Number.isFinite(length) && length > 0 ? length : 0;
79
107
  onDownload(0, total);
80
- body = counted(body, total, onDownload);
81
- }
82
- let head = Promise.resolve(undefined);
83
- if (readHead) {
84
- const [compiled, read] = body.tee();
85
- body = compiled;
86
- // A broken download also fails the compile, which reports it.
87
- head = readHead(read).catch(() => undefined);
108
+ counting = countBytes(copy(), total, onDownload, stop.signal);
88
109
  }
110
+ // A broken download also fails the compile, which reports it.
111
+ const head = readHead?.(copy()).catch(() => undefined);
89
112
  let module;
90
113
  try {
91
- // The engine gives the type itself, so a host that sends .wasm files with another type still
92
- // compiles them as they arrive.
93
- module = await WebAssembly.compileStreaming(new Response(body, { headers: { 'Content-Type': 'application/wasm' } }));
114
+ module = await WebAssembly.compileStreaming(compiled);
94
115
  }
95
116
  catch (thrown) {
117
+ stop.abort();
96
118
  if (!wasmAllowed())
97
119
  throw error('E1418', `the page's Content-Security-Policy does not let ${name} compile: ${reason(thrown)}.`);
98
120
  if (thrown instanceof WebAssembly.CompileError)
99
121
  throw error('E1406', `${name} from ${where} is not a WebAssembly module: ${reason(thrown)}.`);
100
122
  throw error('E1406', `${name} did not download whole from ${where}: ${reason(thrown)}.`);
101
123
  }
124
+ await counting;
102
125
  return { module, head: await head };
103
126
  }
104
127
  /**
@@ -38,6 +38,13 @@ export declare function bootstrapFailure(message: string, error: WasmError): Eng
38
38
  * a production build.
39
39
  */
40
40
  export declare function startedWorkerScript(): URL | undefined;
41
+ /**
42
+ * The script that `start` would start a worker from, as the thread resolves it, without starting
43
+ * one: `start` runs while the thread's `Worker` is a stand-in that only notes the address. So a
44
+ * thread learns the built file's address of a worker that it starts later, to download its script
45
+ * ahead. Undefined when `start` throws.
46
+ */
47
+ export declare function workerScriptOf(start: () => Worker): URL | undefined;
41
48
  /**
42
49
  * Starts an engine worker. `start` constructs it in the form that bundlers read, `new Worker(new
43
50
  * URL('<file>', import.meta.url), options)`, and runs while the thread's `Worker` starts a script
@@ -135,6 +135,33 @@ function bootstrappingWorker(Native) {
135
135
  }
136
136
  return BootstrappedWorker;
137
137
  }
138
+ /**
139
+ * The script that `start` would start a worker from, as the thread resolves it, without starting
140
+ * one: `start` runs while the thread's `Worker` is a stand-in that only notes the address. So a
141
+ * thread learns the built file's address of a worker that it starts later, to download its script
142
+ * ahead. Undefined when `start` throws.
143
+ */
144
+ export function workerScriptOf(start) {
145
+ const Native = globalThis.Worker;
146
+ let script;
147
+ // A plain constructor, as `new` refuses an arrow function. It returns an object, which `new` gives
148
+ // back in place of the stand-in's own.
149
+ function NotingWorker(address) {
150
+ script = new URL(String(address), globalThis.location?.href);
151
+ return {};
152
+ }
153
+ globalThis.Worker = NotingWorker;
154
+ try {
155
+ start();
156
+ }
157
+ catch {
158
+ script = undefined;
159
+ }
160
+ finally {
161
+ globalThis.Worker = Native;
162
+ }
163
+ return script;
164
+ }
138
165
  /**
139
166
  * Starts an engine worker. `start` constructs it in the form that bundlers read, `new Worker(new
140
167
  * URL('<file>', import.meta.url), options)`, and runs while the thread's `Worker` starts a script
@@ -105,6 +105,15 @@ export interface SketchEngine {
105
105
  * this is true, so a held frame or a replay shows the finished scene.
106
106
  */
107
107
  readonly held: boolean;
108
+ /**
109
+ * Resolves once the GPU has finished the engine's first frame, as `engine.firstFrame` does on
110
+ * the page. Start the downloads that the first frame does not need here, so they leave the
111
+ * network to the first frame's own files. Never await it in the setup: the first frame waits
112
+ * for the setup. In hold mode and a replay, it resolves once the engine has stepped the sketch
113
+ * to the last frame, which no later frame follows, so work that it starts never changes the
114
+ * frames that those modes show. It never resolves when the engine stops first.
115
+ */
116
+ readonly firstFrame: Promise<void>;
108
117
  }
109
118
  /**
110
119
  * The user's display preferences, which the page reads from the system and passes on.
@@ -188,6 +197,32 @@ export interface SketchOptions {
188
197
  fixedRate?: number;
189
198
  /** The most fixed steps that one frame runs, after a slow frame. The default is 8. */
190
199
  maxFixedSteps?: number;
200
+ /**
201
+ * False keeps the governor out of its lowest quality tier, whose cuts reach the scene's
202
+ * settings. A scene whose sketch thread limits its frames gains nothing from the tier's smaller
203
+ * render: the cut cannot make the sketch work cheaper, and the smaller picture is a loss. The
204
+ * default is true, and the page's `?tier=off` switch keeps the tier out too.
205
+ */
206
+ lowestTier?: boolean;
207
+ /**
208
+ * The files that the setup loads, as addresses that resolve against the page's address, as the
209
+ * loading calls' do. A live start begins to download them as soon as the sketch's module has
210
+ * loaded, often while the engine's core still downloads. The setup's loads then take the bytes
211
+ * that arrived or are on their way, with no second download. List the files in the order that
212
+ * the setup needs them. Two download at a time, so the engine's own start files keep free
213
+ * connections. A load of a later file moves it to the front, and up to four listed files
214
+ * download while loads wait for them. Name only files that the first frame waits for, and start
215
+ * the others when `engine.firstFrame` resolves. A file that no load takes costs its download,
216
+ * and its bytes stay in memory until the engine stops. Hold mode, a replay and a recording
217
+ * download each file at its load, as without the list.
218
+ */
219
+ downloads?: readonly (string | URL)[];
220
+ /**
221
+ * False turns off the warning of a development build for a load whose download starts only
222
+ * after another load's file has arrived, during the setup. Turn it off when each address comes
223
+ * from the contents of the file before it. The default is true.
224
+ */
225
+ serialLoadWarning?: boolean;
191
226
  }
192
227
  declare const SKETCH_MARKER: unique symbol;
193
228
  /**
@@ -35,8 +35,8 @@ export interface InputPointer {
35
35
  /**
36
36
  * The wheel's scroll since the previous frame, in pixels: positive where a page would scroll down.
37
37
  * A wheel that scrolls by lines counts 16 pixels a line, and one that scrolls by pages counts 100
38
- * a page, as three.js's controls count them. Scroll that follows a release of the pointer waits
39
- * for the next frame, so a frame's scroll never comes after the end of its drag.
38
+ * a page. Scroll that follows a release of the pointer waits for the next frame, so a frame's
39
+ * scroll never comes after the end of its drag.
40
40
  */
41
41
  readonly wheel: number;
42
42
  /**