threedog 0.8.0 → 1.0.1

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 (372) hide show
  1. package/CHANGELOG.md +223 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -10,3 +10,4 @@ const engine = createEngine({ renderer }); // canvas defaults to renderer.domE
10
10
  - The engine configures only a renderer it created itself. With yours it sets nothing: pixel ratio (unless `pixelRatio` is given), size, tone mapping, exposure and shadow map stay as you left them, so set them yourself on the renderer. MSAA follows your renderer's `antialias` too (unless `createEngine({ antialias })` says otherwise; a value that differs from the renderer's runs the post chain's MSAA targets every frame).
11
11
  - **WebGLRenderer or three's WebGPURenderer.** On WebGPURenderer, materials, patches and post effects take their node / TSL forms (recipe 56). Everything else (scene, modules, input, saves, ops) does not depend on the renderer.
12
12
  - Changing the renderer, lights or post effects is yours to do at any time; the engine never warns. `engine.describe().render` (CLI: `describe render`) lists the current values; `describe().picture.writers` says which line wrote each on the dev server.
13
+ - **A transparent canvas** (the page shows through where nothing is drawn) is this same route; createEngine has no option for it. WebGL: `new THREE.WebGLRenderer({ canvas, alpha: true })` (three's default is opaque). WebGPURenderer: alpha is on by default; pass `alpha: true` to be explicit. Then `renderer.setClearColor(0x000000, 0)` and keep `engine.scene.background` null (a colour or texture background is opaque by definition). Post effects keep the alpha (tested on both backends with vignette). With `fallback: 'webgl'` a WebGPURenderer you built with alpha is replaced by a WebGLRenderer that keeps the alpha (a renderer the engine built itself stays opaque).
@@ -19,7 +19,7 @@ same data and adds the files: `source` (where `name: 'shop'` or `define('shop.bu
19
19
  A module entry has: `state`, `stage`, `runIndex` (place in `engine.moduleOrder`), `critical`, `requires`, `optional` (`{ name, installed, lost }`),
20
20
  `params` (schema, default and the value in use), `ops` (`{ name, desc, args, failures }`), `saves` (`{ key, version, migrates }`),
21
21
  `time` (`hooks`, `step: 'fixed' | 'frame' | 'none'`, `skip`), `queries` (`describe().<id>`, names added with `describe.add`, the api's public names) and
22
- `problems`, such as "fixed hook but no skip hook" or an `optional` module that is missing.
22
+ `problems`, such as "no skipKind" (the module does not say how `engine.skip` advances it) or an `optional` module that is missing.
23
23
 
24
24
  `threedog catalog <id>` lists each param as `key:type=default — sentence`: the type (for `any` params) and sentence are read from the module's api page (its options typedef JSDoc), so the schema keeps only names, defaults and checks; a param with no sentence shows `(no doc)` and counts as a problem (rule R38 lists the modules).
25
25
 
@@ -30,13 +30,18 @@ Who owns what: an op, save part or describe name registered while a module's `in
30
30
  An op arg is `'int?'` or the full schema `{ type, default, min, max, values, desc, optional }`. The same object validates the call in dev, fills the
31
31
  default before `can` and `run`, and is what the catalog and `threedog catalog` show, so the code never needs `n = 1` in two places.
32
32
  ```js
33
+ const PRICE = { bread: 2 };
33
34
  engine.ops.define('shop.buy', {
35
+ atomic: true,
34
36
  args: { item: 'string', n: { type: 'int', default: 1, min: 1, max: 99, desc: 'how many' } },
35
37
  can: (e, { item, n }) => e.inventory.count('gold') >= n * PRICE[item] ? true : 'noMoney',
36
- run: (e, { item, n }) => e.inventory.add(item, n),
37
- reasons: { noMoney: 'Not enough gold' }, // the failure codes the catalog lists
38
+ run(e, { item, n }) {
39
+ e.inventory.remove('gold', n * PRICE[item]);
40
+ return e.inventory.add(item, n).added === n ? n : { ok: false, code: 'bagFull' };
41
+ },
42
+ reasons: { noMoney: 'Not enough gold', bagFull: 'No room in the bag' }, // the failure codes the catalog lists
38
43
  });
39
- engine.ops.run('shop.buy', { item: 'bread', n: 0 }); // dev: throws "n must be >= 1"; release: returns { ok: false, code: 'badArgs' } (run never starts)
44
+ engine.ops.run('shop.buy', { item: 'bread' }); // n: 1; with n: 0, dev throws "n must be >= 1" and release returns { ok: false, code: 'badArgs' } (run never starts)
40
45
  ```
41
46
 
42
47
  ## 3. Declare module options once (`readParams`)
@@ -57,7 +62,8 @@ The schema types are those of op args plus `object`, `array` and `function` (opt
57
62
  time hooks; a `fixed` hook without `skip` is listed under problems (recipe 49).
58
63
 
59
64
  ## 5. "How do I get this effect": `threedog how`
60
- `threedog how "rain"` scores the words of the task against the AI.md task rows and the recipe headings with their first sentence, and prints the
61
- top five: the API in the row, the recipe path with section (`recipes/08-weather-sky.md §1`) and a one-line snippet. It reads the docs only, so it works with no page
62
- and prints the same list every run. When a dev page runs it adds up to three live catalog modules whose name matches the first English word. Words match at a word
63
- start (`rain` does not hit `terrain`). No hit means rephrase, or read AI.md.
65
+ `threedog how "rain"` (the MCP tool `how` is the same answer) scores the words of the task against the AI.md task rows and the recipe headings, then leads with one
66
+ recommended route. That is a first read, never the only allowed way. Under it: whether the route is installed in this game (the game's `engine.use` calls, or the page's catalog when
67
+ one is attached), which dependency is missing, a minimal example, and the next route when it does not fit. `--full` lists the other routes with their paragraphs, your library's
68
+ entries and this game's own modules. It works with no page and answers the same every run. Words match at a word start (`rain` does not hit `terrain`). A weak match
69
+ recommends nothing and lists the closest hits; rephrase, or read AI.md.
@@ -28,7 +28,7 @@ Fog and the placeholder lights: [recipe 34](34-environment-lighting.md). The sky
28
28
 
29
29
  ## Surfaces: ground, plants, cloud shadow, season
30
30
 
31
- ```js
31
+ ```js fragment
32
32
  engine.terrain.material = myGroundMaterial; // plain three.js on the module; terrain({ colors, shading, detail }) are its start values (recipe 28)
33
33
  engine.uniforms.uWindFreq.value = 1.5; engine.uniforms.uWindAmp.value = 0.5; // signals: live on every plant, planted ones too
34
34
  engine.vegetation.define('grass', { geometry, wind: { amplitude: 0.05, glsl, tsl } }); // your own sway: threedogWind(...) / tsl: (ctx) => moved position (recipe 36)
@@ -57,7 +57,7 @@ Each runs in a slot, then by `order` (low first): `scene` (replaces the scene re
57
57
  A plain Pass is placed by its kind: one that renders `engine.scene` itself (`RenderPixelatedPass`, `SSAARenderPass`, `TAARenderPass`) goes in `scene` and replaces the engine's scene render (the scene is drawn once; a second one throws), FXAA / SMAA / TAA in `final`, any other in `hdr` after the effects already there (`ldr` when you added it after an OutputPass); a RenderPass of `engine.scene` and an OutputPass are skipped (the engine has them). Without `{ name }` it is listed by class or shader name (`CopyShader#1`); its `remove()` does not dispose it.
58
58
 
59
59
  To read the chain: `engine.post.object()` and `engine.post.targets()`; both stay the engine's (it rebuilds passes, resizes, disposes), so change the chain through `engine.post`; to take the built chain over, `engine.post.own()` (`own(false)` gives it back). A game that renders the canvas itself (its own composer) takes the frame: the engine stops drawing and warns once `[own-frame]`.
60
- ```js
60
+ ```js fragment
61
61
  import { bloom, outline, vignette, lut } from '@threedog/post-effects'; // shared effects come from the add-on
62
62
  import { LUTPass } from 'three/addons/postprocessing/LUTPass.js';
63
63
  const line = engine.post.add(outline({ thickness: 1.5 })); engine.post.add(vignette());
@@ -86,7 +86,7 @@ export default bloom({ strength: 0.2 });
86
86
  This was reasoned on a one-dimensional model of the two orders, not yet checked with the real passes.
87
87
  - On / off: `engine.post.get('bloom').enabled = false` for every effect, whoever added it, pauses it where it is (place and params stay); `engine.plugins.off('<file>')` unloads a plugin (the effect leaves the chain; `on` plugs it again; a pack's file: `'<pack>/<file>'`). Either way
88
88
  it comes back in the same place: inside a slot `order` decides, and equal orders keep the order the names were first added in. There is no `createEngine({ post })`. The switch is the shared point `post.<name>.enabled`: `enabled` writes its game layer, a hold of your own goes through `engine.mod('post.bloom.enabled', { owner, set, layer })`, and reading `enabled` gives what runs now.
89
- The settings menu shows `bloom` / `ao` toggles only when effects with those names exist; a toggle the player turns off sits on the settings layer of that point, above the game and any hold (`describe().render.post` reads `writer: 'settings'`). MSAA is `engine.post.setAntialias(on)` and works with every effect on.
89
+ The settings menu shows `bloom` / `ao` toggles only when effects with those names exist; a toggle the player turns off sits on the settings layer of that point, above the game and any hold (`describe().render.post` reads `writer: 'settings'`). MSAA is `engine.post.antialias = on` and works with every effect on.
90
90
  - `fuse`: a light color effect can skip its own fullscreen pass by carrying a GLSL snippet instead of `create()`:
91
91
  `fuse: { uniforms: { uMyAmount: 'float' }, values: p => ({ uMyAmount: p.amount }), glsl: 'color.rgb *= 1.0 - uMyAmount * length(vUv - 0.5);' }`.
92
92
  Fused effects that are on and next to each other in one slot (never `scene`) compile into one shader and draw in one pass, in `order`. The
@@ -124,7 +124,7 @@ Each of them is registered once (`core/ops/owned.js`), and every one behaves the
124
124
  | `background` | sky | sky: a backdrop color or skybox every frame; with the dome the dome hides when you take it | `scene.background = x` (the dome hides); whole sky: `engine.sky.replace(texture \| object3D)` | `engine.sky.backdrop = '#335577'` |
125
125
  | `view.aspect` | view | every resize | `engine.autoView.manual('aspect')` | - |
126
126
  | `sky.sunDir` | view | `sky()` each frame, from the time and `engine.sky.orbit` (the same vector as `uSunDir`) | `engine.autoView.manual('sunDir')` | - |
127
- | `view.far` | view | terrain view range (`setViewChunks`) | `engine.autoView.manual('far')` | - |
127
+ | `view.far` | view | terrain view range (`terrain.viewChunks`) | `engine.autoView.manual('far')` | - |
128
128
  | `view.fov` | view | the settings menu fov slider, camera modules (first person / rts fov, fixed shots, back to the install fov on a switch) | `engine.autoView.manual('fov')` | - |
129
129
  | `view.pixelRatio` | view | adaptive resolution, about once a second while slow | `engine.autoView.manual('pixelRatio')` | `engine.setPixelRatio(1.5)` |
130
130
  | `camera` (position, rotation) | view | the camera module, every frame | `const cam = engine.takeCamera('me')` (`cam.remove()` gives it back) | - |
@@ -3,6 +3,7 @@
3
3
  A shared value is something several owners change: the game, a module, an effect. Name it, say who you are, say how you change it:
4
4
 
5
5
  ```js
6
+ engine.time.channel('enemies'); // a channel of your own exists once you name it (world, player and calendar are built in)
6
7
  const slow = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time; slow.remove() ends it early
7
8
  engine.mod('time.world', { owner: 'hitstop', set: 0, layer: 'system', for: 0.06 }); // decide on a higher layer: hides everything below
8
9
 
@@ -21,8 +22,8 @@ What to remember:
21
22
  - **Layers combine by themselves.** The game sets a base value, effects (weather, sunset, bullet time) multiply on top, the player's settings cap
22
23
  it. You never pick a layer by hand unless you want to: game code and game modules write `'game'` (the default); effects pass `layer: 'effect'`.
23
24
  - **`mul` / `add` to cooperate, `set` to decide.** Any number of owners can multiply and add. Two owners `set` the same value on the same layer is
24
- an error in development that names both lines and gives three copyable fixes; copy one. Release builds let the later write win and warn once.
25
- - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`.
25
+ an error (in development and release alike) that names both lines and gives three copyable fixes; copy one. The earlier value stays.
26
+ - **`replaces` to swap an engine part** that `provides` a slot; a second provider without it is the error `shared-taken`. What the old part issued goes with it: read `engine.<slot>` where you use it, and keep the issuer beside any handle so you can compare (`if (from !== engine.rigid) { from = engine.rigid; crate = from.addBox(mesh); }`). Version numbers count per module, so they cannot tell two modules apart. The engine's own props, NPCs, pickups, cars and movers do this; a rider leaves a rigid car when rigid goes. `world` is the exception: it owns every record, so install your world before the modules that need it. Once they are installed, or after `start()`, `replaces: 'world'` and `unuse('world')` are refused (`module-replaces`, `module-unuse`) and nothing changes. A factory that gives two modules goes in whole: `engine.use(terrain(o), { replaces: 'terrain' })` swaps its drawing part too. A module of your own wraps `world.present`, `world.simulate`, `rays.addProvider`, `input.touchButton` and `assets.onSwap` in `ctx.track(...)`, so they leave with it.
26
27
  - Every handle ends with `h.remove()` (`engine.mod`, `ctx.mod`, `input.gate`, `wrap`, `freeze`, `takeCamera`); it drops only your own entry.
27
28
 
28
29
  Only things several parties commonly write are shared values: time speeds and the calendar rate, pause / freeze / camera holders, move stats,
@@ -64,7 +65,7 @@ engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) =>
64
65
  - Saved: `engine` to `effect` entries. Not saved: `settings` (the settings module re-applies the player's choices), `system`, `debug`.
65
66
 
66
67
  ## Picture points follow the same rule
67
- `shadows.enabled`, `post.<name>.enabled`, `sky.tint`, `sky.flash` and `ground.cover` are shared points like the rest: the game sets a base value, effects multiply on top, the player's settings cap it.
68
+ `shadows.enabled`, `post.<name>.enabled`, `sky.tint`, `sky.flash` and `ground.cover` are shared points like the rest.
68
69
  `sky.tint`, `ground.cover` (blend by amount) and `sky.flash` (adds) are written with `engine.mod`.
69
70
  ```js
70
71
  const hold = engine.mod('shadows.enabled', { owner: 'cutscene', layer: 'system', set: false }); // decides over the game
@@ -106,7 +107,7 @@ checks that need this step's player position). The order never depends on which
106
107
 
107
108
  Two modules that each want to be "the" one (a sky, a tone-mapping stage, an inventory) declare an exclusive slot: `provides: ['inventory']`.
108
109
  Other modules `requires: ['inventory']` and work with whichever holds it. `engine.use(myInventory(), { replaces: 'inventory' })` unloads the
109
- holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails.
110
+ holder (its tracked handles, its `ctx.mod` entries, its `dispose`) before the new install, and puts it back if that fails, with its save data and content sections. Either way the holder is a fresh install, so `module:restored` fires with the fresh modules once their `init` is done: content sections load again, as a `content.load` on a running game would (a newcomer with its own format may refuse a pack written for the old holder: that part stays out, with a warning naming the pack), and what game code defined on the old holder by hand it defines again on that event. Level walls and solid props need no event: they go into whichever `collision` or `collider3d` is installed, also one that came late or came back.
110
111
 
111
112
  Most replaceable modules have a contract (`modules/gameplay/*.contract.js`, `modules/*/contract.js`; object contract `modules/characters/vehicle.contract.js`; the rest and what cannot be replaced: CONVENTIONS.md "What can be replaced"): the api, fields, ops, events
112
113
  and save keys other code relies on, and nothing more (the engine's callers use only that surface). `runContract(contract, () => myInventory(), { check })`
@@ -1,7 +1,7 @@
1
1
  # WebGPU and your own TSL materials
2
2
 
3
3
  **In this recipe**: WebGPU or WebGL · Turning it on, fallbacks · A minimal TSL material · The engine's values as nodes · The engine's shader
4
- functions · Patches with a `tsl` field (lighting hooks) · Sky and fog hooks · Post effects as nodes · A consistent style · Mistakes, each with the fix · GLSL to TSL
4
+ functions · Patches with a `tsl` field (lighting hooks) · Sky and fog hooks · Post effects as nodes · A consistent style · Mistakes, each with the fix · Drawn wrong without a thrown error · GLSL to TSL
5
5
 
6
6
  On the WebGPU route a game draws with three.js node materials (`MeshStandardNodeMaterial` ...) and writes shaders in TSL, three's shading
7
7
  language in JavaScript. Learn TSL from three itself: the [TSL guide](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language) and
@@ -286,6 +286,17 @@ Many materials, many programs: WebGPURenderer builds one program per distinct se
286
286
  `detail` / `lighting` options through `applyEffects` share theirs, so a hundred stones build one; a patch you write once and pass
287
287
  to every material shares too, a fresh patch object per material builds one program each.
288
288
 
289
+ ## Drawn wrong without a thrown error
290
+ These come from WebGPURenderer in three.js r187. Nothing throws and the engine's start check does not name them, so the picture is what shows them.
291
+ - `new THREE.Points(geo, new THREE.PointsMaterial({ size: 8 }))` → `const s = new THREE.Sprite(new PointsNodeMaterial({ positionNode: instancedBufferAttribute(attr), size: 8 })); s.count = n; s.frustumCulled = false`: a `Points` object is always 1 px here, and `size` and `sizeNode` work only on the instanced sprite. `engine.particles` already draws this way.
292
+ - `new THREE.LineLoop(geo, mat)` → `new THREE.Line(geo, mat)` with the first point repeated at the end: the renderer skips a `LineLoop` and logs a console error each frame.
293
+ - `new THREE.LineBasicMaterial({ linewidth: 4 })` → `Line2` from `three/addons/lines/webgpu/Line2.js` with `LineGeometry` and `new Line2NodeMaterial({ linewidth: 4 })`: line primitives have no width on WebGPU. The addon's plain `LineMaterial` is a `ShaderMaterial`, so it fails by name.
294
+ - `mesh.customDepthMaterial = m` (or `customDistanceMaterial`) → `material.castShadowPositionNode`, `material.maskShadowNode`, `material.castShadowNode`: only WebGLRenderer reads the old two. The shadow pass already follows a material's `positionNode`.
295
+ - `new THREE.MeshDepthMaterial()` (or `MeshDistanceMaterial`) → a `MeshBasicNodeMaterial` whose `colorNode` reads `depth` from `three/tsl`: neither has a node version, so the mesh draws with an empty `NodeMaterial` after a console error.
296
+ - `map.repeat.set(4, 4)` with `texture(map, myUv)` → `texture(map, myUv).setUpdateMatrix(true)`: a texture node given its own UVs ignores `repeat`, `offset` and `rotation`. `texture(map)` alone follows them.
297
+ - `new THREE.MeshBasicMaterial({ toneMapped: false })` → draw it outside the frame (`engine.ui`): the flag is never read here, so every material gets the frame's tone mapping.
298
+ - `new THREE.MeshStandardMaterial({ dithering: true })` → your own noise in `colorNode`, or a post effect: the flag is never read here, so banding stays.
299
+
289
300
  ## GLSL to TSL
290
301
  The language itself is in three's TSL guide. The lines that catch a port:
291
302
 
@@ -3,14 +3,14 @@
3
3
  Every character (the player, an NPC, a hand-built `Character`) has one control slot. One owner is in charge of it at a time, and only that
4
4
  owner moves the character. Take it, steer, give it back:
5
5
 
6
- ```js
6
+ ```js fragment
7
7
  // a quest walks the guard to the gate; its schedule waits and carries on afterwards
8
8
  const escort = engine.control.take(guard, { owner: 'escort', layer: 'script', step: (dt, ch) => ({ x: 0, z: 1 }) });
9
9
  escort.remove();
10
10
 
11
- // a roll: the keys pause for 0.4 s, then come back by themselves
11
+ // a roll: the keys pause for 0.4 play seconds, then come back
12
12
  const roll = engine.control.take(engine.player, { owner: 'roll', layer: 'script', step: () => ({ x: 0, z: 1, run: true }) });
13
- engine.clock.after(0.4, () => roll.remove());
13
+ engine.clock.after(0.4, () => roll.remove(), { channel: 'real' });
14
14
 
15
15
  // no step: move it from your own code; move() does nothing while someone above holds it
16
16
  const h = engine.control.take(drone, { owner: 'ai', layer: 'script' });
@@ -25,7 +25,7 @@ What to remember:
25
25
  orders; the default) < `cutscene` (timeline) < `physics` (a ragdoll: nothing can steer a limp body) < `net` (another machine drives it). The highest holder is in charge.
26
26
  - **A higher holder pauses the lower one, it does not cancel it.** When the cutscene ends, the walk it interrupted goes on; when the walk
27
27
  arrives, the keys work again. Nobody has to remember what to restore.
28
- - **One owner per layer.** Two different owners on the same layer is `[control-conflict]` in development, naming both: end the old one first
28
+ - **One owner per layer.** Two different owners on the same layer is `[control-conflict]` in every build, naming both: end the old one first
29
29
  (`h.remove()`), or take another layer. The same owner taking again just replaces its own hold.
30
30
  - **A held character moves only through its holder.** `character.move()` from anywhere else is `[control-bypass]` in development: the bug where
31
31
  keys, a walk and a cutscene all pushed one body in the same step and the last one won.
@@ -41,7 +41,7 @@ What to remember:
41
41
  | `createPlayer({ control })` | base | `'player-input'` | `control` is `'camera'` or `(player, input, dt) => ({ x, z, run })`; jump and driving live here too |
42
42
  | NPC behaviour (schedule, wander, your own) | base | `'npcs'` | paused near and far while anything above holds the NPC; kept by NPC id, so it survives the model being rebuilt |
43
43
  | `character.walkTo(target)` | script | `'walkTo'` | paused under a cutscene (no progress, no stuck clock), resumes after |
44
- | `timeline.play(steps, { actors })` | cutscene | `'timeline'` | `actors` defaults to `[engine.player]`; `[]` drives nobody; a `path` step adds its character. While the player is an actor, the `'cutscene'` input context is up |
44
+ | `timeline.play(steps, { actors })` | cutscene | `'timeline'` | `actors` defaults to `[engine.player]`; `[]` drives nobody; a `path` step adds its character. Resolves `{ ending, error? }`: `'finished'`, `'skipped'`, `'dropped'` (a load, new game or dispose took its state) or `'failed'`; `timeline:end` carries the same. While the player is an actor, the `'cutscene'` input context is up |
45
45
  | `net()` | net | `'net'` | a client holds every character the host drives; the host holds each peer's avatar. Taking one is `[control-net]`: change it with an op the host runs |
46
46
 
47
47
  Two cutscenes running at once are one owner (`'timeline'`), counted per character, so they never conflict; the slot goes back when the last
@@ -64,7 +64,7 @@ Move the player by script in one of three ways. Pick by what the player may stil
64
64
  | A ride on a route: boat, cable car, being carried up stairs | `engine.control.take` with `step: () => false` | steers nothing, gravity is off, your code places it |
65
65
  | Climbing: ladder, rope, wall | `mover: 'manual'` plus the `states` option | moves on the axis you write, the climb clip plays |
66
66
 
67
- ```js
67
+ ```js fragment
68
68
  // a ride: keys and gravity stop while the hold lasts; the seat is a point in the boat's own space
69
69
  const seat = new THREE.Vector3(0, 0.6, 0);
70
70
  const ride = engine.control.take(engine.player, { owner: 'boat', layer: 'script', step: (dt, ch) => {
@@ -78,13 +78,13 @@ To lock the player's input during a scripted ride, one line: `const lock = engin
78
78
  Gravity comes back the moment the hold ends, so end a ride where the character can stand: `player.placeAt(pier)` then `ride.remove()`, both in a
79
79
  fixed step or an op. The camera and saves follow the position as usual.
80
80
 
81
- ```js
81
+ ```js fragment
82
82
  // a ladder (the landing point must be ground or a registered platform, engine.characters.support; anywhere else it drops to what is below): createPlayer({ clips: { climb: 'Climb' }, states: () => climbing ? 'climb' : null }), then call this when the player uses the ladder
83
83
  let climbing = false;
84
84
  function climb(player, top) { // top: { x, y, z }, where it steps off, on ground or a registered platform
85
85
  climbing = true; player.mover = 'manual'; // no gravity, the position is yours
86
86
  const h = engine.control.take(player, { owner: 'ladder', layer: 'script', step: (dt, ch) => {
87
- const up = (engine.input.down('moveForward') ? 1 : 0) - (engine.input.down('moveBackward') ? 1 : 0);
87
+ const up = (engine.input.down('moveForward') ? 1 : 0) - (engine.input.down('moveBack') ? 1 : 0);
88
88
  ch.root.position.y += up * 2 * dt;
89
89
  if (ch.root.position.y < top.y) return null; // null: the mover runs, so states picks climb
90
90
  climbing = false; ch.mover = 'simple'; h.remove(); ch.placeAt(top);
@@ -107,5 +107,25 @@ hold.remove(); // go
107
107
 
108
108
  ## Saves
109
109
 
110
- Holds are not saved: they are running code (a walk, a cutscene, a quest step), and that code takes control again after a load. A walk is
111
- cancelled by a load (`walkTo` resolves `'cancelled'`).
110
+ Holds are not saved: they are running code (a walk, a cutscene, a quest step), and that code takes control again after a load. `walkTo` resolves
111
+ `'cancelled'` on whatever ends the walk: a load or new game, a level change, `placeAt`, a seat, physics taking the body, the character going. To go on, call it again.
112
+
113
+ ## Advanced: your own mover (flight, swimming, wall running)
114
+
115
+ Only for a body the built-in movers cannot move. Most games stop at the sections above.
116
+
117
+ Control decides where to go, the mover decides how to move. A mover is `(character, engine) => ({ name, move(x, z, run, dt, y), dispose? })`; `y` is the up part of the direction (a control step returns `{ x, y, z }`, default 0, and `walkTo` and NPCs pass it towards the path's next point). It writes `character.root.position`.
118
+
119
+ ```js fragment
120
+ const fly = (c, e) => ({ name: 'fly', move(x, z, run, dt, y) {
121
+ const p = c.root.position, v = c.stat('speed') * dt;
122
+ p.x += x * v; p.y += y * v; p.z += z * v;
123
+ c.grounded = false; e.characters.kit.ownState(c, 'fly', v / dt);
124
+ } });
125
+ const held = engine.mod('character.mover', { owner: 'wings', id: 'player', set: fly }); // for a while: held.remove() puts back what was there
126
+ engine.player.mover = fly; // or for good
127
+ ```
128
+
129
+ A mover that keeps something in the physics world gives it a `leave()`: the engine calls it when another mover takes over, and `move` runs again when it is back. `mover: 'rapier'` does this, so an NPC taking off leaves no capsule behind.
130
+
131
+ Contact is opt-in: `engine.characters.kit` has `kit.beginMove`, `kit.groundAt`, `kit.endMove`, `kit.ownState`. Call `kit.beginMove` first and `kit.endMove` last to be carried by platforms and keep `safeGround` and the fall check. A mover that calls neither owns contact. The rule takes the built-in names too, and `false` means `'manual'`; it is not saved, take it again after a load. What a mover must have: `modules/characters/mover.contract.js`.
@@ -58,3 +58,16 @@ Everything a module declares or binds through `ctx.input` leaves with it (rollba
58
58
  `engine.input.rebind('attack', ['KeyK'])` is the player's choice, on top of the game's keys; `rebind('attack', null)` gives the game's back.
59
59
  `engine.input.rebound()` lists them (the settings menu saves exactly that and restores it at start, even before the module declaring an action is
60
60
  installed). The settings menu's key page, its reset button and its save all go through these two calls.
61
+
62
+ ## Local players on one screen
63
+
64
+ A seat is one player's own keys and gamepad. It reads like `engine.input` (`axis`, `down`, `pressed`, `released`), so a control function works on either.
65
+
66
+ ```js
67
+ const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });
68
+ const p2 = engine.characters.createPlayer({ id: 'two', input: two, control: 'camera', spawn: [4, 0, 0] });
69
+ ```
70
+
71
+ The seat's pad leaves `engine.input` and answers the game's pad bindings on this seat alone, so `bind('jump', ['PadA'])` works for it as written. A seat's keys are its own list: keep them out of the first player's bindings. Two seats on one pad or key, or one seat on two players, throw `input-seat`.
72
+
73
+ `engine.player` stays the first player; `p2` has its own world record, saved with the world, and `removePlayer('two')` takes it away. There is one screen and one camera. Footstep sounds and NPCs giving way cover every player. A seat with its own `interact` key uses what its player stands by, as that player (`seat.actor`, set by `createPlayer`; `ctx.actor` in the op). The prompt shows `engine.actor`'s choice alone, and one hold runs at a time. A trigger zone hears every player when its `who` names them.
@@ -56,7 +56,7 @@ hard-edged or pitch-dark look may want exactly what was measured. All of them re
56
56
  | one shadow texel covers X m | the size on the ground of one shadow map pixel, when shadows do not show | cascades: `engine.shadows.cascades(engine.lights.sun, { count })` for the engine sun, `engine.shadows.cascades(light, { count: 3 })` on your own light ([recipe 45](45-cascaded-shadows.md)) |
57
57
  | over budget | lit point and spot lights, shadow maps, the largest map size, against `engine.budget` | many lights: `engine.lightPool` ([recipe 09](09-materials-lights-models.md)); shadows: `castShadow`, `light.shadow.mapSize` picked from `engine.tier` |
58
58
  | shadows nearly black | how much the fill adds on the shadowed pixels themselves | `engine.bakeProbes` ([recipe 34](34-environment-lighting.md)) or a fill light |
59
- | shadow stripes, stepped edges | the shadow alone, at canvas pixels: thin bands, or stairs along an edge | the bias, map size and shadow range it lists; stairs also the cascades above |
59
+ | shadow stripes, stepped edges | the shadow alone, at canvas pixels: several thin bands side by side, or edges that move when only the shadow map's pixel grid moves | the bias, map size and shadow range it lists; stairs also the cascades above |
60
60
  | fog covers X% | how much of the picture is fog color; printed before a line about the night, since the fog comes first | `scene.fog` |
61
61
 
62
62
  Limits a game sets per device go through the same check: `engine.budget.enable(engine.tier === 'low' ? { lights: 4 } : { lights: 12 })`. A limit you wrote is
@@ -1,7 +1,7 @@
1
1
  # The whole picture in plain three.js: signals in, picture out
2
2
 
3
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 (4b), what the engine still does (5), checking (6).
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).
5
5
 
6
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
7
  lights, materials, fog, sky colors and post passes. The engine hands it signals (time of day, weather) and keeps doing the engineering
@@ -13,7 +13,7 @@ a night street in a flat-illustration look; `picture/` is the whole picture). Ev
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/
16
- index.js wiring: creates the parts, calls each part's update(signals) in one engine.onRender; no values here
16
+ index.js wiring: the picture module (engine.use(createPicture()), then engine.picture): creates the parts, calls each part's update(signals) in one engine.onRender; no values here
17
17
  palette.js colors and key values for the whole game, including the tone curve
18
18
  lights.js lights: the mapping from signals to lights
19
19
  materials.js materials by name; other code asks for picture.materials.wall and never builds its own
@@ -22,16 +22,17 @@ picture/
22
22
  shaders/*.glsl your shader code; saving one hot-reloads it
23
23
  areas/<name>.js a large game's overrides for one area (a cave, an interior): only what differs
24
24
  ```
25
- To add a part, write a file that returns `{ update(signals) }` and call it from `index.js`:
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:
26
26
  ```js
27
27
  // picture/sky.js: the engine's dome stays, fog is the game's
28
- export function createSky(engine) {
29
- engine.scene.fog = new THREE.Fog(palette.fog.color, palette.fog.near, palette.fog.far);
30
- return { update(s) { engine.scene.fog.color.copy(night).lerp(day, s.uDaylight.value); } };
28
+ export function createSky(engine, ctx) {
29
+ const fog = new THREE.Fog(palette.fog.color, palette.fog.near, palette.fog.far);
30
+ ctx.borrow(engine.scene, { fog });
31
+ return { update(s) { fog.color.copy(night).lerp(day, s.uDaylight.value); } };
31
32
  }
32
33
  // picture/post.js: engine.post.add takes a three.js Pass and keeps the chain in order (recipe 52)
33
- export function createPost(engine) {
34
- engine.post.add(new ShaderPass(GrainShader), { name: 'grain' });
34
+ export function createPost(engine, ctx) {
35
+ ctx.track(engine.post.add(new ShaderPass(GrainShader), { name: 'grain' }));
35
36
  return { update() {} };
36
37
  }
37
38
  ```
@@ -70,7 +71,7 @@ own, read by the picture code, so the picture still has one writer.
70
71
  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.
71
72
 
72
73
  ## 3. The hook: `engine.onRender`, not `onFrame`
73
- ```js
74
+ ```js fragment
74
75
  const sun = new THREE.DirectionalLight(0xffffff, 2), hemi = new THREE.HemisphereLight(); // made once in picture/lights.js
75
76
  engine.onRender(() => {
76
77
  const day = engine.uniforms.uDaylight.value, rain = engine.uniforms.uRain.value;
@@ -86,7 +87,7 @@ the modules' frame hooks: it would read last frame's values (and noon on the ver
86
87
  ## 3b. Rules that keep the folder working in a bigger game
87
88
  - **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
88
89
  a name of your own and never touches the light or the material:
89
- ```js
90
+ ```js fragment
90
91
  // picture/index.js
91
92
  export const picture = { lights, materials, lamp: id => ({ off() { lamps.get(id).intensity = 0; } }) };
92
93
  // gameplay
@@ -106,17 +107,20 @@ the modules' frame hooks: it would read last frame's values (and noon on the ver
106
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.
107
108
 
108
109
  Under the dev server (`npm run dev`, `threedog snap`) the engine records which line last changed each value:
109
- ```js
110
- engine.describe('picture').picture.writers // { values: { 'fog.far': { at: 'picture/sky.js:12', framesAgo: 3 }, 'light:sun.intensity': ... }, conflicts: [...] }
111
- engine.explain({ picture: 'fog.far' }) // threedog explain picture fog.far
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
112
114
  ```
113
115
  Names are `renderer.toneMapping`, `renderer.toneMappingExposure`, `scene.fog`, `fog.near | far | density | color`, `scene.environment`, `scene.environmentIntensity`,
114
- `scene.background`, `scene.backgroundIntensity`, `light:<name>.intensity | color | groundColor | position`, `material:<name>.color | emissive | opacity | emissiveIntensity`.
116
+ `scene.background`, `scene.backgroundIntensity`, `light:<name>.intensity | color | groundColor | position`, `material:<name>.color | emissive | opacity | emissiveIntensity`,
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.
115
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,
116
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.
117
121
 
118
- **A conflict warning** reads `fog.far was written twice in one frame with different results: picture/sky.js:14, then picture/rival.js:3. The later write is what is drawn`, then the fix.
119
- The first 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.
122
+ **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.
120
124
  Both writes going through a shared helper count as one place, the helper's line: the warning cannot see past it.
121
125
 
122
126
  ## 3d. Save to the library, pull it out
@@ -129,7 +133,7 @@ threedog lib pull flat-materials # lands in picture/
129
133
  ```
130
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
131
135
  (`./palette.js`) and names them; the entry would arrive as a half. Take the numbers as parameters instead:
132
- ```js
136
+ ```js fragment
133
137
  /** Flat materials by name: a flat color plus an emissive copy of it that rises at night.
134
138
  * @param {object} THREE three.js @param {Record<string, number>} palette name → hex @param {number} nightGlow emissive at full night */
135
139
  export function flatMaterials(THREE, palette, nightGlow = 0.2) {
@@ -146,7 +150,7 @@ A day-and-night light group is the same shape: `dayNightLights(THREE, scene, { d
146
150
  ## 3e. Several parts change one picture value
147
151
  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
148
152
  (recipe 55): everyone changes it with `engine.mod`, and one place in `picture/` reads the result and writes three.js once.
149
- ```js
153
+ ```js fragment
150
154
  // picture/lights.js: the one writer
151
155
  const level = engine.stacks.define('sun.level', { base: 1, min: 0, save: false });
152
156
  const sun = new THREE.DirectionalLight(0xffffff, 2);
@@ -161,26 +165,27 @@ An amount that moves takes one entry and changes it: `const wet = ctx.mod('sun.l
161
165
  `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.
162
166
 
163
167
  ## 3f. Picture parts: three.js code from different sources in one game
164
- Code you write alone stays the plain functions of section 0, and pays nothing for this section. Use a part when code has to live beside code you did not write: an entry from the library,
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,
165
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.
166
- ```js
170
+ ```js fragment
167
171
  // picture/harbor-fog.js
168
172
  import * as THREE from 'three';
169
173
 
170
174
  export const harborFog = ({ near = 10, far = 200 } = {}) => ({
171
175
  name: 'harborFog', type: 'picture', provides: ['fog'],
172
176
  install(e, ctx) {
173
- e.scene.fog = new THREE.Fog(0x667788, near, far);
177
+ ctx.borrow(e.scene, { fog: new THREE.Fog(0x667788, near, far) }); // given back when the part goes
174
178
  const flare = new THREE.PointLight(0xffaa66, 2, 30);
175
179
  e.scene.add(flare);
176
180
  ctx.track(e.onRender(() => { // reads signals, writes three.js
177
181
  e.scene.fog.far = far * (1 - 0.6 * e.uniforms.uRain.value);
178
182
  flare.intensity = 2 * (1 - e.uniforms.uDaylight.value);
179
183
  }));
180
- ctx.track({ remove() { e.scene.remove(flare); flare.dispose(); e.scene.fog = null; } }); // what it added goes with it
184
+ ctx.track({ remove() { e.scene.remove(flare); flare.dispose(); } }); // what it added goes with it
181
185
  },
182
186
  });
183
187
  ```
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`).
184
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
185
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.
186
191
 
@@ -206,7 +211,7 @@ A part that needs another one says `requires: ['sun']`. A shared value a part de
206
211
  **What the dev server reports** (`npm run dev`, `threedog snap`). It observes and blocks nothing; a bundled build has none of it. `describe('picture').picture.slots` shows who holds what, in every build.
207
212
  - `picture-held`: a value in a held slot was written by anyone else, in any frame. It names the holder, the writer and both lines. Fix: delete the write, swap the holder, or make it a shared value.
208
213
  In `picture.writers.values`, a held value says `writer: 'holder'` or `writer: 'stray'`; `picture.writers.held` lists the strays.
209
- - `picture-conflict`: two places wrote one value in one frame (3c), with the part names when they are parts.
214
+ - `picture-conflict`: two places wrote one value in one frame or kept taking turns (3c), with the part names when they are parts.
210
215
  - `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.
211
216
  `ctx.track` only removes what it was handed, so anything else needs a `remove()` or the part's `dispose()`.
212
217
 
@@ -215,6 +220,13 @@ not named `'sun'`. Nothing here sees that a warm lamp clashes with a cold sea: t
215
220
 
216
221
  **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.
217
222
 
223
+ **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
+ ```js fragment
225
+ engine.use(duskPicture(), { replaces: 'picture' }); // the old look's lights, hooks, post effects and borrowed values go first
226
+ for (const m of myMeshes) m.material = engine.picture.materials[m.userData.surface];
227
+ ```
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`.
229
+
218
230
  ## 4. A flat illustration (one way among many)
219
231
  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:
220
232
  - `MeshLambertMaterial({ color: c, emissive: c, emissiveIntensity: 0 })`: raise the emissive copy at night, so faces
@@ -228,38 +240,84 @@ environment map comes out too dark on faces away from the sun: raise the ambient
228
240
  `uWeatherLight` is sized for the sun: multiplying ambient by it as well darkens rain more than the sun alone does, so give ambient a share of it.
229
241
 
230
242
  ## 4b. Pixel art: low-resolution rendering with sharp scaling
231
- Pixel art means drawing fewer pixels and then keeping every edge hard when they are enlarged. It takes two engine options and plain three.js and CSS:
232
- - **Render fewer pixels.** `pixelRatio` below 1 makes the drawing buffer smaller than the canvas on the page. Pick it from the art resolution you want against the canvas
233
- size, and call `engine.setPixelRatio(p)` again when the size changes. A value that makes one art pixel a whole number of screen pixels keeps them all the same size.
234
- - **Turn adaptive resolution off.** `adaptiveResolution: false`: it changes the render scale with frame cost, so the size of a pixel would drift during play.
235
- `antialias: false` too, since it blends the edges you want hard.
236
- - **Scale sharply.** The browser smooths an enlarged canvas unless told otherwise: CSS `image-rendering: pixelated` on it.
237
- - **Leave the menu rows that fight it out.** The settings menu's render scale, anti-aliasing and adaptive rows and its quality presets would change the pixel size. Leave those rows out where the game lists its tabs, `settings({ sections: [{ id: 'graphics', omit: ['pixelRatio', 'antialias', 'adaptive'] }, 'audio', 'controls', 'language', 'saves'] })`: an omitted row stays your value, and no preset or stored value moves it.
243
+ 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.
238
247
  - **Sample sharply.** `engine.assets.texture(name, { pixelated: true })` sets `NearestFilter` for enlarging and `NearestMipmapNearestFilter` for shrinking. On a texture of
239
248
  your own, set `magFilter` and `minFilter` to `THREE.NearestFilter`.
240
249
  ```js
241
- const canvas = document.querySelector('canvas');
242
- canvas.style.imageRendering = 'pixelated';
243
- const engine = createEngine({ canvas, pixelRatio: artHeight / canvas.clientHeight, adaptiveResolution: false, antialias: false });
250
+ const engine = createEngine({ canvas: document.querySelector('canvas'), pixelSize: 3 });
244
251
  ```
245
252
  Whatever blends neighbouring pixels works against the look, so judge each post effect and any tone curve (section 4) by eye. Text and panels under `engine.uiRoot` are page elements and stay at screen
246
- resolution. Objects that move by less than an art pixel shimmer; if that shows, round their drawn position to the art grid in `onRender`. `describe().render.scale` reports `upscaled: true` here, which is what you asked for.
253
+ resolution. Objects that move by less than an art pixel shimmer; `pixelSnap` and `pixelSprite` below deal with that. `describe().render.scale.pixelSize` reports k.
247
254
 
248
- **A following camera without jitter.** Jitter comes from rounding the camera and the character on their own: each lands on a different pixel from frame to frame. Keep one exact position and round once:
249
- - Draw the character with `engine.stepBlend` (recipe 06 section 1b), in `onFrame`.
250
- - Make the camera follow that drawn position. The camera module runs after the `onFrame` list, so it moves after the character in the same frame.
251
- - Round only the final position relative to the camera, in `onRender`, which runs after the camera has moved. Never round the camera and the character separately.
252
- ```js
253
- const drawn = new THREE.Object3D(); // the exact drawn position; the sprite is its rounded copy
254
- engine.cameraRig.follow(drawn);
255
- engine.onFrame(() => { drawn.position.lerpVectors(body.last, body.now, engine.stepBlend); }); // body: what onFixed moves
256
- engine.onRender(({ camera }) => { // side view, where screen x and y are world x and y; pixel: the world size of one art pixel
257
- const snap = (v, c) => c + Math.round((v - c) / pixel) * pixel;
258
- sprite.position.set(snap(drawn.position.x, camera.position.x), snap(drawn.position.y, camera.position.y), drawn.position.z);
259
- });
255
+ **A pixel-perfect camera.** `pixelSnap` on `followCamera` or `fixedCamera` rounds the camera to the art grid on the screen's own axes, so a turned or isometric view works. It is orthographic only. A perspective camera throws `camera-option`.
256
+ ```js fragment
257
+ engine.use(followCamera({ projection: 'orthographic', yaw: Math.PI / 4, pitch: 0.6, lockPitch: true, mouseLook: false,
258
+ pixelSnap: { pixelsPerMeter: 32, bounds: { minX: -20, maxX: 20, minZ: -20, maxZ: 20 } } }));
259
+ ```
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.
262
+ - **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
+ - **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.
265
+
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.
267
+
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.
269
+ ```js fragment
270
+ import { pixelSprite, spriteFrame } from 'threedog/pixel';
271
+ 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
273
+ ```
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.
277
+
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.
279
+ ```js fragment
280
+ // picture/spriteNormals.js
281
+ import * as THREE from 'three';
282
+ export function silhouetteNormals(image, frameWidth, frameHeight, { strength = 1.5, blur = 1 } = {}) {
283
+ const W = image.width, H = image.height, ctx = Object.assign(document.createElement('canvas'), { width: W, height: H }).getContext('2d', { willReadFrequently: true });
284
+ ctx.drawImage(image, 0, 0);
285
+ 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
287
+ const inside = (x, y) => x >= 0 && y >= 0 && x < w && y < h && alpha[((fy + y) * W + fx + x) * 4 + 3] > 127;
288
+ const d = new Float32Array(w * h), at = (a, x, y) => (x < 0 || y < 0 || x >= w || y >= h ? 0 : a[y * w + x]);
289
+ 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
291
+ 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
+ d[y * w + x] = v;
293
+ };
294
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) pass(x, y, 1);
295
+ for (let y = h - 1; y >= 0; y--) for (let x = w - 1; x >= 0; x--) pass(x, y, -1);
296
+ let height = d;
297
+ for (let i = 0; i < blur; i++) {
298
+ const next = new Float32Array(w * h);
299
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
300
+ let sum = 0;
301
+ for (let j = -1; j <= 1; j++) for (let k = -1; k <= 1; k++) sum += at(height, x + k, y + j);
302
+ next[y * w + x] = sum / 9;
303
+ }
304
+ height = next;
305
+ }
306
+ 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
309
+ 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
+ }
311
+ }
312
+ 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
314
+ t.generateMipmaps = false;
315
+ t.colorSpace = THREE.NoColorSpace; // numbers, not colours: an sRGB read would bend every normal
316
+ t.needsUpdate = true;
317
+ return t;
318
+ }
260
319
  ```
261
- A dead zone keeps small moves from shifting the camera: have it follow a separate object that the game moves only when the character leaves an area around it.
262
- For smooth scrolling of the whole picture, render with the camera on a whole pixel, draw slightly larger than the screen, and slide the final image by the leftover fraction. Nothing in this repository shows that step yet: it is untested.
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.
263
321
 
264
322
  ## 5. What the engine still does with all of this off
265
323
  - `scene.background` starts as a neutral gray: write your own color or sky.
@@ -17,7 +17,8 @@ const engine = createEngine({ canvas: document.getElementById('view'), renderer:
17
17
  ui: { loading: { title: 'Pier' }, title: { title: 'Pier' } }, saveKey: 'pier' }); // start screen: Continue (once a save exists), Start, Settings
18
18
  engine.use(world(), content(), collision(), characters(), followCamera({ pointerLock: true }), hud(), settings({ freezeWorld: true }));
19
19
  engine.saves.autosave(0.5); // every 30 s of play
20
- const picture = createPicture(engine);
20
+ engine.use(createPicture());
21
+ const { picture } = engine;
21
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
22
23
  engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: [0, 0, 0] });
23
24
  engine.content.load(data);