threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -1,15 +1,15 @@
1
1
  # The whole picture in plain three.js: signals in, picture out
2
2
 
3
- **In this recipe**: the `picture/` folder (0), setup (1), signals (2), the hook (3), rules for a bigger game (3b), wiring and who wrote a value (3c), the library (3d), shared values (3e),
4
- picture parts: code from different sources in one game (3f), a flat look (4), pixel art, pixel-perfect camera and sprites (4b), what the engine still does (5), checking (6).
3
+ > **Covers:** the whole picture as plain three.js in `picture/`: signals in, picture out, parts, a flat look, pixel art.
4
+ > **Use when:** writing or changing how the game looks.
5
+ > **Shortest:** the generated `picture/` folder (§0).
6
+ > **Sections:** 0 The picture/ folder · 1 Setup the engine's · 2 The signals engine.uniforms · 3 The hook engine.onRender · 3b Rules that keep · 3c Wiring picture/ parts · 3d Save to the · 3e Several parts change · 3f Picture parts three.js · 4 A flat illustration · 4b Pixel art low-resolution · 5 What the engine · 6 Check the picture
5
7
 
6
- Any picture (flat illustration, toon, painterly, realistic) can be written as plain three.js in one folder of the game, the picture code: its own
7
- lights, materials, fog, sky colors and post passes. The engine hands it signals (time of day, weather) and keeps doing the engineering
8
- (streaming, shadows, saves, tests); it writes none of the picture's values. Working example: `examples/plain-picture/` (page `/plain-picture.html`,
9
- a night street in a flat-illustration look; `picture/` is the whole picture). Every value has one writer, a line in your code, so
10
- "why is this wall black" has one place to look.
8
+ Any picture (flat, toon, painterly, realistic) can be plain three.js in one folder of the game: its own lights, materials, fog, sky colors and post
9
+ passes. The engine hands it signals (time of day, weather), keeps the engineering (streaming, shadows, saves, tests) and writes none of its values.
10
+ Working example: `examples/plain-picture/` (page `/plain-picture.html`). Every value has one writer, a line in your code.
11
11
 
12
- ## 0. The `picture/` folder
12
+ ## 0. The `picture/` folder: where all picture code goes
13
13
  `threedog new-game` generates it, with a gray start; it is yours to change or delete. One file per job, so the picture never piles up in one place:
14
14
  ```
15
15
  picture/
@@ -19,7 +19,7 @@ picture/
19
19
  materials.js materials by name; other code asks for picture.materials.wall and never builds its own
20
20
  sky.js add when the game has its own sky or fog
21
21
  post.js add when the game has post effects
22
- shaders/*.glsl your shader code; saving one hot-reloads it
22
+ shaders/ your shader code: TSL .js on WebGPU (the default), .glsl on WebGL (a saved .glsl hot-reloads)
23
23
  areas/<name>.js a large game's overrides for one area (a cave, an interior): only what differs
24
24
  ```
25
25
  To add a part, write a file that returns `{ update(signals) }` and call it from `index.js`, handing it the module's `ctx` so what it adds leaves with the picture:
@@ -36,18 +36,18 @@ export function createPost(engine, ctx) {
36
36
  return { update() {} };
37
37
  }
38
38
  ```
39
- Gameplay and level code use material names and signals only, so a picture change touches `picture/` alone.
39
+ Gameplay and level code use material names and signals only.
40
40
 
41
41
  ## 1. Setup: the engine's placeholder lights off
42
42
  ```js
43
- const engine = createEngine({ canvas, lights: false }); // no placeholder sun / hemisphere; this is the WebGL form: a new game also has `import 'threedog/tsl'` and `renderer: 'webgpu'`
43
+ const engine = createEngine({ canvas, lights: false }); // no placeholder sun / hemisphere; this is the WebGL form: a new game also has `import 'threedog/tsl'` and `renderer: 'webgpu'`
44
44
  engine.use(calendar({ time: '22:00' }),
45
- sky(), // computes the signals and draws the dome; writes no light or fog
45
+ sky(), // computes the signals and draws the dome; writes no light or fog
46
46
  weather({ types: { clear: {}, rain: { rain: 1, cloud: 0.8 } } }));
47
- engine.renderer.toneMapping = THREE.AgXToneMapping; // three.js's default (none) stands until you pick one
48
- if (engine.sky) engine.sky.dome.visible = false; // when you draw your own sky (a gradient sphere, a skybox)
47
+ engine.renderer.toneMapping = THREE.AgXToneMapping; // three.js's default (none) stands until you pick one
48
+ if (engine.sky) engine.sky.dome.visible = false; // when you draw your own sky (a gradient sphere, a skybox)
49
49
  ```
50
- Without `calendar` and `sky()` there is no day and night: `uDaylight` stays 1 and `uSunDir` straight up. With only `calendar` the daylight and time signals still move, but the sun stays straight up; keep `calendar` + `sky` for a full day cycle even when you draw everything yourself.
50
+ Without `calendar` and `sky()` `uDaylight` stays 1 and `uSunDir` straight up; with only `calendar` the daylight moves but the sun stays up. Keep both for a day cycle, even when you draw everything yourself.
51
51
 
52
52
  ## 2. The signals (`engine.uniforms`, each `{ value }`)
53
53
  | Signal | Range | From |
@@ -64,25 +64,26 @@ Without `calendar` and `sky()` there is no day and night: `uDaylight` stays 1 an
64
64
  | `uFoliageTint`, `uGroundTint`, `uGroundCover` | season tints, snow cover | sky + calendar |
65
65
  | `uSkyTop`, `uSkyHorizon` | the engine dome's colors (its neutral keyframes unless the game sets them) | sky |
66
66
 
67
- Read `.value` in JS, or share the object in a shader (`uniforms: { uDaylight: engine.uniforms.uDaylight }`): one object, no copy. The sky
68
- colors are the engine dome's picture, not physics: a styled game keeps its own palette and mixes them in only if it wants. Gameplay that should change the picture (a cutscene dims the world, a status effect tints it) goes through a signal of your
69
- own, read by the picture code, so the picture still has one writer.
67
+ Read `.value` in JS, or share the object in a shader (`uniforms: { uDaylight: engine.uniforms.uDaylight }`). The sky colors are the engine dome's
68
+ picture, not physics: a styled game mixes them in only if it wants. Gameplay that changes the picture (a cutscene dims the world) goes through a signal
69
+ of your own that the picture code reads.
70
+
71
+ A sun on a path of your own: `engine.autoView.manual('sunDir')` once, then write `engine.uniforms.uSunDir.value` in the picture's `onRender` before the lights read it; the dome's sun follows.
70
72
 
71
73
  Written every frame: `uSkyTop` and `uSkyHorizon` take `engine.sky.top` / `engine.sky.horizon`, `uDaylight` and `uTimeOfDay` take a `daylight` / `timeOfDay` measure; a direct write is lost and warns once (`signal-overwritten`). `uSunDir` (the same vector as `engine.sky.sunDir`) and `camera.aspect` stay as written: `engine.autoView.manual('sunDir', false)` gives one back.
72
74
 
73
75
  ## 3. The hook: `engine.onRender`, not `onFrame`
74
76
  ```js fragment
75
- const sun = new THREE.DirectionalLight(0xffffff, 2), hemi = new THREE.HemisphereLight(); // made once in picture/lights.js
77
+ const sun = new THREE.DirectionalLight(0xffffff, 2), hemi = new THREE.HemisphereLight(); // made once in picture/lights.js
76
78
  engine.onRender(() => {
77
79
  const day = engine.uniforms.uDaylight.value, rain = engine.uniforms.uRain.value;
78
80
  sun.position.copy(engine.uniforms.uSunDir.value).multiplyScalar(100);
79
81
  sun.intensity = 2.2 * day * (1 - rain * 0.6);
80
- hemi.color.copy(NIGHT.sky).lerp(DAY.sky, day); // your palette, your rule
81
- for (const m of walls) m.emissiveIntensity = 0.2 * (1 - day); // flat look: the wall keeps its own color at night
82
+ hemi.color.copy(NIGHT.sky).lerp(DAY.sky, day); // your palette, your rule
83
+ for (const m of walls) m.emissiveIntensity = 0.2 * (1 - day); // flat look: the wall keeps its own color at night
82
84
  });
83
85
  ```
84
- `onRender` (default `'before'`) runs once per drawn frame after every module updated, so it reads this frame's signals. `onFrame` runs before
85
- the modules' frame hooks: it would read last frame's values (and noon on the very first frame). Picture code uses `onRender` only.
86
+ `onRender` (default `'before'`) runs once per drawn frame after every module updated; `onFrame` runs before them and would read last frame's values (noon on the first frame).
86
87
 
87
88
  ## 3b. Rules that keep the folder working in a bigger game
88
89
  - **One object's state goes through a name `picture/` exports.** Signals are global, but one street lamp shot out or one flickering sign is not. Gameplay calls
@@ -93,7 +94,6 @@ the modules' frame hooks: it would read last frame's values (and noon on the ver
93
94
  // gameplay
94
95
  picture.lamp(hit.id).off();
95
96
  ```
96
- The engine has no such layer: the names are the game's.
97
97
  - **`picture/` shaders follow the renderer.** A new game is on WebGPU and writes TSL (recipe 56); `ShaderMaterial` and `onBeforeCompile` do not run there, and a GLSL material
98
98
  on WebGPU stops at start and names itself. A `--webgl` game writes GLSL (recipe 43).
99
99
  - **The picture reads the quality tier.** The engine cannot hold your code to it, so read `engine.tier` (`'low'` | `'high'`) for what costs: shadow map size,
@@ -102,26 +102,24 @@ the modules' frame hooks: it would read last frame's values (and noon on the ver
102
102
  ## 3c. Wiring `picture/` parts
103
103
  - **One `engine.onRender`, in `picture/index.js`.** It calls each part's `update(signals)` and holds no values. A part never adds its own hook: two hooks hide the order.
104
104
  - **Order is the call order.** Put what others read first (`palette`, a part that computes this frame's mood from signals), then lights, sky, materials, post.
105
- - **Who may write what:** one part owns each value; `lights.js` the lights, `sky.js` the fog and background, `materials.js` the materials, `post.js` tone and exposure.
106
- Another part that needs to change that value does not write it: it changes a signal of its own and the owner reads it.
107
- - **Several steps in one function are fine** (`fog.color.copy(a); fog.color.lerp(b, t);`), and so is one state of the game writing a value that another state wrote in earlier frames.
105
+ - **Who may write what:** one part owns each value (`lights.js` the lights, `sky.js` fog and background, `materials.js` the materials, `post.js` tone and exposure);
106
+ another part changes a signal of its own that the owner reads.
107
+ - **Several steps in one function are fine** (`fog.color.copy(a); fog.color.lerp(b, t);`), and so is one game state taking over a value another state wrote earlier.
108
108
 
109
109
  Under the dev server (`npm run dev`, `threedog snap`) the engine records which line last changed each value:
110
110
  ```js fragment
111
- engine.describe('picture').picture.writers // the state at a glance, every value at once: { values: { 'fog.far': { at: 'picture/sky.js:12', framesAgo: 3 }, 'light:sun.intensity': ... }, conflicts: [...] }
112
- engine.explain({ value: 'fog.far' }) // who wrote it, its last writers with frames (detail.history), a fight if one was seen, and the fix
113
- engine.debug.watch('boss.hp', boss, 'hp') // any other value, by a name you choose; a Color, Vector or rotation is watched inside
111
+ engine.describe('picture').picture.writers // the state at a glance, every value at once: { values: { 'fog.far': { at: 'picture/sky.js:12', framesAgo: 3 }, 'light:sun.intensity': ... }, conflicts: [...] }
112
+ engine.explain({ value: 'fog.far' }) // who wrote it, its last writers with frames (detail.history), a fight if one was seen, and the fix
113
+ engine.debug.watch('boss.hp', boss, 'hp') // any other value, by a name you choose; a Color, Vector or rotation is watched inside
114
114
  ```
115
115
  Names are `renderer.toneMapping`, `renderer.toneMappingExposure`, `scene.fog`, `fog.near | far | density | color`, `scene.environment`, `scene.environmentIntensity`,
116
116
  `scene.background`, `scene.backgroundIntensity`, `light:<name>.intensity | color | groundColor | position`, `material:<name>.color | emissive | opacity | emissiveIntensity`,
117
117
  every id in `describe().owned` (when the engine yields, the warning and `writtenAt` name the line that took the value; an id with no plain property, like `view.pixelRatio`, answers `not tracked`), and any shared point's name.
118
- `framesAgo` is how old the answer is: a value written every frame is looked at about twice a second, and `writtenSince: true` means it moved after that picture. Anything else,
119
- a value set before it entered the scene, a console write, a bundled build (`threedog shot`, `npm test`), answers `not tracked` with the reason. Nothing is ever blocked.
120
- Only watched values are seen, and a write that leaves a value unchanged is not, so seeing no conflict is not proof there is none.
118
+ `framesAgo` is how old the answer is (a value written every frame is sampled about twice a second; `writtenSince: true`: it moved since). A value set before it entered the scene,
119
+ a console write or a bundled build (`threedog shot`, `npm test`) answers `not tracked` with the reason. Nothing is blocked, and an unchanged write is not seen, so no conflict is not proof of none.
121
120
 
122
121
  **A conflict hint** is one line: `fog.far: two writers in one frame, picture/sky.js:14 and picture/rival.js:3; the last write stands`, and `engine.explain({ value: 'fog.far' })` has the history and the fix.
123
- Two writers that never share a frame but keep overwriting each other read `taking turns across frames`; one state handing a value to another does not count. One line's work never reaches the screen. Decide which part owns the value, delete the other write, or turn it into a signal or a shared value the owner reads. It warns once per value.
124
- Both writes going through a shared helper count as one place, the helper's line: the warning cannot see past it.
122
+ Two writers that never share a frame but keep overwriting each other read `taking turns across frames` (one state handing a value to another does not count). Fix: one part owns the value; delete the other write or make it a signal or shared value the owner reads. Warns once per value; writes through a shared helper count as the helper's line.
125
123
 
126
124
  ## 3d. Save to the library, pull it out
127
125
  A part of the picture that worked can go into your library (outside the repo, `~/.threedog/library`) and come back in the next game:
@@ -131,8 +129,7 @@ threedog lib add picture/shaders/ink.glsl --kind picture # a .glsl fil
131
129
  threedog lib list flat # next game: look before writing your own
132
130
  threedog lib pull flat-materials # lands in picture/ (a .glsl lands in picture/shaders/)
133
131
  ```
134
- A picture entry is **one plain three.js file that exports a function**, so it has to stand alone. `lib add` refuses a file that imports its siblings
135
- (`./palette.js`) and names them; the entry would arrive as a half. Take the numbers as parameters instead:
132
+ A picture entry is **one plain three.js file that exports a function**: `lib add` refuses a file that imports its siblings (`./palette.js`) and names them. Take the numbers as parameters:
136
133
  ```js fragment
137
134
  /** Flat materials by name: a flat color plus an emissive copy of it that rises at night.
138
135
  * @param {object} THREE three.js @param {Record<string, number>} palette name → hex @param {number} nightGlow emissive at full night */
@@ -145,7 +142,7 @@ export function flatMaterials(THREE, palette, nightGlow = 0.2) {
145
142
  } };
146
143
  }
147
144
  ```
148
- A day-and-night light group is the same shape: `dayNightLights(THREE, scene, { day, night })`. The copy in your game is yours: pull, then adapt it to that game's picture.
145
+ The pulled copy is yours to adapt.
149
146
 
150
147
  ## 3e. Several parts change one picture value
151
148
  A sunset and a cutscene both dim the sun. If each writes the light, the second one's end brings back a value that is already wrong. Make the value a shared point
@@ -158,15 +155,15 @@ engine.onRender(() => { sun.intensity = 2.2 * engine.uniforms.uDaylight.value *
158
155
 
159
156
  // anywhere else: nobody touches the light
160
157
  const dusk = engine.mod('sun.level', { owner: 'sunset', mul: 0.6 });
161
- const hold = engine.mod('sun.level', { owner: 'cutscene', mul: 0.3, for: 4 }); // 0.18 while both are on
162
- dusk.remove(); // they end in any order
158
+ const hold = engine.mod('sun.level', { owner: 'cutscene', mul: 0.3, for: 4 }); // 0.18 while both are on
159
+ dusk.remove(); // they end in any order
163
160
  ```
164
- An amount that moves takes one entry and changes it: `const wet = ctx.mod('sun.level', { mul: 1 });` once in the install, then `wet.change(1 - 0.5 * rain)` each frame. Calling `ctx.mod` every frame would pile up entries. In a module use `ctx.mod`, not `engine.mod`: the change then goes with the module.
161
+ An amount that moves takes one entry and changes it: `const wet = ctx.mod('sun.level', { mul: 1 });` once in the install, then `wet.change(1 - 0.5 * rain)` each frame (a `ctx.mod` per frame piles up entries). In a module use `ctx.mod`: it goes with the module.
165
162
  `describe().shared` shows who holds it and why it reads what it reads. A value only one part writes needs none of this: write the light.
166
163
 
167
164
  ## 3f. Picture parts: three.js code from different sources in one game
168
- The `picture/` folder of section 0 is one part holding the whole look, with slot `picture`. Use smaller parts when code has to live beside code you did not write: an entry from the library,
169
- another agent's sky, a rain from an old game. A part is an ordinary module with `type: 'picture'`. There is no new layer and no new way to write a picture: inside it is plain three.js.
165
+ The `picture/` folder of section 0 is one part holding the whole look, with slot `picture`. Use smaller parts when code lives beside code you did not write (a library entry,
166
+ another agent's sky). A part is an ordinary module with `type: 'picture'`, plain three.js inside.
170
167
  ```js fragment
171
168
  // picture/harbor-fog.js
172
169
  import * as THREE from 'three';
@@ -174,20 +171,19 @@ import * as THREE from 'three';
174
171
  export const harborFog = ({ near = 10, far = 200 } = {}) => ({
175
172
  name: 'harborFog', type: 'picture', provides: ['fog'],
176
173
  install(e, ctx) {
177
- ctx.borrow(e.scene, { fog: new THREE.Fog(0x667788, near, far) }); // given back when the part goes
174
+ ctx.borrow(e.scene, { fog: new THREE.Fog(0x667788, near, far) }); // given back when the part goes
178
175
  const flare = new THREE.PointLight(0xffaa66, 2, 30);
179
176
  e.scene.add(flare);
180
- ctx.track(e.onRender(() => { // reads signals, writes three.js
177
+ ctx.track(e.onRender(() => { // reads signals, writes three.js
181
178
  e.scene.fog.far = far * (1 - 0.6 * e.uniforms.uRain.value);
182
179
  flare.intensity = 2 * (1 - e.uniforms.uDaylight.value);
183
180
  }));
184
- ctx.track({ remove() { e.scene.remove(flare); flare.dispose(); } }); // what it added goes with it
181
+ ctx.track({ remove() { e.scene.remove(flare); flare.dispose(); } }); // what it added goes with it
185
182
  },
186
183
  });
187
184
  ```
188
- `ctx.borrow(obj, values)` writes properties on something the part does not own (`scene.fog`, `renderer.toneMapping`, the engine dome's `visible`) and restores them when the part goes or is disabled after an error, or on the handle's `remove()`. A value goes back only if it is still what the borrow wrote, so a fog the game set meanwhile stands. One property has one holder: a second borrow of it is refused, so a value several parts want goes on a shared point (`engine.mod`).
189
- `engine.use(harborFog())` installs it, `engine.unuse('harborFog')` removes it, and `engine.use(otherFog(), { replaces: 'fog' })` swaps it. A part may use its own hooks: the single
190
- `engine.onRender` of 3c is how one author keeps one folder in order, and two parts from two sources have no shared wiring file.
185
+ `ctx.borrow(obj, values)` writes properties on something the part does not own (`scene.fog`, `renderer.toneMapping`, the engine dome's `visible`) and restores them when the part goes, is disabled after an error, or on the handle's `remove()`. A value goes back only while this borrow holds it and it is what the borrow wrote, so a fog the game set meanwhile stands. One property has one holder (a second borrow is refused): a value several parts want goes on a shared point (`engine.mod`).
186
+ `engine.use(harborFog())` installs it, `engine.unuse('harborFog')` removes it, `engine.use(otherFog(), { replaces: 'fog' })` swaps it. A part may use its own hooks (the single `onRender` of 3c is for one author's folder).
191
187
 
192
188
  **A value is one of three kinds, and each has one rule:**
193
189
  | Kind | Example | Rule | On a collision |
@@ -215,17 +211,17 @@ A part that needs another one says `requires: ['sun']`. A shared value a part de
215
211
  - `picture-leftover`: a part went and left lights, objects, post effects, frame callbacks, or the fog, environment or background it wrote. It names each with its line; `picture.writers.leftovers` lists them.
216
212
  `ctx.track` only removes what it was handed, so anything else needs a `remove()` or the part's `dispose()`.
217
213
 
218
- **What this cannot catch:** code that never runs, a write made before the holder took its slot, a write of the same value, a thing added under another object rather than the scene root, and a main light
219
- not named `'sun'`. Nothing here sees that a warm lamp clashes with a cold sea: that takes a screenshot and an eye (section 6).
214
+ **What this cannot catch:** code that never runs, a write before the holder took its slot, a write of the same value, a thing added under another object than the scene root, a main light
215
+ not named `'sun'`, and taste (a warm lamp against a cold sea): that takes a screenshot (section 6).
220
216
 
221
217
  **When not to bother:** one author, one game, a `picture/` folder that works. Turn a file into a part when another source arrives, not before.
222
218
 
223
219
  **Switching the whole look at run time.** Keep each look as a module holding `picture` and whatever other slots it writes (`provides: ['picture', 'tone', 'fog', 'sun']`), then:
224
220
  ```js fragment
225
- engine.use(duskPicture(), { replaces: 'picture' }); // the old look's lights, hooks, post effects and borrowed values go first
221
+ engine.use(duskPicture(), { replaces: 'picture' }); // the old look's lights, hooks, post effects and borrowed values go first
226
222
  for (const m of myMeshes) m.material = engine.picture.materials[m.userData.surface];
227
223
  ```
228
- The old materials are disposed, and the engine cannot know which of your meshes hold them: **a mesh holding an old look's material must take the new one**, by name as above. Everything the look added itself leaves with it, as long as it went through `ctx`.
224
+ The old materials are disposed and the engine cannot know which of your meshes hold them: **a mesh holding an old look's material must take the new one**, by name as above. What the look added through `ctx` leaves with it.
229
225
 
230
226
  ## 4. A flat illustration (one way among many)
231
227
  Light alone turns a warm wall under a cool night fill into mud. An illustrator keeps each surface its own color and only shifts it:
@@ -241,9 +237,9 @@ environment map comes out too dark on faces away from the sun: raise the ambient
241
237
 
242
238
  ## 4b. Pixel art: low-resolution rendering with sharp scaling
243
239
  Pixel art means drawing fewer pixels and then keeping every edge hard when they are enlarged. One engine option does the screen side:
244
- - **`createEngine({ pixelSize: k })`, or `engine.setPixelSize(k)` during play.** One art pixel is k real screen pixels, every one the same width at any display scale, and it stays so through a page zoom or a move to another display. The canvas gets `image-rendering: pixelated`, and `antialias` defaults to off (it blends the edges you want hard, and can only be set at creation: passing `antialias: true` warns). A whole number of art pixels rarely fills the canvas, so the last few real pixels at the right and bottom, fewer than k, stay empty and show the page behind; the box the page laid out does not change. `engine.setPixelSize(null)` turns it off.
245
- - **Nothing else changes the size while it is on.** Adaptive resolution stops, and the quality tier leaves the ratio alone. `engine.setPixelRatio` throws `pixel-conflict`, and so does `createEngine` given `pixelRatio` or `adaptiveResolution: true` as well. `engine.photo.take()` keeps the art pixels: the picture is the drawing buffer's size, whatever its `scale`. A direct `renderer.setPixelRatio` still wins, as everywhere in three.js: the engine stops fitting the canvas (recipe 52).
246
- - **The menu follows.** While it is on the settings menu has no render scale or adaptive row, and no preset or stored value moves the ratio. The anti-aliasing row would still blend edges: leave it out where the game lists its tabs, `settings({ sections: [{ id: 'graphics', omit: ['antialias'] }, 'audio', 'controls', 'language', 'saves'] })`: an omitted row stays your value, and no preset or stored value moves it.
240
+ - **`createEngine({ pixelSize: k })`, or `engine.setPixelSize(k)` during play.** One art pixel is k real screen pixels at any display scale, through a page zoom or a move to another display. The canvas gets `image-rendering: pixelated`, and `antialias` defaults to off (it blends hard edges; creation-time only: `antialias: true` warns). Fewer than k real pixels at the right and bottom stay empty and show the page behind. `engine.setPixelSize(null)` turns it off.
241
+ - **Nothing else changes the size while it is on.** Adaptive resolution stops; the quality tier leaves the ratio alone. `engine.setPixelRatio` throws `pixel-conflict`, and so does `createEngine` given `pixelRatio` or `adaptiveResolution: true` as well. `engine.photo.take()` keeps the art pixels (the drawing buffer's size, whatever its `scale`). A direct `renderer.setPixelRatio` still wins, as in three.js: the engine stops fitting the canvas (recipe 52).
242
+ - **The menu follows.** The settings menu has no render scale or adaptive row, and no preset or stored value moves the ratio. Leave out the anti-aliasing row: `settings({ sections: [{ id: 'graphics', omit: ['antialias'] }, 'audio', 'controls', 'language', 'saves'] })` (an omitted row keeps your value).
247
243
  - **Sample sharply.** `engine.assets.texture(name, { pixelated: true })` sets `NearestFilter` for enlarging and `NearestMipmapNearestFilter` for shrinking. On a texture of
248
244
  your own, set `magFilter` and `minFilter` to `THREE.NearestFilter`.
249
245
  ```js
@@ -257,25 +253,25 @@ resolution. Objects that move by less than an art pixel shimmer; `pixelSnap` and
257
253
  engine.use(followCamera({ projection: 'orthographic', yaw: Math.PI / 4, pitch: 0.6, lockPitch: true, mouseLook: false,
258
254
  pixelSnap: { pixelsPerMeter: 32, bounds: { minX: -20, maxX: 20, minZ: -20, maxZ: 20 } } }));
259
255
  ```
260
- - **`pixelsPerMeter` decides the view height.** The view must show buffer height / `pixelsPerMeter` world units, or the grid and the picture disagree, so `pixelSnap` sets it, also after a resize. `size` with `pixelSnap` throws `pixel-conflict`; on `fixedCamera` every shot says `projection: 'orthographic'` and has no `size`. The wheel does not zoom: `engine.setPixelSize(k)` is the zoom that keeps art pixels whole, and it needs nothing else. If the game writes `camera.zoom` or `orthoSize` itself, a `pixel-conflict` warning says so, rounding stops, and `describe().camera.pixelSnap.agrees` reads `false` until it is put back.
261
- - **`bounds`** is a world rectangle (`minY` and `maxY` are optional, 0 by default). The camera does not show past it. It is projected on the screen's axes and rounded inward, the true position is clamped, and only then rounded, so sliding along a bound stays on whole art pixels. On an axis where the level is smaller than the view, the camera centers. Turning the view changes the screen rectangle: at 45 degrees of yaw it is a box around a diamond, so the view can show the empty corners outside the level. Fill them with something, or keep the yaw near a multiple of 90 degrees.
256
+ - **`pixelsPerMeter` decides the view height.** The view must show buffer height / `pixelsPerMeter` world units, so `pixelSnap` sets it, also after a resize. `size` with `pixelSnap` throws `pixel-conflict`; on `fixedCamera` every shot says `projection: 'orthographic'` and has no `size`. The wheel does not zoom: `engine.setPixelSize(k)` is the zoom that keeps art pixels whole. If the game writes `camera.zoom` or `orthoSize` itself, a `pixel-conflict` warning says so, rounding stops, and `describe().camera.pixelSnap.agrees` reads `false` until it is put back.
257
+ - **`bounds`** is a world rectangle (`minY` and `maxY` are optional, 0 by default). The camera does not show past it. It is projected on the screen's axes and rounded inward; the true position is clamped, then rounded, so sliding along a bound stays on whole art pixels. Where the level is smaller than the view, the camera centers. At 45 degrees of yaw the screen rectangle is a box around a diamond and shows empty corners: fill them, or keep yaw near a multiple of 90 degrees.
262
258
  - **Turns.** The grid is read fresh each frame, so a turn or a new `pixelSize` needs no reset. While the view is turning, nothing can hold still on a grid that turns with it; a `track: true` shot on `fixedCamera` turns all the time.
263
259
  - **A cutscene** holding `engine.takeCamera` is not rounded.
264
- - **The leftover.** `engine.cameraRig.pixelSnap.error` is the last rounding in art pixels on each screen axis. It is there for a game that wants to do something with it, such as sliding the final image for smooth scrolling. The engine does not do that.
260
+ - **The leftover.** `engine.cameraRig.pixelSnap.error` is the last rounding in art pixels on each screen axis, for a game that wants to slide the final image for smooth scrolling (the engine does not).
265
261
 
266
- **The grid on its own.** `threedog/pixel` is math and plain three.js objects, with no look of its own. `engine.cameraRig.pixelSnap.grid` is the camera's grid; `pixelGrid({ camera, pixelsPerMeter })` makes one for a camera of yours. `snap(world)` rounds a point on the screen's axes and keeps its depth, `error(world)` says by how much, `toScreen` and `toWorld` convert, and `axes()` gives right, up and forward. Round a drawn position with these, not by hand: never move what physics or a save reads.
262
+ **The grid on its own.** `threedog/pixel` is math and plain three.js objects, no look of its own. `engine.cameraRig.pixelSnap.grid` is the camera's grid; `pixelGrid({ camera, pixelsPerMeter })` makes one for a camera of yours. `snap(world)` rounds a point on the screen's axes and keeps its depth, `error(world)` says by how much, `toScreen` and `toWorld` convert, and `axes()` gives right, up and forward. Round a drawn position with these, never what physics or a save reads.
267
263
 
268
- **Sprites in a 3D view: `pixelSprite`.** It returns a plain `THREE.Mesh` with your material: a vertical plane that turns around Y with the camera's forward direction. Its height is stretched by `1 / cos(pitch)`, which the tilt of the view takes back, so one texel is one art pixel.
264
+ **Sprites in a 3D view: `pixelSprite`.** It returns a plain `THREE.Mesh` with your material: a vertical plane that turns around Y with the camera's forward direction. Its height is stretched by `1 / cos(pitch)`, which the view's tilt takes back: one texel is one art pixel.
269
265
  ```js fragment
270
266
  import { pixelSprite, spriteFrame } from 'threedog/pixel';
271
267
  const hero = pixelSprite({ grid: engine.cameraRig.pixelSnap.grid, material, width: 16, height: 24, columns: 4, rows: 3, anchor: [0.5, 0], snap: 'followed' });
272
- spriteFrame(hero, 5, true); // frame 5 of the sheet, mirrored
268
+ spriteFrame(hero, 5, true); // frame 5 of the sheet, mirrored
273
269
  ```
274
- - Frames count left to right, top to bottom, and `width` and `height` are one frame in texels. The material is yours: set `alphaTest` for hard edges, and a nearest filter on its texture. The mesh goes in the scene, or is handed to a character as its `model` (recipe 13 section 3c). `mesh.position` stays exact; only the drawn matrix is rounded.
275
- - `snap: 'world'` (the default) rounds the drawn position to the grid: use it for anything that stands or walks on its own. `snap: 'followed'` is for the one object the camera follows: rounding a follower and its camera separately makes them step on different frames, a one-pixel shake, so this one takes the camera's rounding. On anything else it would creep against the ground.
276
- - Standing upright is what keeps a head out of the wall behind it: the whole figure has the depth of its feet, so no shader is needed. A plane tilted toward the camera would lean back through that wall. One case still cuts: a wall not parallel to the sprite, with the feet nearer to it than `(sprite width / 2) * |sin(angle between them)|`. Keep the collision radius above that.
270
+ - Frames count left to right, top to bottom, and `width` and `height` are one frame in texels. The material is yours: `alphaTest` for hard edges, a nearest filter on its texture. The mesh goes in the scene or to a character as its `model` (recipe 13 section 3c). `mesh.position` stays exact; only the drawn matrix is rounded.
271
+ - `snap: 'world'` (the default) rounds the drawn position to the grid: use it for anything that stands or walks on its own. `snap: 'followed'` is for the one object the camera follows (rounding both separately steps them on different frames: a one-pixel shake), so it takes the camera's rounding; on anything else it would creep against the ground.
272
+ - Standing upright keeps a head out of the wall behind it: the whole figure has the depth of its feet, no shader needed (a plane tilted toward the camera would lean back through the wall). One case still cuts: a wall not parallel to the sprite, with the feet nearer to it than `(sprite width / 2) * |sin(angle between them)|`. Keep the collision radius above that.
277
273
 
278
- **Lighting a sprite from its silhouette.** A flat plane lights flat. A normal map made from the sprite's own outline gives it a rounded edge, with no drawing work: the height is the distance from each texel to the nearest transparent one, then blurred, and the normal is its slope. This is one way among many; a hand-painted normal map goes in the same slot.
274
+ **Lighting a sprite from its silhouette.** A flat plane lights flat. A normal map made from the sprite's outline rounds its edge with no drawing work: height is the distance from each texel to the nearest transparent one, blurred; the normal is its slope. A painted one goes in the same slot.
279
275
  ```js fragment
280
276
  // picture/spriteNormals.js
281
277
  import * as THREE from 'three';
@@ -283,11 +279,11 @@ export function silhouetteNormals(image, frameWidth, frameHeight, { strength = 1
283
279
  const W = image.width, H = image.height, ctx = Object.assign(document.createElement('canvas'), { width: W, height: H }).getContext('2d', { willReadFrequently: true });
284
280
  ctx.drawImage(image, 0, 0);
285
281
  const alpha = ctx.getImageData(0, 0, W, H).data, out = new Uint8Array(W * H * 4), w = frameWidth, h = frameHeight;
286
- for (let fy = 0; fy < H; fy += h) for (let fx = 0; fx < W; fx += w) { // each frame alone: neighbouring frames must not change its outline
282
+ for (let fy = 0; fy < H; fy += h) for (let fx = 0; fx < W; fx += w) { // each frame alone: neighbouring frames must not change its outline
287
283
  const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && alpha[((fy + y) * W + fx + x) * 4 + 3] > 127;
288
284
  const d = new Float32Array(w * h), at = (a, x, y) => (x < 0 || y < 0 || x >= w || y >= h ? 0 : a[y * w + x]);
289
285
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) d[y * w + x] = inside(x, y) ? 1e6 : 0;
290
- const pass = (x, y, s) => { // two sweeps of a chamfer distance: plenty for sprite-sized frames
286
+ const pass = (x, y, s) => { // two sweeps of a chamfer distance: plenty for sprite-sized frames
291
287
  const v = Math.min(d[y * w + x], at(d, x - s, y) + 1, at(d, x, y - s) + 1, at(d, x - s, y - s) + 1.414, at(d, x + s, y - s) + 1.414);
292
288
  d[y * w + x] = v;
293
289
  };
@@ -304,20 +300,20 @@ export function silhouetteNormals(image, frameWidth, frameHeight, { strength = 1
304
300
  height = next;
305
301
  }
306
302
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
307
- const dx = (at(height, x + 1, y) - at(height, x - 1, y)) * strength, dy = (at(height, x, y - 1) - at(height, x, y + 1)) * strength; // y: rows run down, a normal's y runs up
308
- const l = Math.hypot(dx, dy, 1), o = ((H - 1 - fy - y) * W + fx + x) * 4; // a DataTexture's first row is the bottom
303
+ const dx = (at(height, x + 1, y) - at(height, x - 1, y)) * strength, dy = (at(height, x, y - 1) - at(height, x, y + 1)) * strength; // y: rows run down, a normal's y runs up
304
+ const l = Math.hypot(dx, dy, 1), o = ((H - 1 - fy - y) * W + fx + x) * 4; // a DataTexture's first row is the bottom
309
305
  out.set([(-dx / l * 0.5 + 0.5) * 255, (-dy / l * 0.5 + 0.5) * 255, (1 / l * 0.5 + 0.5) * 255, 255], o);
310
306
  }
311
307
  }
312
308
  const t = new THREE.DataTexture(out, W, H);
313
- t.magFilter = t.minFilter = THREE.NearestFilter; // hard art pixels, and no mipmaps: they would mix neighbouring frames
309
+ t.magFilter = t.minFilter = THREE.NearestFilter; // hard art pixels, and no mipmaps: they would mix neighbouring frames
314
310
  t.generateMipmaps = false;
315
- t.colorSpace = THREE.NoColorSpace; // numbers, not colours: an sRGB read would bend every normal
311
+ t.colorSpace = THREE.NoColorSpace; // numbers, not colours: an sRGB read would bend every normal
316
312
  t.needsUpdate = true;
317
313
  return t;
318
314
  }
319
315
  ```
320
- Give it to the sprite's material as `normalMap`, on a lit material such as `MeshStandardMaterial`, next to the sheet it was made from. Measured on WebGL and on real WebGPU: a side light brightens the near half about twice as much as the far half. A sprite mirrored with `spriteFrame` lights the right way round with no change, because three.js takes the tangent direction from the UVs. A light straight overhead is the weak case. The plane's own normal is horizontal, so without a normal map the sprite goes black, and with one only its upper half lights. Add an ambient or hemisphere light, or keep the main light in front of the view.
316
+ Give it to the sprite's material as `normalMap`, on a lit material such as `MeshStandardMaterial`, next to the sheet it was made from. Measured on WebGL and WebGPU: a side light brightens the near half about twice as much as the far half. A sprite mirrored with `spriteFrame` lights the right way round (three.js takes the tangent from the UVs). A light straight overhead is the weak case. The plane's normal is horizontal, so without a normal map the sprite goes black, and with one only its upper half lights: add an ambient or hemisphere light, or keep the main light in front of the view.
321
317
 
322
318
  ## 5. What the engine still does with all of this off
323
319
  - `scene.background` starts as a neutral gray: write your own color or sky.
@@ -326,9 +322,6 @@ Give it to the sprite's material as `normalMap`, on a lit material such as `Mesh
326
322
  - The page-wide changes to three.js are listed in `describe().threePatches` (`THREE.md`).
327
323
 
328
324
  ## 6. Check the picture
329
- `threedog shot <page> --time 22:00` (and `--weather rain`): the picture numbers and hints measure your lights and glowing materials as they
330
- are (the probe's renders do not run your `onRender` code, so a lamp it turns off stays off for that render), name the key and fill lights
331
- you added, and report fog that covers most of the picture or a black frame with the material that causes it. They also measure what your own code
332
- does to the frame: a `ShaderMaterial` in view that ignores the fog or the tone curve, a light layout that changed during play (a shader recompile), two transparent meshes with one
333
- `renderOrder` whose pixels depend on draw order. Each line says what it measured, or `not sure`. `recipes/60-judge-the-picture.md`
334
- says how to judge the result.
325
+ `threedog shot <page> --time 22:00` (and `--weather rain`): the picture hints measure your lights and glowing materials as they are (the probe's renders do not
326
+ run your `onRender`), name the key and fill lights, and report fog that covers most of the picture, a black frame and its material, a shader in view that ignores
327
+ fog or tone curve, a light layout that changed during play, and transparent meshes whose pixels depend on draw order. How to judge: `recipes/60-judge-the-picture.md`.
@@ -1,84 +1,73 @@
1
1
  # Third-person start: walking, camera, save, pause, menu
2
2
 
3
- **In this recipe**: 1. About twenty lines · 2. What each line gives · 3. Where it stops · 4. Talk, press E, a quest, a counter · 5. Not worth it for a small game · 6. A model made in code, placed in content
3
+ > **Covers:** the shortest third-person start, and its first-person variant (§7): walking, camera, collision, save, pause, menu.
4
+ > **Use when:** a character walks around a place you built, seen from behind or through its eyes.
5
+ > **Shortest:** about twenty lines (§1); first person changes three of them (§7).
6
+ > **Sections:** 1 About twenty lines · 2 What each line · 3 Where it stops · 4 Talk, press E · 5 Not worth it · 6 A model made · 7 First-person start
4
7
 
5
- The shortest working path for a game where a character walks around a place you built yourself. It is the blank template's `main.js` plus a few lines, on any
6
- ground (`--open-world` adds generated terrain and a sky on top of the same parts). The picture stays plain three.js in `picture/`; nothing here touches it.
8
+ The blank template's `main.js` plus a few lines, on any ground (`--open-world` adds terrain and a sky on the same parts). The picture stays plain three.js in `picture/`.
7
9
 
8
10
  ## 1. About twenty lines
9
11
  ```js
10
- import 'threedog/tsl'; // WebGPU with TSL, as a new game starts; a game started with --webgl drops this line and `renderer: 'webgpu'`
12
+ import 'threedog/tsl'; // WebGPU with TSL, as a new game starts; a game started with --webgl drops this line and `renderer: 'webgpu'`
11
13
  import { createEngine, presets, world, content, settings, characters, collision, followCamera, hud } from 'threedog';
12
14
  import { createPicture } from './picture/index.js';
13
15
  import data from './content/index.js';
14
16
 
15
17
  const engine = createEngine({ canvas: document.getElementById('view'), renderer: 'webgpu', lights: false,
16
- bindings: { ...presets.bindings.walk, ...presets.bindings.interact }, // Shift runs, Space jumps, E uses; WASD, arrows and the pad stick are built in
17
- ui: { loading: { title: 'Pier' }, title: { title: 'Pier' } }, saveKey: 'pier' }); // start screen: Continue (once a save exists), Start, Settings
18
+ bindings: { ...presets.bindings.walk, ...presets.bindings.interact }, // Shift runs, Space jumps, E uses; WASD, arrows and the pad stick are built in
19
+ ui: { loading: { title: 'Pier' }, title: { title: 'Pier' } }, saveKey: 'pier' }); // start screen: Continue (once a save exists), Start, Settings
18
20
  engine.use(world(), content(), collision(), characters(), followCamera({ pointerLock: true }), hud(), settings({ freezeWorld: true }));
19
- engine.saves.autosave(0.5); // every 30 s of play
21
+ engine.saves.autosave(0.5); // every 30 s of play
20
22
  engine.use(createPicture());
21
23
  const { picture } = engine;
22
- engine.collision.addBlocked((x, z) => Math.abs(x) > 3 || Math.abs(z) > 20); // the walkable shape: here a pier 6 m by 40 m
23
- engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: [0, 0, 0] });
24
+ engine.collision.addBlocked((x, z) => Math.abs(x) > 3 || Math.abs(z) > 20); // the walkable shape: here a pier 6 m by 40 m
25
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, spawn: [0, 0, 0] });
24
26
  engine.content.load(data);
25
27
 
26
- const game = { score: 0 }; // the game's own state: plain values
27
- engine.saves.register('game', { version: 1, save: () => ({ ...game }), load: d => { Object.assign(game, d); } });
28
- engine.hud.counter('score', { label: 'Score', value: game.score });
28
+ const game = { score: 0 };
29
+ engine.saves.define('game', { version: 1, save: () => ({ ...game }), load: d => { Object.assign(game, d); } });
30
+ engine.hud.addCounter('score', { label: 'Score', value: game.score });
29
31
  Object.assign(window, { engine, picture });
30
32
  await engine.start();
31
33
  ```
32
34
 
33
35
  ## 2. What each line gives
34
- | You get | From | Without writing |
35
- |---|---|---|
36
- | WASD, arrows, stick, run, jump, walking relative to the camera, gravity | `characters()`, `presets.player.thirdPerson` | movement code, key listeners |
37
- | The camera follows, mouse turns it, walls pull it in | `followCamera()` | camera rig, pointer lock |
38
- | The player's position and your state come back after a refresh | `saves.autosave`, `saves.register`, Continue on the start screen | localStorage code, a save format, versioning, a corrupt-save path |
39
- | Esc stops the game and opens a menu: quality presets, volume, keys, language, save files | `settings({ freezeWorld: true })` | a pause flag in every system, a menu |
40
- | A walkable shape and solid things | `collision()`: `addBlocked`, `addBox`, `addCircle`, `addObject(mesh)` | bounds checks in the movement code |
41
- | A score on screen | `hud()`, `engine.hud.counter` | DOM upkeep |
36
+ Each line is one module you can swap: `characters()` with `presets.player.thirdPerson` (WASD, arrows, stick, run, jump, camera-relative walking, gravity), `followCamera()` (the camera follows, the mouse turns it, walls pull it in), `saves.autosave` and `saves.define` (position and your state come back after a refresh; Continue on the start screen), `settings({ freezeWorld: true })` (Esc stops the game and opens a menu: quality presets, volume, keys, language, saves), `collision()` (`addBlocked`, `addBox`, `addCircle`, `addObject(mesh)`), `hud()` (`addCounter`).
42
37
 
43
- A floor that is not at `y = 0`: `engine.setGround({ height: (x, z) => 0.4 })`. A body for the player: `createPlayer({ model })` (recipe 13); without one it is a gray capsule.
38
+ A floor that is not at `y = 0`: `engine.setGround({ height: (x, z) => 0.4 })`. A body for the player: `addPlayer({ model })` (recipe 13); without one it is a gray capsule. Feet on stairs and slopes: `engine.player.anim.addFeet()` ([13 §3e](13-animation.md)).
44
39
 
45
40
  ## 3. Where it stops
46
41
  Each part is one line to swap and none of them holds the rest back:
47
- - Your own movement or feel: recipe 21 §5 replaces one piece of the player and keeps saving and `describe().player`; drop `characters()` and write it all, and the rest still works.
48
- - Your own start screen: `engine.ui.set('title', ...)`; your own menu: recipe 26 §6. Win and lose windows: `makeWindow` with `closable: false` (recipe 26 "The choice cursor"), replay with `engine.session.newGame()`.
49
- - Saving at a moment you choose (a lamp lit, a level done): `await engine.saves.save()` beside the timer. A refresh keeps what the last save wrote, so a save started as the page closes is not one to rely on.
50
- - Pictures past the start screen: `threedog shot --play`.
42
+ - Your own movement or feel: recipe 21 §5 replaces one piece of the player and keeps saving and `describe().player`; dropping `characters()` leaves the rest working.
43
+ - Your own start screen: `engine.ui.set('title', ...)`; menu: recipe 26 §6. End screens: recipe 26 ("A window: results, game over"); replay with `engine.session.newGame()`.
44
+ - Saving at a moment you choose (a lamp lit, a level done): `await engine.saves.save()`. A refresh keeps what the last save wrote; a save started as the page closes is not reliable.
51
45
 
52
- ## 4. Talk, press E, a quest, a counter
53
- Add `THREE, interactions, dialogue, quests` to the import and `interactions({ ...presets.interactions.nearest }), dialogue(), quests()` to `engine.use`; E is already bound in section 1 (any other key works: `interact: ['KeyF']`; with no key at all dev warns with the line to add). Then, before `engine.start()`:
46
+ ## 4. Talk, press E, a counter
47
+ Add `THREE, interactions, dialogue` to the import and `interactions({ ...presets.interactions.nearest }), dialogue()` to `engine.use`; E is already bound in section 1 (any other key works: `interact: ['KeyF']`; with no key at all dev warns with the line to add). Then, before `engine.start()`:
54
48
  ```js
55
- const guide = new THREE.Mesh(new THREE.CapsuleGeometry(0.4, 1, 4, 8), new THREE.MeshStandardMaterial({ color: 0xc89a5a })); // any three.js object
49
+ const guide = new THREE.Mesh(new THREE.CapsuleGeometry(0.4, 1, 4, 8), new THREE.MeshStandardMaterial({ color: 0xc89a5a })); // any three.js object
56
50
  guide.position.set(0, 0.9, -8); engine.scene.add(guide);
57
51
  const shell = new THREE.Mesh(new THREE.SphereGeometry(0.25), new THREE.MeshStandardMaterial({ color: 0xd8c8a8 }));
58
52
  shell.name = 'shell'; shell.position.set(1, 0.25, -4); engine.scene.add(shell);
59
53
  engine.dialogue.define('guide', { start: { text: 'Pick up the shell, then walk to the end of the pier.', choices: [{ text: 'On my way', do: s => { s.flags.met = true; } }, { text: 'Later' }] } });
60
- engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'coins' }); // hides it, counts it, both saved
61
- engine.interactions.add(guide, { label: 'Talk', onUse: () => engine.dialogue.start('guide') }); // E nearby; the same call works on a door, a lever
62
- engine.input.bind(presets.bindings.quests); // J opens the quest log
63
- engine.quests.define('pier', { title: 'The pier', steps: [
64
- { text: 'Talk to the guide', target: guide, done: e => !!e.dialogue.state.flags.met },
65
- { text: 'Walk to the pier end', target: { x: 0, z: 18 }, done: e => (e.actorPosition()?.z ?? 0) > 17 }] }); // a marker arrow follows the target
66
- engine.quests.start('pier');
67
- engine.hud.counter('coins', { label: 'Coins', value: 0 }); // call again with a new value to update it
54
+ engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'coins' }); // hides it, counts it, both saved
55
+ engine.interactions.add(guide, { label: 'Talk', onUse: () => engine.dialogue.start('guide') }); // E nearby; the same call works on a door, a lever
56
+ engine.hud.addCounter('coins', { label: 'Coins', value: 0 }); // call again with a new value to update it
68
57
  ```
69
- Dialogue flags, quest progress and what `once` and `counter` did are saved by the modules: no `register` for them. An interaction's `counter` adds 1 to the HUD counter of that name (`hud.bump`); read the total with `engine.hud.value('coins')`, the one place it lives. A short popup message: `toast(engine, 'Picked up a shell')` (import `toast` from `threedog`; recipe 26 §3).
58
+ A quest with a marker arrow and a log (J): recipe 04. Dialogue flags and what `once` and `counter` did are saved by the modules. An interaction's `counter` adds 1 to the HUD counter of that name (`hud.bump`); read the total with `engine.hud.value('coins')`.
70
59
 
71
- A content prop with `collide` blocks the follow camera with its whole mesh; a hand-written mesh blocks it only after `engine.rays.addStatic(mesh, { occluder: true })` (recipe 21).
60
+ Camera blocking: recipe 21 (`addStatic`).
72
61
 
73
62
  ## 5. Not worth it for a small game
74
- Plain three.js and `engine.setGround` are the shorter road for the things below; the modules pay off only when a game leans on them. Ready-made looks are optional too: `threedog how "cel shading"` finds them.
75
- - Water: a `PlaneGeometry` with your own material is enough for a pond or a sea seen from a pier. `water()` earns its place with waves that float things, or swimming.
76
- - Full terrain: a flat or gently rolling island is `engine.setGround({ height: (x, z) => ... })` plus meshes. `terrain()` is for large streamed worlds.
77
- - The sky module for a fixed time of day: a background color or a gradient mesh and your own lights. `sky()` is for a day that changes.
78
- - Rigid vehicles: a mesh that moves by your own rule needs no physics. `rigid()` is for things that must push, roll and collide.
63
+ Plain three.js and `engine.setGround` are shorter for these; the modules pay off when a game leans on them.
64
+ - Water: a `PlaneGeometry` with your material; `water()` is for floating waves, or swimming.
65
+ - Terrain: `engine.setGround({ height: (x, z) => ... })` plus meshes; `terrain()` is for large streamed worlds.
66
+ - The sky module for a fixed time of day: a background color or gradient mesh and your lights; `sky()` is for a changing day.
67
+ - Rigid vehicles: a mesh moved by your rule needs no physics; `rigid()` is for pushing, rolling, colliding.
79
68
 
80
69
  ## 6. A model made in code, placed in content
81
- Any game, any genre: the shape is code, where it stands is content. The blank game ships one example, and it is neutral gray on purpose.
70
+ The shape is code, where it stands is content. The blank game ships one gray example.
82
71
  ```js
83
72
  // assets.js: a generator returns a geometry (drawn gray) or an Object3D; it runs once per name, every placement is a clone
84
73
  const marker = () => new THREE.CylinderGeometry(0.2, 0.25, 1.2, 12).translate(0, 0.6, 0);
@@ -88,4 +77,18 @@ export default [{ name: 'starter', models: { marker } }];
88
77
  // content/props.js: placements, each with a stable id (saved with the game)
89
78
  export default [{ id: 'marker-1', model: 'marker', x: 0, z: -2 }, { id: 'marker-2', model: 'marker', x: 3, z: -5 }];
90
79
  ```
91
- `scene.add` at startup also works, but the model stays out of GAMEMAP and the save. `world.add` at startup makes a second copy after each load unless it has `{ save: false }`, and `npm run check` warns about that. A `.glb` registered under the same name later replaces the generator with no other change (recipe 05). Before building a model or an effect from scratch, `threedog lib list` and `threedog how "<words>"` also search the library.
80
+ `scene.add` at startup also works, but the model stays out of GAMEMAP and the save; `world.add` at startup duplicates after each load unless `{ save: false }` (`npm run check` warns; recipe 18). A `.glb` registered under the same name later replaces the generator (recipe 05). `threedog lib list` and `threedog how "<words>"` search the library before you build from scratch.
81
+
82
+ ## 7. First-person start: walk and collide with walls you built
83
+ The same start with the camera at the eyes; §1 changes in the player preset, the camera module, and the walls (code-built level, grid, maze).
84
+ ```js
85
+ import { createEngine, presets, world, content, settings, characters, collision, firstPersonCamera, hud } from 'threedog';
86
+ engine.use(world(), content(), collision(), characters(), firstPersonCamera({ height: 1.6 }), hud(), settings({ freezeWorld: true })); // pointer lock is on by default
87
+ engine.characters.addPlayer({ ...presets.player.aim, spawn: [0, 0, 0] }); // aim: the body turns with the view
88
+ const maze = ['.....', '..#..', '.....']; // rows by z, columns by x, 1 m cells from 0, 0: '#' = wall (your grid or code map)
89
+ engine.collision.addBlocked((x, z) => maze[Math.floor(z)]?.[Math.floor(x)] === '#'); // walls of a grid or code map: one pure function
90
+ engine.collision.addBox([4, 0, -6], { halfWidth: 1, halfDepth: 0.2, height: 3 }); // one wall, crate or door frame
91
+ engine.cameraRig.yaw = Math.PI; // heading: yaw 0 looks toward -z, PI toward +z (recipe 21 §3)
92
+ ```
93
+ `world()` stays even with no content and no saves (the player is a record in it); `content()`, `hud()`, `settings()` can go.
94
+ Walls from your own geometry are only picture until a collider (api/collision.md) says no. Later third-person: `engine.setCamera('follow')` (recipe 21 §1).
@@ -1,12 +1,17 @@
1
1
  # Particles: dust, smoke, sparks, splashes
2
2
 
3
+ > **Covers:** particles: dust, smoke, sparks, splashes; values over life, emitters, soft edges.
4
+ > **Use when:** short-lived effects in numbers.
5
+ > **Shortest:** `engine.use(particles({ effects: { dust: { … } } }))`, then `engine.particles.emit('dust', p)`.
6
+ > **Sections:** Where a value comes · Values over life · Fast emitters · Soft edges · Lit particles · The material · Weather
7
+
3
8
  ```js fragment
4
9
  import { particles } from 'threedog';
5
10
  engine.use(particles({
6
- default: { color: 0xc8b89a }, // what every effect starts from
7
- effects: { dust: { max: 300, lifetime: [0.6, 1.2], size: [0.3, 0.8], opacity: [0.6, 0] } }, // the effects, by name
11
+ default: { color: 0xc8b89a }, // what every effect starts from
12
+ effects: { dust: { max: 300, lifetime: [0.6, 1.2], size: [0.3, 0.8], opacity: [0.6, 0] } }, // the effects, by name
8
13
  }));
9
- engine.particles.emit('dust', player.position, { count: 20 }); // a name in effects needs no define()
14
+ engine.particles.emit('dust', player.position, { count: 20 }); // a name in effects needs no define()
10
15
  engine.particles.define('smoke', { gravity: 0.4, size: [0.5, 2] });
11
16
  const chimneySmoke = engine.particles.attach('smoke', chimney, { rate: 8, offset: [0, 2, 0] });
12
17
  chimneySmoke.remove();
@@ -21,8 +26,8 @@ Lowest to highest: the neutral fallback, `particles({ default })`, `particles({
21
26
  ## Values over life
22
27
  `size`, `color` and `opacity` take one value, `[birth, death]`, or more stops: evenly spaced, or timed from 0 (birth) to 1 (death).
23
28
  ```js
24
- engine.particles.define('flash', { size: [0.2, 1.5, 0.4] }); // evenly spaced
25
- engine.particles.define('puff', { opacity: [[0, 0], [0.1, 0.7], [1, 0]] }); // fades in, then out
29
+ engine.particles.define('flash', { size: [0.2, 1.5, 0.4] }); // evenly spaced
30
+ engine.particles.define('puff', { opacity: [[0, 0], [0.1, 0.7], [1, 0]] }); // fades in, then out
26
31
  engine.particles.define('ember', { color: [[0, 0xffffff], [0.3, 0xffaa33], [1, 0x331100]] });
27
32
  ```
28
33
  Before the first time and after the last, the end stop holds. A stop list in `overrides` belongs to that batch.
@@ -32,7 +37,7 @@ Before the first time and after the last, the end stop holds. A stop list in `ov
32
37
  ```js fragment
33
38
  engine.particles.define('trail', { rate: 0, ratePerMeter: 6, lifetime: [0.4, 0.6], max: 200 });
34
39
  const trail = engine.particles.attach('trail', rocket);
35
- trail.ratePerMeter = 12; // live; attach(name, object, { ratePerMeter }) sets it too
40
+ trail.ratePerMeter = 12; // live; attach(name, object, { ratePerMeter }) sets it too
36
41
  ```
37
42
  Set `max` to what the trail needs: a step that earns more keeps the newest. A teleport counts as moving: set `active = false` for a frame around it. While frozen nothing is born.
38
43
 
@@ -47,12 +52,19 @@ cannot read the depth it draws into, so the scene is drawn once more, depth only
47
52
  wind, displacement or alphaTest. On WebGPURenderer's WebGL2 backend (the fallback where WebGPU is missing) three's depth copy works only with post and antialias on; elsewhere there the
48
53
  particles draw hard and the console says so. `soft` applies to the engine's material, not to one of yours.
49
54
 
55
+ ## Lit particles
56
+ By default a particle's color is drawn as given (dust looks the same in a dark mine and in a bright spot). `lit: true` lets the scene's lights tint it:
57
+ ```js
58
+ engine.particles.define('dust', { max: 300, color: 0xc8b89a, opacity: [0.6, 0], lit: true }); // dark away from the light, warm beside it
59
+ ```
60
+ Each particle gets what a matte card facing every light would show (Lambert, no facing). Shadows, environment map, probes and area lights do not count: dust behind a wall still sees the light, and with only an environment map it goes dark (add an ambient or hemisphere light). CPU cost: live particles x lights per frame, same on both renderers; set at `define`, not per batch.
61
+
50
62
  ## The material
51
63
  ```js
52
64
  const sparks = engine.particles.define('sparks', { blending: 'additive' });
53
- sparks.material = new THREE.PointsMaterial({ size: 0.2, color: 0xffaa33 }); // WebGLRenderer: drawn as given
54
- sparks.material = null; // the engine's back
55
- sparks.uniforms.uMaxPx.value = 64; // live
65
+ sparks.material = new THREE.PointsMaterial({ size: 0.2, color: 0xffaa33 }); // WebGLRenderer: drawn as given
66
+ sparks.material = null; // the engine's back
67
+ sparks.uniforms.uMaxPx.value = 64; // live
56
68
  ```
57
69
  `.material` is the effect's plain three.js material, `.points` what draws it. Particle age reaches the picture through the geometry attributes `aSize`,
58
70
  `aAlpha`, `aColor`, `aAngle`: a material that ignores them shows every particle alike, and one that wants the fade reads them, as
@@ -63,7 +75,7 @@ buffer with `aAlpha` 0, so give them size 0 as the engine's shader does.
63
75
  // TSL (WebGPURenderer, a new game's route): import { PointsNodeMaterial } from 'three/webgpu'; import { attribute, color, mix, vec4 } from 'three/tsl';
64
76
  const m = new PointsNodeMaterial({ transparent: true, depthWrite: false, sizeAttenuation: false });
65
77
  m.colorNode = vec4(mix(color(0x00ff00), color(0xff0000), attribute('aLife', 'float')), attribute('aAlpha', 'float'));
66
- sparks.material = m; // placed and sized by the engine's nodes, unless m sets positionNode / sizeNode (the particle's place is attribute('aPos', 'vec3'))
78
+ sparks.material = m; // placed and sized by the engine's nodes, unless m sets positionNode / sizeNode (the particle's place is attribute('aPos', 'vec3'))
67
79
  ```
68
80
  A flipbook is the same material with a texture. Each route has its own y: `uv()` runs up, `gl_PointCoord` runs down.
69
81
  ```js fragment