@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
@@ -3,7 +3,7 @@ id: api/sketch
3
3
  title: "Sketch API: defineSketch and the context"
4
4
  status: experimental
5
5
  since: "0.1"
6
- summary: "The context object: scene, assets, materials, geometry, textures, input, time, engine, quality, post, render, page, ui, debug; the callbacks."
6
+ summary: "The context object: scene, assets, materials, geometry, textures, input, time, engine, quality, post, render, page, ui, debug; the callbacks; the options, with the download list."
7
7
  ---
8
8
 
9
9
  # Sketch API: defineSketch and the context
@@ -44,7 +44,9 @@ The page passes the module's address to `createEngine`, and the engine loads the
44
44
 
45
45
  A module whose default export is not `defineSketch(...)` fails the start with [E1401](../errors/E1401.md). A module that does not load fails it with [E1410](../errors/E1410.md): the module did not download, or its code threw an error while it loaded. The engine imports a module that does not load once more, after a short wait, and the console notes the second import. So a short break in the network does not fail the start. Only a second failure gives E1410, with the first failure's reason.
46
46
 
47
- Code at the top of the module runs once, when the module loads, before the engine calls `setup`. With worker threads, the module loads after the engine has started in the sketch worker. In the single-threaded build, the engine downloads the module while it downloads its core, to start sooner on a slow network. So there, code at the top of the module can run before the engine has started, and also when the start fails.
47
+ Code at the top of the module runs once, when the module loads, before the engine calls `setup`. The engine loads the module while it downloads its core, in the sketch worker or, in the single-threaded build, on the page. So the module's own imports and its top-level code take no time of their own on a slow network. Code at the top of the module can therefore run before the engine has started, and also when the start fails. Work there must not need the engine. Every call that makes scene data goes through the setup's context, and an engine call before the core starts fails with [E1403](../errors/E1403.md). Work that needs no engine, such as a large table that the first view reads, can run there and overlap the download.
48
+
49
+ Hold mode, a replay and a recording load the module only after the engine has started and seeded the thread's random numbers. There, code at the top of the module draws the same numbers from `Math.random` on every run ([Testing](../guides/testing.md)).
48
50
 
49
51
  ## The setup function
50
52
 
@@ -54,12 +56,15 @@ An error that `setup` throws ends the start: `createEngine` rejects with it. An
54
56
 
55
57
  ## Options
56
58
 
57
- `defineSketch` takes options after the setup function. They set the fixed steps, which [Time](time.md#fixed-steps) explains.
59
+ `defineSketch` takes options after the setup function. They set the fixed steps, which [Time](time.md#fixed-steps) explains, and the files that the setup loads.
58
60
 
59
61
  | Option | Default | What it sets |
60
62
  | --- | --- | --- |
61
63
  | `fixedRate` | 60 | Fixed steps per second of sketch time: how often `onFixedUpdate` runs |
62
64
  | `maxFixedSteps` | 8 | The most fixed steps that one frame runs, after a slow frame |
65
+ | `lowestTier` | true | False keeps the governor's lowest quality tier out, for a scene that its own sketch thread limits |
66
+ | `downloads` | none | The files that the setup loads, which start to download as soon as the module has loaded ([The download list](#the-download-list)) |
67
+ | `serialLoadWarning` | true | False turns off a development build's warning for a load that waited for another one ([Loads one after another](#loads-one-after-another)) |
63
68
 
64
69
  ```ts
65
70
  export default defineSketch(setup, { fixedRate: 120 });
@@ -67,6 +72,43 @@ export default defineSketch(setup, { fixedRate: 120 });
67
72
 
68
73
  An option out of its range fails the start with [E1214](../errors/E1214.md), before the engine calls `setup`.
69
74
 
75
+ ### The download list
76
+
77
+ A setup that awaits its files one after another waits for each download in turn. The `downloads` option names the files that the setup loads, so they download before the setup asks for them:
78
+
79
+ ```ts
80
+ // sketch.ts
81
+ import { defineSketch } from '@null3d/engine';
82
+
83
+ const SHIP = 'models/ship.glb';
84
+ const SKY = 'env/harbor.ktx2';
85
+
86
+ export default defineSketch(
87
+ async ({ assets, scene }) => {
88
+ const [ship, sky] = await Promise.all([assets.loadGltf(SHIP), assets.loadEnvironment(SKY)]);
89
+ scene.setEnvironment(sky);
90
+ scene.instantiate(ship);
91
+ },
92
+ { downloads: [SHIP, SKY] },
93
+ );
94
+ ```
95
+
96
+ A live start begins the downloads as soon as the module has loaded. That is often before the engine's core has arrived, so the files download while the engine starts. The setup's loads take the bytes that arrived or are on their way, and nothing downloads twice. Each address resolves against the page's address, as the loading calls' addresses do.
97
+
98
+ - List the files in the order that the setup needs them. Two download at a time, so the engine's own files, such as the shaders of the first frame, still find free connections to the server. A load of a later file moves it to the front of the list. While loads wait for listed files, up to four download at once, which still leaves connections for the engine's own files.
99
+ - Name only the files that the first frame waits for. A file that loads after the first frame takes bandwidth from the files that the first frame needs. Start its load when `engine.firstFrame` resolves instead ([The engine field](#the-engine-field)).
100
+ - A file that no load takes costs its download, and its bytes stay in memory until the engine stops. Nothing decodes it.
101
+ - Hold mode, a replay and a recording download each file at its load, as without the list, so their runs stay the same.
102
+ - `assets.onProgress` counts the listed files, also the bytes that arrived before the setup added the handler.
103
+
104
+ An entry that is not a file's address, such as an empty string, fails the start with [E1214](../errors/E1214.md). A listed file that does not download fails the load that takes it with [E1411](../errors/E1411.md).
105
+
106
+ ### Loads one after another
107
+
108
+ A development build watches the setup's loads. Sometimes a load starts its download only after another load's file has arrived, while no other file downloads. The console then shows one warning that names both files. The two files could have downloaded together, and the first frame waited for the gap. Start both loads before you await either, as `Promise.all` does above, or name both files in `downloads`. An environment that the engine makes with no file counts as an earlier load too. A load that starts only after `assets.builtinEnvironment` or `assets.skyEnvironment` has finished could have started beside it.
109
+
110
+ When the second file's address comes from the first file, as a level file names its models, the order is needed. A JSON file that holds the second file's name passes without a warning. For other such cases, pass `serialLoadWarning: false`. The engine watches only the loads of a live setup, not a model's own files and not loads after the first frame. A production build has no warning.
111
+
70
112
  ## The context
71
113
 
72
114
  | Field | What it holds |
@@ -78,6 +120,7 @@ An option out of its range fails the start with [E1214](../errors/E1214.md), bef
78
120
  | `assets` | Downloads of textures, JSON and binary files, with preloads and progress: [Assets](assets.md) |
79
121
  | `input` | Pointer, touch, keyboard and gamepad input, and action maps: [Input](input.md) |
80
122
  | `post` | The tone mapping and the exposure: [Post-processing API](post.md) |
123
+ | `render` | The sketch's own render passes, such as a camera that draws into a texture: [Render graph API](render.md) |
81
124
  | `quality` | The quality preset that the engine runs, and its settings: [Quality API](quality.md) |
82
125
  | `time` | Sketch time in seconds, the frame's step and the frame number: [Time](time.md) |
83
126
  | `engine` | The canvas's size, and what the device can do: [The engine field](#the-engine-field) |
@@ -94,6 +137,8 @@ An option out of its range fails the start with [E1214](../errors/E1214.md), bef
94
137
 
95
138
  `engine.held` is true when the engine steps the sketch itself, as hold mode and a replay do. It is false when the sketch runs live. A sketch that returns before its scene is complete waits for it when this is true. A held frame or a replay then shows the finished scene. A live page starts the work without awaiting it, and the result appears as it lands.
96
139
 
140
+ `engine.firstFrame` is a promise that resolves once the GPU has finished the engine's first frame, as `engine.firstFrame` does on the page. Start the downloads that the first frame does not need when it resolves. They then leave the network to the first frame's own files, such as its shaders. A frame number is no such signal: the thread that draws can still be drawing the first frame while the sketch runs the second. Never await the promise in the setup, because the first frame waits for the setup. In hold mode and a replay, the promise resolves once the engine has stepped the sketch to its last frame. No frame follows that one, so the work that it starts never changes what those modes show. The promise never resolves when the engine stops first.
141
+
97
142
  ```ts
98
143
  export default defineSketch(({ scene, engine }) => {
99
144
  // A portrait screen gets a wider view, so the scene still fits across it.
@@ -103,6 +148,20 @@ export default defineSketch(({ scene, engine }) => {
103
148
  });
104
149
  ```
105
150
 
151
+ A scene that adds far scenery after the first frame starts its download then, and in hold mode loads it in the setup:
152
+
153
+ ```ts
154
+ // sketch.ts
155
+ import { defineSketch } from '@null3d/engine';
156
+
157
+ export default defineSketch(async ({ assets, engine, scene }) => {
158
+ const addForest = async () => scene.instantiate(await assets.loadGltf('models/forest.glb'));
159
+ // Build the first view here.
160
+ if (engine.held) await addForest(); // a held frame shows the finished scene
161
+ else void engine.firstFrame.then(addForest).catch((error) => console.error(error)); // the forest appears as it lands
162
+ });
163
+ ```
164
+
106
165
  ## The callbacks
107
166
 
108
167
  Each frame runs the callbacks in this order, and each callback is optional:
@@ -115,6 +174,8 @@ Each frame runs the callbacks in this order, and each callback is optional:
115
174
 
116
175
  `step` is the length of a fixed step in seconds, 1/60 at the default rate. `dt` is the frame's step in seconds, the same value as `time.dt`. It is 0 in the first frame and after a pause, and it is never longer than a quarter second. [Time](time.md) gives the details.
117
176
 
177
+ `onDestroy()` runs once when the engine stops, on the sketch's thread, before its workers stop. Remove the timers, event listeners and message handlers that the sketch added outside the engine there. After it, every call to the engine fails with [E1420](../errors/E1420.md).
178
+
118
179
  ## When changes show
119
180
 
120
181
  Setters take effect at once. Changes that `onFixedUpdate` and `onUpdate` make show in the frame that the engine draws next. Creating, destroying and reparenting objects take effect when the engine processes the frame, after `onUpdate` returns ([Scene](scene.md#when-changes-take-effect)).
@@ -0,0 +1,169 @@
1
+ ---
2
+ id: api/sound
3
+ title: "Sound (@null3d/sound)"
4
+ status: experimental
5
+ since: "0.3"
6
+ summary: "createSound and connectSound: loops, groups and one-shots placed in the scene, played with the browser's audio and driven from the sketch on the audio thread."
7
+ ---
8
+
9
+ # Sound (@null3d/sound)
10
+
11
+ > Roadmap step 0.3, first released in null3D 0.1.0. The API is experimental, so it can still change between versions.
12
+
13
+ ```mermaid
14
+ flowchart LR
15
+ sketch["Sketch worker<br/>createSound: loops,<br/>groups and shots"] -- "writes places, levels,<br/>rates and tones" --> table[("One shared<br/>table")]
16
+ table --> mixer["Audio thread<br/>the mixer"]
17
+ page["Page<br/>connectSound: files<br/>and audio nodes"] --> nodes["Each voice:<br/>source, filter,<br/>gain, panner"]
18
+ mixer -- "drives every voice<br/>in each quantum" --> nodes
19
+ nodes --> out["Speakers or<br/>headphones"]
20
+ ```
21
+
22
+ `@null3d/sound` plays sound that follows the scene. A sketch makes its sounds and moves them as it moves its objects. The page plays them with the browser's audio, through the add-on's page half. A sound can come from a place, such as a waterfall or a car. It can also play in both ears alike, such as wind or rain.
23
+
24
+ The browser offers its audio only on the page's main thread, and the sketch runs in a worker. The add-on bridges the two. The sketch writes each sound's place, level, playback rate and tone into a table that the page shares. A mixer on the browser's audio thread, compiled from Rust to WebAssembly, reads that table and drives every voice. Where the page shares its memory with its workers, no frame sends a message, and the page's thread does no work while the sounds play. Only a shot sends one, once for each play.
25
+
26
+ ```sh
27
+ bun add @null3d/sound
28
+ ```
29
+
30
+ ```ts
31
+ // sketch.ts
32
+ import { defineSketch } from '@null3d/engine';
33
+ import { createSound } from '@null3d/sound';
34
+
35
+ export default defineSketch((ctx) => {
36
+ const { scene } = ctx;
37
+ const camera = scene.createPerspectiveCamera({ position: [0, 1.6, 6], target: [0, 1, 0] });
38
+ scene.setActiveCamera(camera);
39
+
40
+ const sound = createSound(ctx, { listener: camera });
41
+ // A waterfall at a place, full within 4 m and gone by 120 m.
42
+ const fall = sound.loop({ file: '/sounds/waterfall.mp3', near: 4, far: 120 });
43
+ fall.setPosition(-20, 2, -30);
44
+ // Wind in both ears, whose level the sketch sets each frame.
45
+ const wind = sound.loop({ file: '/sounds/wind.mp3', positional: false, level: 0.5 });
46
+
47
+ return {
48
+ onUpdate() {
49
+ wind.setLevel(0.4 + 0.2 * Math.sin(ctx.time.now * 0.3));
50
+ },
51
+ onLateUpdate() {
52
+ sound.update();
53
+ },
54
+ };
55
+ });
56
+ ```
57
+
58
+ ```ts
59
+ // page.ts
60
+ import { createEngine } from '@null3d/engine';
61
+ import { connectSound } from '@null3d/sound/page';
62
+
63
+ const engine = await createEngine({
64
+ canvas: document.querySelector('canvas')!,
65
+ sketch: new URL('./sketch.ts', import.meta.url),
66
+ });
67
+ const sound = connectSound(engine);
68
+ document.querySelector('#sound')!.addEventListener('click', () => void sound.start());
69
+ ```
70
+
71
+ Call `sound.update()` once a frame, in `onLateUpdate`. It reads the listener's place and turn in the world, which by then holds every move of the frame's `onUpdate`. A camera that moves in `onLateUpdate` itself is heard one frame later, which no ear can tell. A browser starts a page's audio only in answer to the user. So the page calls `start` from a click, a tap or a key. `connectSound(engine, { startOnInput: true })` starts it on the user's first input instead.
72
+
73
+ ## The sketch's calls
74
+
75
+ | Call | What it does |
76
+ | --- | --- |
77
+ | `createSound(ctx, options)` | Makes the sketch's sounds. `listener` is required: the camera, or another object that hears. `capacity` is the emitters that the sounds hold together, 256 by default and 4,096 at most. `volume` sets every sound's volume, from 0 to 1. A sketch has one sound system at a time: a second call while the first lives throws error 2504. |
78
+ | `loop(options)` | A sound that plays its file over and over. `positional: false` makes a bed that plays in both ears. `level`, `rate`, `tone` and `position` give its first values. |
79
+ | `group(options)` | `count` sounds that play one file, of which the loudest `voices` sound at once. Use it for the cars in a street or the bees of a swarm. |
80
+ | `shot(options)` | A sound that plays its file once for each call of its `play`, such as thunder. `voices` plays that many at once, 2 by default. A play past that count fades the oldest out quickly. Each play starts about 20 ms after the call, at its own level, place and pitch, or about 80 ms after it when it replaces a play that still sounds. |
81
+ | `setVolume(volume)` | The volume of every sound, from 0 to 1. |
82
+ | `update()` | Reads the listener's place and turn, and counts the frame. Call it once a frame. |
83
+ | `destroy()` | Stops every sound and closes the link to the page. The page then waits for the sketch's next sound system. |
84
+ | `connected` | True once the page's half has opened its link. |
85
+
86
+ A loop has `setLevel`, `setRate`, `setTone`, `setPosition` and `destroy`. A group has the same setters with a member's index first, such as `setPosition(index, x, y, z)`. A group also has the arrays `positions`, `levels`, `rates` and `tones`, which are views of the table. A sketch that keeps its places in one array copies them in one call, as in `cars.positions.set(places)`. A shot has `play(x, y, z, level, rate)` and `destroy`. A destroyed sound's setters do nothing. Its arrays may then serve another sound, so a sketch drops them with the group.
87
+
88
+ The setters write numbers into the table and make no object, so a sketch may call them in every frame. `update` makes no object either. A sound made before the page connects plays once it does, and a sketch may make sounds at any time.
89
+
90
+ ## The values of a sound
91
+
92
+ | Value | Range | What it does |
93
+ | --- | --- | --- |
94
+ | level | 0 and up, 1 by default | The sound's loudness. 0 silences it. |
95
+ | rate | 1 by default | The playback rate. 2 plays the file twice as fast and an octave higher. Tie it to a car's speed for its engine. |
96
+ | tone | 0 to 1, 1 by default | A low-pass filter. 1 plays the file as it is, and 0 keeps only its lows, from about 120 Hz down. Strong wind sounds brighter than a breeze, so raise its tone with its speed. |
97
+ | place | world units | Where the sound comes from. A bed that plays in both ears has no place. |
98
+
99
+ Each value eases toward the one that the sketch writes, so a change never clicks. The level, the tone and the rate each ease in about 80 ms. A level or a place that is not a finite number silences the sound until the sketch writes one that is. A rate or a tone that is not one plays the file at its own pitch and brightness.
100
+
101
+ ## Distance
102
+
103
+ A sound's options take a placement:
104
+
105
+ | Option | What it does |
106
+ | --- | --- |
107
+ | `near` | The distance within which the sound plays at its full level. Beyond it the level falls with distance: at twice `near` it is half, at four times a quarter. |
108
+ | `far` | The distance at which the sound has faded out. The fade starts at 60% of it. |
109
+ | `muffle` | Whether the sound loses its highs as it nears `far`, as distant sounds do. It is on by default when `far` is given. |
110
+
111
+ A sound with neither distance keeps the level that the sketch gives it wherever the listener stands. Use that for a bed whose level the sketch works out itself, such as the sea, which grows louder as the camera nears the shore.
112
+
113
+ ## Groups and their voices
114
+
115
+ A browser mixes a few dozen voices well, and a scene may have hundreds of sources of one kind. A group gives its members a few voices. The mixer ranks the members by their loudness where the listener stands, from their level and distance. It gives each voice to one of the loudest. A voice keeps its member while that member stays close to the cut. So a voice does not flap between two members at the same distance. A voice that moves to another member fades out first, so its sound never jumps across the scene. It takes the new member's pitch before it fades in.
116
+
117
+ A group's voices add as power: three at full level sound about 5 dB louder than one. Give a group's points lower levels than a loop's. Write a mass of like sources as one loop, whose level follows the density around the camera, not one source for each object.
118
+
119
+ A group's voices play one file, each from a point of its own, so the copies never sound in step. Rates that differ for each member add no richness that the offsets do not already give. They also make the group's pitch change as the camera moves and the nearest members change. Keep the members at one rate, and use `setRate` for a source whose own speed differs, such as a car's engine.
120
+
121
+ The page plays 32 voices at most. A loop takes one voice, a group takes its `voices`, and a shot takes its `voices`, wherever free voices sit. A sketch that asks for more than 32 at once gets error 2501, which names the count. While other voices are free, a destroyed sound's voices rest for a third of a second before another sound takes them. So their fade ends first.
122
+
123
+ ## The page's calls
124
+
125
+ | Call | What it does |
126
+ | --- | --- |
127
+ | `connectSound(engine, options)` | Connects the page to the sketch's sounds. Call it once on a page, after `createEngine` resolves. `startOnInput` starts the audio on the user's first click, tap or key other than Escape, which are the inputs that let a browser start a page's audio. `muted` starts muted. |
128
+ | `start()` | Starts the audio. Call it in the handler of a click, a tap or a key. Called so, it resolves once the audio runs, and each sound fades in as its file arrives. Called outside an input, as a page that plays its sound by default does, it loads the files, and the browser holds the audio until the user's first click, tap or key. The sounds then start at once. |
129
+ | `setMuted(muted)` | Mutes or unmutes every sound. |
130
+ | `state` | `off` before `start`, then `starting` until the audio runs, `on`, `paused` while the engine is paused or the page is hidden, `interrupted` while the browser holds the audio until the user's next input, and `stopped` after the engine stops. |
131
+ | `onState(handler)` | Calls the handler at each change of the state, such as to label a sound button. Returns a function that removes the handler. |
132
+ | `stop()` | Stops the audio for good. The engine's stop does the same. |
133
+
134
+ The page loads nothing until `start` runs: no file, no audio and no mixer. The mixer's module is about 18 KB. Each file loads once, however many sounds play it. A file that fails to load leaves its sounds silent, and the console names the file. A mixer that fails on the audio thread stops the sound with a warning. So does a mixer module that the host answers with something else, such as its own page for a missing file.
135
+
136
+ While the browser holds the audio, the page starts no file. So the browser warns once, as the page makes the audio, and not for each voice. A shot that plays in that time is dropped. It would otherwise sound late, after the user's first input, long after the event that played it.
137
+
138
+ The [sound demo](https://github.com/null3d-engine/null3d/tree/main/examples/sound) shows a storm. Each strike's thunder plays from where the bolt struck, once sound could have reached the camera. A brook in it is a group of points.
139
+
140
+ ## Pauses and hidden pages
141
+
142
+ When the sketch's frames stop, every sound fades out within about a second, and the page suspends the audio soon after. That happens when `engine.setPaused(true)` pauses the engine, when the browser hides the page, and when a sketch stops calling `update`. It also happens when the engine was paused before the sound started. The audio resumes, and the sounds fade back in, when the frames move again.
143
+
144
+ A browser can also take the audio away, as an iPhone does during a call. The state is then `interrupted`, and the page resumes the audio at the user's next input, or when the page shows again. A sound button calls `start` in that state rather than muting.
145
+
146
+ ## Panning and the quality presets
147
+
148
+ A sound that comes from a place plays through the browser's panner. The High and Ultra presets use its HRTF model, which places a sound around the head on headphones. Low and Medium use equal-power panning, which places it between the speakers and costs less on the audio thread. A change of preset changes every voice's panning.
149
+
150
+ ## Files
151
+
152
+ A relative address resolves against the page's address, as the engine's loaders do ([Assets](assets.md)). So `'sounds/sea.mp3'` on `https://example.com/game/` loads `https://example.com/game/sounds/sea.mp3`. An address from `new URL('./sea.mp3', import.meta.url)` resolves against the sketch module instead. MP3 decodes in every browser. An MP3 encoder adds samples at each end of a file, and records how many in a header in the file's first frame. Some browsers keep them as they decode. Safari kept 576 at each end of a mono loop, which would dip at every join. The add-on reads the header and drops what the browser kept, so a loop joins with no gap. A file without that header loses only the silence at its ends, up to 2,048 samples. A file made to loop joins its end to its start, as the sample loops do.
153
+
154
+ ## Browsers
155
+
156
+ - Firefox's audio listener has no place parameters. The mixer turns each sound's place into the listener's frame, so the listener stays still in every browser.
157
+ - An iPhone's silent switch mutes a page's audio unless the page plays media. The add-on sets the page's audio session to playback where Safari offers it.
158
+ - A page without cross-origin isolation runs the sketch on its own thread ([Hosting and cross-origin isolation](../getting-started/hosting.md)). There the page hands the mixer a copy of the table once per display frame. That costs the page's thread a copy of a few kilobytes, a message and a small view of the returned buffer in each frame.
159
+
160
+ ## Costs and limits
161
+
162
+ - The mixer runs on the audio thread. Its work grows with the voices and with the members of each group, which it ranks every fourth render quantum. With 32 voices and a group of 200 moving members, it takes about 3 ms of work per second of audio. That figure comes from the mixer's module in Bun on a desktop computer.
163
+ - Each voice is a source, a filter, a gain and a panner. The panner's HRTF model costs the most of them, which is why the lighter presets drop it.
164
+ - A limiter on the page's output holds the mix under full scale. So sounds that sum, or a stereo sound panned to one side, never clip. It adds about 2 dB to quiet passages.
165
+ - The table holds 12 numbers for the listener and 6 for each emitter: 6 KB at the default capacity.
166
+ - The page plays 32 voices at once and the table holds 4,096 emitters at most.
167
+
168
+ [The API reference](reference/sound.md) lists every export of this page with its type and
169
+ description. The add-on's doc comments make it.
@@ -118,6 +118,11 @@ sketch's thread nothing. A change of the camera or of the budget starts a new se
118
118
  then packs the chosen rows into the batch in its own memory, so a moved frame copies no rows
119
119
  through the sketch's heap.
120
120
 
121
+ `createSplats` starts the selection's task and the SPZ reader as it starts, beside the download of
122
+ the index or the file. So the first selection and the first chunk's decode wait for neither. In the
123
+ splat demo, on a simulated phone connection, the reader arrived at 4.4 seconds instead of 7.9. The
124
+ first parts showed at 7.0 seconds instead of 8.3.
125
+
121
126
  The budget follows the quality preset. On each preset the add-on draws at most:
122
127
 
123
128
  | Preset | WebGPU | WebGL2 |
@@ -201,6 +206,8 @@ total size and `splats.loadedBytes` gives the part that has arrived.
201
206
  | `chunkSplats(data, options)` | The chunks that `createSplats` draws, if you want them yourself |
202
207
  | `parseStreamIndex(text, base)` | The chunks that a stream index names |
203
208
  | `colorOfSh(dc, encoded?)` | The linear color of a first-band spherical-harmonic coefficient |
209
+ | `checkSplats(data, what)` | The same `data`, once its arrays hold the number of splats that it names. Otherwise it throws E2101, whose message names `what` |
210
+ | `SPLAT_EXTENSION` | The name of the glTF extension that the add-on reads, `'KHR_gaussian_splatting'` |
204
211
 
205
212
  `Splats` gives `update(eye)`, `setBudget(count)`, `settle()`, `ready`, `total`, `drawn`, `chunks`,
206
213
  `loaded`, `failed`, `bytes`, `loadedBytes`, `feature` and `draw`, and `destroy()` frees it.
@@ -8,7 +8,7 @@ summary: "createSprites; world and screen size modes; atlases."
8
8
 
9
9
  # Sprites
10
10
 
11
- > Roadmap step 0.2, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. Sprites do not cast or receive shadows, and overlap queries do not find them. Coding agents must not rely on either.
11
+ > Roadmap step 0.2, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. Sprites do not cast or receive shadows, and overlap queries do not find them.
12
12
 
13
13
  ```mermaid
14
14
  flowchart LR
@@ -148,7 +148,7 @@ Blended sprites draw after the opaque objects, farthest first, in the same trans
148
148
 
149
149
  ## Clicks and raycasts
150
150
 
151
- Raycasts hit a sprite where the ray crosses its quad, as three.js's `Raycaster` hits a `Sprite`. The hit's `object` is the batch, and its `instance` is the sprite. A sprite batch takes `sprites.on('click', handler)` and the other [pointer events on objects](input.md#pointer-events-on-objects), as an instance batch does. A ray hits the whole quad, also where the sprite's map is clear. [Raycasting](raycast.md#sprites-points-and-lines) has the details.
151
+ Raycasts hit a sprite where the ray crosses its quad. The hit's `object` is the batch, and its `instance` is the sprite. A sprite batch takes `sprites.on('click', handler)` and the other [pointer events on objects](input.md#pointer-events-on-objects), as an instance batch does. A ray hits the whole quad, also where the sprite's map is clear. [Raycasting](raycast.md#sprites-points-and-lines) has the details.
152
152
 
153
153
  ```ts
154
154
  sprites.on('click', (event) => {
@@ -160,25 +160,9 @@ sprites.on('click', (event) => {
160
160
 
161
161
  ## Speed
162
162
 
163
- A batch costs about the same per sprite as an instance batch costs per row. The engine packs each sprite into the data that it keeps for an instance row. So sprites share the culling, sorting and drawing of instance batches. One batch of 100,000 sprites draws in one draw on WebGPU and WebGL2.
163
+ A batch costs about the same per sprite as an instance batch costs per row. The engine packs each sprite into the data that it keeps for an instance row. So sprites share the culling, sorting and drawing of instance batches. One batch of 100,000 sprites draws in one draw on WebGPU and WebGL2, where three.js makes one object and one draw for each sprite.
164
164
 
165
- Every sprite counts toward the device's limit of objects and instance rows, as an instance row does ([Instances and batching](../concepts/instances.md#limits)). Each sprite takes about 215 bytes of engine memory. Sprite batches count toward the limit of 256 instance batches.
166
-
167
- ## Compared with three.js
168
-
169
- | three.js | null3D |
170
- | --- | --- |
171
- | `new THREE.Sprite(new THREE.SpriteMaterial({ map, color }))` | One row of `scene.createSprites({ count, map })`; set `colors` per sprite or `color` for all |
172
- | `sprite.position` | `positions` |
173
- | `sprite.scale.set(w, h, 1)` | `sizes` |
174
- | `material.rotation` | `rotations`, per sprite |
175
- | `material.sizeAttenuation = false` | `sizeAttenuation: false`, with sizes in CSS pixels |
176
- | `sprite.center` | `center`, for the whole batch |
177
- | `texture.offset` and `texture.repeat` for an atlas | `atlas` and `frames` |
178
- | `material.transparent` (true for sprites) | `alphaMode: 'blend'`, the default |
179
- | `material.alphaTest` | `alphaMode: 'mask'` with `alphaCutoff` |
180
-
181
- three.js makes one object and one draw per sprite. null3D draws a whole batch in one draw. Without size attenuation, a three.js sprite's size is a fraction of the view's height that depends on the camera's field of view. A null3D sprite's size is in CSS pixels. A three.js scale of `s` shows `s × h / (2 × tan(fov / 2))` pixels on a canvas `h` CSS pixels high. Raycasts hit sprites as three.js's `Raycaster` does. Sprites face the active camera, which takes the place of `raycaster.camera`.
165
+ Every sprite counts toward the device's limit of objects and instance rows, as an instance row does ([Instances and batching](../concepts/instances.md#limits)). Each sprite takes about 215 bytes of engine memory. Sprite batches count toward the limit of 512 instance batches.
182
166
 
183
167
  ## API reference
184
168
 
package/docs/api/tasks.md CHANGED
@@ -91,9 +91,9 @@ A task that fails does not stop the engine, and a later task tries again. A modu
91
91
 
92
92
  ## The task's module in a build
93
93
 
94
- The address must name JavaScript that the browser imports as a module. In a project built with Vite, write the task in the add-on's package, and let the package's build write it. Give the address of the built file, as in the example above.
94
+ The address must name a module that the browser imports. With the engine's Vite plugin, a production build bundles the module that `new URL('./file.ts', import.meta.url)` names into a chunk of its own, with its imports. A development server compiles a TypeScript file on request.
95
95
 
96
- The file must run on its own. Bundle anything that it imports, or keep it free of imports. A development server compiles a TypeScript file on request, but a production build copies it as it stands.
96
+ The plugin leaves a file under a package's `dist` folder as it is, so a published add-on ships its task already built. That file must run on its own: bundle anything that it imports, or keep it free of imports.
97
97
 
98
98
  ## Related pages
99
99
 
@@ -8,7 +8,7 @@ summary: "createTerrain: a height field drawn as a camera-centered quadtree of b
8
8
 
9
9
  # Terrain (@null3d/terrain)
10
10
 
11
- > Roadmap step 0.2, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. The ground carries no collision. A block morphs toward its parent block's surface before it gives way to it, and a skirt closes the seam between neighbours that differ by more than one level. Coding agents must not use these parts.
11
+ > Roadmap step 0.2, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. The ground has no collision. A block morphs toward its parent block's surface before it gives way to it, and a skirt closes the seam between neighbours that differ by more than one level.
12
12
 
13
13
  ```mermaid
14
14
  flowchart LR
@@ -101,22 +101,10 @@ The terrain carries no collision. Read `heightAt(x, z)` and `normalAt(x, z, out)
101
101
 
102
102
  A terrain draws one mesh per visible block. The blocks near the camera are the most and the finest, and the few coarse blocks cover the rest. A 1,200 meter ground at the default settings draws about 200 blocks, near 130,000 triangles, from a camera near the ground. That figure is for a picture 1,080 pixels tall. A taller picture draws more and finer blocks, and a shorter one draws fewer. A higher camera or a wider field of view draws fewer and coarser blocks, and the Low preset draws coarser blocks than High. A block splits or merges only when the camera moves far enough to need other blocks.
103
103
 
104
- The quadtree selection and the block build run in the add-on's own WebAssembly module. The module runs on the engine's job workers, so `update` only asks for the work. A crossing can need tens of new blocks. One task builds at most `blocksPerUpdate` of them, 16 by default. The first selection builds every block that it needs, over a few tasks. The ground draws its last complete selection until the new one is built, and `terrain.building` is true meanwhile. The arrays that the tasks fill are made once and shared, so the frame path allocates nothing. A block that the view leaves gives up its mesh to the next block that the ground needs. A terrain that follows a moving camera therefore builds meshes only until it holds `maxBlocks` of them. `terrain.setVisible(false)` hides the ground, and `setVisible(true)` shows the current selection again.
104
+ The quadtree selection and the block build run in the add-on's own WebAssembly module. The module runs on the engine's job workers, so `update` only asks for the work. A crossing can need tens of new blocks. One task builds at most `blocksPerUpdate` of them, 16 by default. The first selection builds every block that it needs, over a few tasks. The ground draws its last complete selection until the new one is built, and `terrain.building` is true meanwhile. The arrays that the tasks fill are made once and shared, so the frame path allocates nothing. A block that the view leaves gives up its mesh to the next block that the ground needs. A terrain that follows a moving camera therefore builds meshes only until it holds `maxBlocks` of them. `terrain.setVisible(false)` hides the ground, and `setVisible(true)` shows the current selection again. `terrain.setTint(color)` multiplies the ground's own colors, white by default, so a scene can take the ground down with the hour at night without changing its day look.
105
105
 
106
106
  A sketch that never imports `@null3d/terrain` ships no terrain code and starts no terrain work. The package follows the engine's add-on rules: its surface function ships compiled, and the selection and build module loads when a terrain first picks its blocks.
107
107
 
108
- ## Compared with three.js
109
-
110
- three.js has no terrain class. Projects displace a `PlaneGeometry` on the CPU, shape the ground with three.js's `ImprovedNoise` and a height map, or add a library such as three-mesh-bvh for large ground.
111
-
112
- | three.js | null3D |
113
- | --- | --- |
114
- | A `PlaneGeometry` with displaced vertices | `createTerrain` with a height function or height map |
115
- | A quadtree or a library for levels of detail | The add-on's own camera-centered quadtree |
116
- | A hand-painted ground or per-vertex colors | A splat map that blends four tiled layers |
117
- | A physics collider or a height lookup on the mesh | `heightAt` and `normalAt` |
118
- | A vertex morph between levels | A block morphs toward its parent, and a skirt covers a neighbour more than one level away |
119
-
120
108
  ## Related pages
121
109
 
122
110
  - [Geometry](geometry.md): meshes from arrays, and the generators.
@@ -8,7 +8,7 @@ summary: "loadTexture options; KTX2 files; fromData; fromImageBitmap; fromCanvas
8
8
 
9
9
  # Textures
10
10
 
11
- > Roadmap step 0.1, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. Step 0.2 adds `textures.fromPass` and `textures.fromCanvas`, and step 0.3 adds `textures.fromVideo`. Materials cannot sample a cube map yet, so coding agents must not try. A cube map can be a background: [Assets](assets.md) loads one with `assets.loadCubemap`.
11
+ > Roadmap step 0.1, first released in null3D 0.1.0. The API is experimental, so it can still change between versions. Materials do not sample cube maps. A cube map can be a background: [Assets](assets.md) loads one with `assets.loadCubemap`.
12
12
 
13
13
  ```mermaid
14
14
  flowchart LR
@@ -58,7 +58,7 @@ Every call that makes a texture takes these options:
58
58
  | Option | Values | Default |
59
59
  | --- | --- | --- |
60
60
  | `colorSpace` | `'srgb'` for color maps, `'linear'` for data maps | `'srgb'` for images, `'linear'` for data |
61
- | `wrap` | `'clamp'`, `'repeat'` or `'mirror'`, or `[u, v]` for each axis | `'clamp'`, as in three.js |
61
+ | `wrap` | `'clamp'`, `'repeat'` or `'mirror'`, or `[u, v]` for each axis | `'clamp'` |
62
62
  | `filter` | `'linear'`, or `'nearest'` for sharp texels such as pixel art | `'linear'` |
63
63
  | `mipmaps` | True to make mip levels on the GPU | True for images, false for data |
64
64
  | `anisotropy` | A whole number from 1 to 16 | 1, which is off |
@@ -66,8 +66,8 @@ Every call that makes a texture takes these options:
66
66
 
67
67
  `loadTexture` also takes `flipY` and `premultipliedAlpha`, which say how the image decodes:
68
68
 
69
- - `flipY: true`, the default, puts the image's top row at v = 1, the top of a plane, as three.js's `TextureLoader` does. glTF textures use `flipY: false`.
70
- - `premultipliedAlpha: true` stores each color multiplied by its alpha, as three.js's `premultiplyAlpha` does. It is false by default.
69
+ - `flipY: true`, the default, puts the image's top row at v = 1, the top of a plane. glTF textures use `flipY: false`.
70
+ - `premultipliedAlpha: true` stores each color multiplied by its alpha. It is false by default.
71
71
 
72
72
  An option that the engine does not know, such as `wrap: 'tile'` or `anisotropy: 32`, throws [E1208](../errors/E1208.md).
73
73
 
@@ -99,7 +99,7 @@ A KTX2 file takes the texture options above, with these differences:
99
99
 
100
100
  - The texture has the mip levels that the file holds. The GPU cannot make mip levels of compressed texels, so encode the file with them, as `basisu -mipmap` and `toktx --genmipmap` do. `mipmaps: false` keeps level 0 alone.
101
101
  - The color space comes from the file, which `basisu` writes as sRGB unless you give it `-linear`. The `colorSpace` option overrides it. HDR data is always linear, so in development builds `colorSpace: 'srgb'` throws E1208 for it.
102
- - The file's first row goes to v = 0, the bottom of a plane, as with three.js's `KTX2Loader`. glTF models expect that order. For a plane, encode the file flipped, as `basisu -y_flip` does. Compressed rows cannot turn over. So in development builds, `flipY: true` throws E1208, and so does `premultipliedAlpha: true`. A production build ignores both.
102
+ - The file's first row goes to v = 0, the bottom of a plane. glTF models expect that order. For a plane, encode the file flipped, as `basisu -y_flip` does. Compressed rows cannot turn over. So in development builds, `flipY: true` throws E1208, and so does `premultipliedAlpha: true`. A production build ignores both.
103
103
  - A KTX2 file of several layers makes a texture of several layers. Cube maps, 3D textures and KTX2 files of other formats throw [E1412](../errors/E1412.md).
104
104
  - A file whose sides pass `textures.maxSize` throws E1412 before the transcoder runs. So do files of more than 256 layers or more mip levels than the size has. A file of more than 256 MiB of texels in the device's format throws it too.
105
105
  - `texture.update` throws E1208 on a texture from a KTX2 file. Load the file again instead.
@@ -108,7 +108,7 @@ The first KTX2 file starts the transcoder: a worker that runs the official build
108
108
 
109
109
  ## Images
110
110
 
111
- `textures.fromImageBitmap` uploads an image as it is: the image's first row goes to v = 0, the bottom of a plane. To make a texture that stands upright, as three.js shows it, decode the image with its rows flipped. `assets.loadImageBitmap` does so by default. `createImageBitmap` does so with `imageOrientation: 'flipY'`:
111
+ `textures.fromImageBitmap` uploads an image as it is: the image's first row goes to v = 0, the bottom of a plane. To make a texture that stands upright on a plane, decode the image with its rows flipped. `assets.loadImageBitmap` does so by default. `createImageBitmap` does so with `imageOrientation: 'flipY'`:
112
112
 
113
113
  ```ts
114
114
  const canvas = new OffscreenCanvas(256, 64);
@@ -186,11 +186,11 @@ The video element's own settings, such as its file format and its cross-origin r
186
186
 
187
187
  A texture with `depth` above 1 holds that many layers, up to 256, one after another in `data`. Its layers are a texture array of their own. Materials read its first layer.
188
188
 
189
- Data of the wrong length or type for the size and format throws E1208. Data textures have no mip levels unless `mipmaps` is true, as in three.js's `DataTexture`.
189
+ Data of the wrong length or type for the size and format throws E1208. Data textures have no mip levels unless `mipmaps` is true.
190
190
 
191
191
  ## Textures of render passes
192
192
 
193
- `textures.fromPass(pass)` returns the texture that a scene pass of `render.addPass` draws into (0.2). Materials and sprites take it as a map, as three.js's render target textures are.
193
+ `textures.fromPass(pass)` returns the texture that a scene pass of `render.addPass` draws into. Materials and sprites take it as a map.
194
194
 
195
195
  ```ts
196
196
  const map = render.addPass({ kind: 'scene', camera: mapCamera, writes: 'minimap', size: [256, 256] });
@@ -245,7 +245,7 @@ Mip levels are smaller copies of a texture. The GPU reads them where the texture
245
245
 
246
246
  Each texture has its own sampler settings, from its options:
247
247
 
248
- - What texture coordinates outside 0 to 1 read along each axis: the texel at the edge, a repeat of the texture, or a mirrored repeat. By default the edge texel repeats outward, as in three.js.
248
+ - What texture coordinates outside 0 to 1 read along each axis: the texel at the edge, a repeat of the texture, or a mirrored repeat. By default the edge texel repeats outward.
249
249
  - The filter of magnified texels, of minified texels and between mip levels: linear or nearest. It is linear by default.
250
250
  - Anisotropic filtering, which keeps a texture sharp on a surface seen at a slant, such as a floor. It reaches at most 16 samples, or the quality preset's cap (`maxAnisotropy`) when that is lower. A nearest filter turns it off. It is off by default.
251
251
 
package/docs/api/ui.md CHANGED
@@ -78,7 +78,7 @@ The engine holds 4,096 labels at once by default, and 256 labels that are planes
78
78
 
79
79
  `engine.labels.bind(id, element)` binds an element to the label with the same id. The sketch can track the label before or after the bind. The element stays hidden until the label's first frame reaches the screen. The code that moves the elements downloads with the first bind, so a page without labels never downloads it.
80
80
 
81
- The engine places the element's center over the label, through its CSS `transform`. It also sets the element's `position` to `absolute` at the top left of its container. So put the elements in a container that covers the canvas exactly, as the example above does. Give the container `pointer-events: none`, so the canvas still gets the pointer.
81
+ The engine places the element's center over the label, through its CSS `transform`. It also sets the element's `position` to `absolute` at the top left of its container. So put the elements in a container that covers the canvas exactly, as the example above does. Give the container `pointer-events: none`, so the canvas still gets the pointer. The elements of labels flat on the screen stack in the order of the page, whatever their distance to the camera. The engine owns the element's `transform`. To anchor another point of the element on the label, offset the content inside the element with CSS.
82
82
 
83
83
  The engine sets `visibility: hidden` on the element while:
84
84
 
@@ -101,14 +101,14 @@ ui.trackLabel(panel, 'card', { transform: 'world', offset: [0, 1.4, 0] });
101
101
  ui.trackLabel(crown, 'title', { transform: 'billboard', rotation: 0.1 });
102
102
  ```
103
103
 
104
- The scene's units are the element's CSS pixels for these labels, as they are for three.js's `CSS3DRenderer`. An element 160 pixels wide is 160 units wide, so the scene around it needs units of the same size.
104
+ The scene's units are the element's CSS pixels for these labels. An element 160 pixels wide is 160 units wide, so the scene around it needs units of the same size.
105
105
 
106
106
  The browser scales the element with the perspective, and keeps its text sharp. The element covers about `w × focal ÷ d` pixels of the canvas, where `w` is its width and `d` its distance. The focal length is half the canvas height in pixels, divided by the tangent of half the vertical field of view.
107
107
 
108
108
  What the page does for such a label:
109
109
 
110
110
  - The engine moves the element into a container of its own, inside the element's parent. The container covers its parent and holds the camera's view. Put the element in a container that covers the canvas, as for any label.
111
- - The engine sets the element's `user-select` to `none`, and leaves the pointer to your CSS. Give the element `pointer-events: auto` when it takes clicks, as three.js's `CSS3DRenderer` does. Keep its `transform-origin` at its center.
111
+ - The engine sets the element's `user-select` to `none`, and leaves the pointer to your CSS. Give the element `pointer-events: auto` when it takes clicks. Keep its `transform-origin` at its center.
112
112
  - The engine writes the element's `transform` only when its matrix changes. Its size, its text and its style stay yours.
113
113
  - The element hides with `visibility: hidden` for the reasons listed above. The engine tests the label's anchor, so the whole element hides at once.
114
114
 
@@ -120,18 +120,6 @@ So the sketch places every label with the camera of each frame, as part of the f
120
120
 
121
121
  The page writes a screen label's element only when the label moved by half a CSS pixel or more, or when it shows or hides. It writes a 3D element's transform only when its matrix changed. It reads every label before it writes any style, so the browser runs no layout between them. While no element is bound, the labels cost the page nothing.
122
122
 
123
- ## Compared with three.js
124
-
125
- Labels take the place of three.js's `CSS2DRenderer` and `CSS2DObject`, of `CSS3DRenderer` with `CSS3DObject` and `CSS3DSprite`, and of drei's `<Html>`.
126
-
127
- - An element's center sits where `CSS2DRenderer` puts a `CSS2DObject`'s center by default, to within a thousandth of a pixel.
128
- - A label with `transform: 'world'` takes a `CSS3DObject`'s matrix, and `'billboard'` takes a `CSS3DSprite`'s, with its `rotation2D` as `rotation`.
129
- - The offset works like a `CSS2DObject`'s or `CSS3DObject`'s position under its parent.
130
- - `CSS2DRenderer` and `CSS3DRenderer` hide an element with `display: none`; null3D uses `visibility: hidden`, which keeps the page's layout as it is.
131
- - null3D does not set `z-index` from the distance to the camera. Elements stack in the order of the page. `CSS2DObject`'s `center` has no counterpart: move the content inside the element with CSS.
132
- - null3D hides a plane whose anchor lies behind the camera, or outside the near and far planes. three.js's `CSS3DRenderer` draws such an element anyway.
133
- - `CSS3DRenderer` writes every element's style in every frame. null3D writes an element's transform only when its matrix changes.
134
-
135
123
  ## Related pages
136
124
 
137
125
  - [UI, HTML overlays and labels](../guides/ui-overlays.md): HTML UI around the canvas, and labels in a full app.