threedog 1.0.1 → 1.2.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 (364) hide show
  1. package/CHANGELOG.md +90 -0
  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 +178 -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 +16 -6
  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 +5 -5
  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 +46 -27
  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 +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  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 +16 -11
  103. package/docs/COMMANDS.md +31 -33
  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 +28 -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/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  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/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -1,5 +1,10 @@
1
1
  # Physics: rigid bodies, pushing, joints, vehicles
2
2
 
3
+ > **Covers:** rigid bodies, pushing, joints, vehicles, boarding and driving, ragdolls.
4
+ > **Use when:** crates that tumble, doors on hinges, a car or a boat.
5
+ > **Shortest:** `engine.rigid.addBox(mesh, { id })` with `rigid()` installed (§3).
6
+ > **Sections:** 1 Build a car · 2 Boarding and driving · 3 Rigid bodies saves · 3b Ragdoll experimental) · 4 Verify
7
+
3
8
  Any physics body (crates the player pushes, balls, doors on hinges, ropes): §3, read it first when the game has no car. Cars and
4
9
  boarding: §1–2.
5
10
 
@@ -18,7 +23,7 @@ function makeCar() {
18
23
  body.position.y = 0.3; body.castShadow = true; car.add(body);
19
24
  const wheels = [[-0.85, 1.2, true, false], [0.85, 1.2, true, false], [-0.85, -1.2, false, true], [0.85, -1.2, false, true]].map(([x, z, steer, drive]) => {
20
25
  const w = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 0.25, 10).rotateZ(Math.PI / 2), new THREE.MeshLambertMaterial({ color: 0x333333 }));
21
- w.position.set(x, 0, z); car.add(w); // wheels are children of the body: they follow suspension, steering and rolling
26
+ w.position.set(x, 0, z); car.add(w); // wheels are children of the body: they follow suspension, steering and rolling
22
27
  return { position: [x, 0, z], radius: 0.35, steer, drive, object: w };
23
28
  });
24
29
  return { car, wheels };
@@ -26,9 +31,9 @@ function makeCar() {
26
31
 
27
32
  engine.events.on('engine:ready', () => {
28
33
  const { car, wheels } = makeCar();
29
- car.position.set(10, engine.surface(10, 0) + 1.5, 0); // place it slightly above the ground and let it drop
34
+ car.position.set(10, engine.surface(10, 0) + 1.5, 0); // place it slightly above the ground and let it drop
30
35
  const v = engine.rigid.addWheeled(car, { wheels, mass: 600, engineForce: 3000, camera: { distance: 14, height: 2 } });
31
- window.car = v; // handy for tests and the console
36
+ window.car = v; // handy for tests and the console
32
37
  });
33
38
  ```
34
39
  Options: `../api/rigid.md` (VehicleOptions). `id` is the stable id saves use (default `vehicle1`, `vehicle2`... in creation order; give one when that order varies).
@@ -71,14 +76,14 @@ where a game re-creates its joints, with the same code that made them:
71
76
  ```js fragment
72
77
  const R = engine.rigid, J = R.rapier.JointData;
73
78
  const post = R.addBox(postMesh, { fixed: true }), door = R.addBox(doorMesh, { mass: 8 });
74
- function hang() { // makes the joints; called after the bodies are added, and again after every rebuild
79
+ function hang() { // makes the joints; called after the bodies are added, and again after every rebuild
75
80
  // hinge on the post's right edge, turning around Y; anchors are in each body's local space
76
81
  const h = R.world.createImpulseJoint(J.revolute({ x: 0.5, y: 0, z: 0 }, { x: -0.5, y: 0, z: 0 }, { x: 0, y: 1, z: 0 }), post.body, door.body, true);
77
82
  h.setLimits(-1.5, 1.5);
78
83
  R.world.createImpulseJoint(J.rope(2, { x: 0, y: -0.5, z: 0 }, { x: 0, y: 0.5, z: 0 }), hook.body, weight.body, true);
79
84
  }
80
85
  hang();
81
- engine.events.on('rigid:rebuilt', hang); // { world, player, bodies }: bodies maps the ids you gave addBox / addBall / addHull
86
+ engine.events.on('rigid:rebuilt', hang); // { world, player, bodies }: bodies maps the ids you gave addBox / addBall / addHull
82
87
  ```
83
88
  `entry.body` already points at the rebuilt body there; a joint object kept from before belongs to the freed world (hold the new one). A body
84
89
  the game made with `world.createRigidBody` is not rebuilt: make anchors with `addBox(mesh, { fixed: true })`. In development a `rigid-misuse`
@@ -99,8 +104,8 @@ stay). Removing a body removes its joints (Rapier does that).
99
104
  ## 3b. Ragdoll (experimental)
100
105
 
101
106
  ```js fragment
102
- const rd = engine.rigid.ragdoll(enemy, { impulse: [0, 150, -400], position: hit.point }); // a Character, NPC handle, id or skinned Object3D
103
- engine.clock.after(4, () => rd.remove(), { channel: 'real' }); // back to animation where the body lies; a get-up clip is yours to play
107
+ const rd = engine.rigid.ragdoll(enemy, { impulse: [0, 150, -400], position: hit.point }); // a Character, NPC handle, id or skinned Object3D
108
+ engine.clock.after(4, () => rd.remove(), { channel: 'real' }); // back to animation where the body lies; a get-up clip is yours to play
104
109
  ```
105
110
  - **Skeletons.** Mixamo, Blender, Unreal, Bip01, VRM and Quaternius names are read by themselves. Otherwise name the parts: `{ bones: { lowerLegL: 'Shin_01' } }`; an unreadable skeleton throws, naming the missing parts.
106
111
  Parts: `hips chest head upperArmL lowerArmL upperArmR lowerArmR upperLegL lowerLegL upperLegR lowerLegR`.
@@ -1,9 +1,14 @@
1
1
  # Navigation mesh (nav)
2
2
 
3
+ > **Covers:** the navigation mesh, paths, many paths at once, links across gaps, sight lines.
4
+ > **Use when:** characters walk around obstacles to a goal.
5
+ > **Shortest:** `engine.characters.findPath(from, to)` (with `nav()` for a mesh).
6
+ > **Sections:** 1 Install main.js) · 2 Use · 3 Verify · 4 Many paths at · 5 One source for · 6 NPC links across · Fences and rivers collision) · Gates some characters pass · Line of sight, stealth
7
+
3
8
  There is a single pathfinding entry point: `engine.characters.findPath(from, to)`; NPC schedules use it too.
4
9
  - Without `nav()` (or before it is built): the collision module's grid A* (good enough for open terrain with a few obstacles).
5
10
  - With `nav()`: after a level loads, a Recast navmesh is built; paths are more accurate and go around walls more cleverly. **Only level ground (the
6
- level module) is supported**; procedural terrain keeps using A*. The mesh is built once per level: `engine.terrain.edit` and other ground changes do not
11
+ level module) is supported**; procedural terrain keeps using A*. Without a level mesh dev warns once (`nav-fallback`): A* has no nav links, crowd or floor changes. The mesh is built once per level: `engine.terrain.edit` and other ground changes do not
7
12
  update it, so a game that reshapes walkable ground at runtime leaves `nav()` out.
8
13
 
9
14
  ## 1. Install (main.js)
@@ -11,7 +16,7 @@ A level is a file or a `THREE.Object3D` built in code: `level({ scene: group })`
11
16
  ```js fragment
12
17
  import { level, collision, followCamera, characters, nav } from 'threedog';
13
18
  engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(),
14
- nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
19
+ nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
15
20
  ```
16
21
  - Mesh source: the walkable meshes in the level (naming convention in `10-blender-level.md`). Walls = the level's `col_` boxes + every
17
22
  `addBox / addCircle` in the collision module;
@@ -20,11 +25,11 @@ engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), char
20
25
 
21
26
  ## 2. Use
22
27
  ```js fragment
23
- const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, y, z }...] or null (unreachable); a y on either end picks the floor
24
- const wall = engine.collision.addBox([16, 0, 0], { halfWidth: 4.5, halfDepth: 1 }); // temporarily block a gap (center, half width, half depth); the navmesh updates with it
25
- wall.remove(); // remove the obstacle
28
+ const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, y, z }...] or null (unreachable); a y on either end picks the floor
29
+ const wall = engine.collision.addBox([16, 0, 0], { halfWidth: 4.5, halfDepth: 1 }); // temporarily block a gap (center, half width, half depth); the navmesh updates with it
30
+ wall.remove(); // remove the obstacle
26
31
  engine.npcs.add({ name: 'Courier', position: [4, 0, -5], schedule: [{ at: 0, position: [4, 0, 5] }] }); // the NPC finds its own way there
27
- engine.nav.dispose(); // unload the navmesh; afterwards A* is used again
32
+ engine.nav.dispose(); // unload the navmesh; afterwards A* is used again
28
33
  ```
29
34
  Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd needs `nav({ crowd: true })`).
30
35
 
@@ -38,13 +43,13 @@ Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd n
38
43
 
39
44
  ## 4. Many paths at once: findPathAsync
40
45
  `findPath` answers now, on the main thread. For crowds (dozens of NPCs repathing, AI squads) use `findPathAsync`: the same search (navmesh if ready, else A*)
41
- runs in `engine.threads` workers and `done(path, status)` runs at the start of a fixed step about 4 steps (67 ms) later, through `engine.commits`.
46
+ runs in `engine.threads` workers and `done(path, status)` runs at the start of a fixed step about 4 steps (67 ms) later, through `ctx.commits`.
42
47
  ```js fragment
43
- const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { // status 'ok' | 'noPath' | 'notReady', as findPath({ detailed: true })
48
+ const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { // status 'ok' | 'noPath' | 'notReady', as findPath({ detailed: true })
44
49
  guard.path = path;
45
50
  }, { radius: 0.5 });
46
- req.remove(); // the target changed before the answer came: done is never called
47
- engine.characters.pathsPerStep = 64; // requests sent per fixed step (default 32); the rest wait in order
51
+ req.remove(); // the target changed before the answer came: done is never called
52
+ engine.characters.pathsPerStep = 64; // requests sent per fixed step (default 32); the rest wait in order
48
53
  ```
49
54
  - Built-in NPCs already use it; keep `findPath` for the few calls that need a path this step (player click-to-move).
50
55
  - threads on / off / slow / crashed give identical paths on the identical step: the worker mirrors the navmesh (exported bytes) and the collision colliders;
@@ -58,45 +63,45 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
58
63
  navmesh, A* and level steps all read it, so a module never writes its own 0.4 or 0.45. A character's position belongs to its mover: other systems
59
64
  request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
60
65
 
61
- A navmesh is cut for one body, so bodies of other sizes get their own. `nav({ agentRadius })` is the size built at load; a path asked for with another `radius` (`findPath`, `findPathAsync`, and `walkTo` and NPCs, which pass the character's own) uses a mesh of that size, built the first time it is asked for and kept until the next rebuild. A small body takes the gap a large one cannot, and a body too wide for every way gets `noPath` and stays put.
66
+ A navmesh is cut for one body; other sizes get their own. `nav({ agentRadius })` is the size built at load; a path with another `radius` (`findPath`, `findPathAsync`, `walkTo` and NPCs, which pass the character's own) uses a mesh of that size, built on first ask and kept until the next rebuild. A small body takes the gap a large one cannot; a body too wide for every way gets `noPath` and stays put.
62
67
  - Sizes are whole cells (`cellSize`, 0.3 m by default), rounded up: 0.5 and 0.6 share a mesh, and only a body no wider than `agentRadius` shares that one. To tell closer sizes apart, or fit a gap within a cell of the body, make `cellSize` smaller.
63
- - Each extra size is another mesh in memory, about as big as the first, and its first ask builds it there and then, on the main thread: about 10 ms on a 40 m level, 0.3 s on a 200 m one with 300 walls. Ask once during loading to take that off the first walk: `engine.nav.findPath(a, b, { radius })`. With one size none of this happens. Obstacles and rebuilds reach every size.
68
+ - Each extra size is another mesh in memory, built on the main thread at its first ask: about 10 ms on a 40 m level, 0.3 s on a 200 m one with 300 walls. Ask once during loading: `engine.nav.findPath(a, b, { radius })`. Obstacles and rebuilds reach all sizes.
64
69
  - Links exist on each size where both ends still reach its mesh, and their ends sit a little differently on each. `engine.nav.links` is the links of `agentRadius`; `crossing.to` on a path is the walker's own.
65
70
  - Height, step and slope are the same for all sizes: only the radius differs.
66
71
  - `nav({ crowd: true })` keeps one crowd on the `agentRadius` mesh: Recast's crowd runs on a single mesh, so give it the size of the widest crowd NPC. Use plain NPCs where sizes must differ.
67
72
 
68
- Floors: a `y` on a path, a stop or `collision.walkable([x, y, z])` picks the floor nearest that height, and `{ x, z }` means the ground. A height more than `engine.movement.height` from every surface there goes to the nearest one and warns once `[nav-height]`. A box added with `y` blocks only that floor, for paths, walkers and NPCs alike. Going between floors needs the navmesh; A* stays on the walker's floor and answers `noPath` for a goal on another one. Without `nav()`, a game names its stairs itself: `engine.mod('characters.path', { owner, set: ({ from, to }) => points })` returns the waypoints with their `y`, and `walkTo`, NPCs and `findPath` follow them. A walker that falls off asks again, so the list must work from anywhere it can be.
73
+ Floors: a `y` on a path, a stop or `collision.walkable([x, y, z])` picks the floor nearest that height, and `{ x, z }` means the ground. A height more than `engine.movement.height` from every surface there goes to the nearest one and warns once `[nav-height]`. A box added with `y` blocks only that floor, for every mover. Between floors takes the navmesh; A* answers `noPath` for a goal on another floor. Without `nav()` a game names its stairs: `engine.mod('characters.path', { owner, set: ({ from, to }) => points })` returns waypoints with `y` that `walkTo`, NPCs and `findPath` follow; a walker that falls off asks again, so it must work from anywhere.
69
74
 
70
75
  ## 6. NPC links across gaps
71
76
  A link joins two places no one can walk between (Recast calls it an off-mesh connection): a gap, a ledge, a teleporter. Paths use it like any other way, and a walker with no help from the game crosses in a straight line at walking speed.
72
77
  ```js fragment
73
78
  nav({ links: [
74
- { id: 'gap', from: [-2.2, 0, 0], to: [2.2, 1.5, 0] }, // both ways
75
- { id: 'drop', from: [10, 4, 2], to: [12, 0, 2], oneWay: true }, // down only
79
+ { id: 'gap', from: [-2.2, 0, 0], to: [2.2, 1.5, 0] }, // both ways
80
+ { id: 'drop', from: [10, 4, 2], to: [12, 0, 2], oneWay: true }, // down only
76
81
  ] });
77
- const path = engine.characters.findPath(a, b); // [{ x, y, z }, { x, y, z, link: { id: 'gap', from, to } }, { x, y, z }...]: the leg after a point with link is the crossing
82
+ const path = engine.characters.findPath(a, b); // [{ x, y, z }, { x, y, z, link: { id: 'gap', from, to } }, { x, y, z }...]: the leg after a point with link is the crossing
78
83
  ```
79
84
  - Put each end on or near walkable ground: within `radius` sideways (default the agent radius + 3 cells, enough for a point at a ledge or a ladder just off it) and within `maxClimb` in height. A `y` left out is the ground there.
80
- - Each end then moves onto the mesh, and that is where walkers step on and land: the mesh stops about the agent radius short of every edge, so a ladder at a deck's side or through a hatch ends 0.6 to 0.8 m in from the edge (cells round it), on the deck, wherever its top was written: in a 1.4 m hatch a foot at the opening's edge gives ends 0.6 to 0.9 m apart, a foot at its middle 1.3 m or more. `engine.nav.links` and `crossing.to` give those places. The straight line between them cuts through the deck's edge, so a ladder that must look straight uses `linkPose` to climb first and step in last (below).
85
+ - Each end then moves onto the mesh, and that is where walkers step on and land: the mesh stops about the agent radius short of every edge, so a ladder at a deck's side or through a hatch ends 0.6 to 0.8 m in from the edge (cells round it), wherever its top was written. `engine.nav.links` and `crossing.to` give those places. The straight line between them cuts the deck's edge: a ladder that must look straight uses `linkPose` (below) to climb first and step in last.
81
86
  - A link reaches at most the neighbouring tile, counted where its ends meet the mesh: two platforms up to `tileSize` x `cellSize` meters (9.6 m by default) minus a little on each side. An end that attaches nowhere gets the `nav-link` warning at the build; no path uses that link.
82
87
  - An obstacle on an end cuts the link until the obstacle goes. Elsewhere, rebuilt tiles keep their links, and `findPathAsync` sees the same ones. Links are fixed at `nav()`: none can be added at run time.
83
88
 
84
89
  The engine moves the walker and says when; how it looks and how long it takes are yours. NPCs, `character.walkTo` and `nav({ crowd: true })` NPCs all cross this way. There is no default animation: the body keeps its last state.
85
90
  ```js
86
- engine.events.on('link:enter', ({ character, crossing }) => { // crossing: { link, from, to, seconds, time }
91
+ engine.events.on('link:enter', ({ character, crossing }) => { // crossing: { link, from, to, seconds, time }
87
92
  if (crossing.link === 'gap') { crossing.seconds = 0.7; character.playAction('jump'); }
88
93
  });
89
94
  engine.events.on('link:exit', ({ id, crossing }) => console.log(id, 'crossed', crossing.link));
90
- engine.characters.linkPose = (t, position) => { position.y += Math.sin(t * Math.PI) * 1.2; }; // t 0-1: bend the straight line into a hop
91
- engine.characters.linkPose = (t, position, { from: a, to: b }) => { // or through a hatch: up the opening, then the step onto the deck; coming down, the step first
95
+ engine.characters.linkPose = (t, position) => { position.y += Math.sin(t * Math.PI) * 1.2; }; // t 0-1: bend the straight line into a hop
96
+ engine.characters.linkPose = (t, position, { from: a, to: b }) => { // or through a hatch: up the opening, then the step onto the deck; coming down, the step first
92
97
  const up = b.y > a.y, side = up ? Math.max(0, t - 0.85) / 0.15 : Math.min(1, t / 0.15), rise = up ? Math.min(1, t / 0.85) : Math.max(0, t - 0.15) / 0.85;
93
98
  position.set(a.x + (b.x - a.x) * side, a.y + (b.y - a.y) * rise, a.z + (b.z - a.z) * side);
94
99
  };
95
100
  ```
96
- - During a crossing the walker has no gravity or collision and its talk, goal and behavior wait. `npc.placeAt` ends it, and `link:exit` still comes. A control holder above the walker (a cutscene, a ragdoll, a `walkTo` on an NPC) does not wait for it: the walker lands at the far end at once, with its `link:exit`. A walker with no speed (a `move.speed` mod of 0) also lands at once, unless `link:enter` sets `seconds`.
97
- - An NPC's crossing is saved (`rec.nav.link`). After a load it goes on from the same spot: `link:enter` is not sent again, so a clip started there does not restart; `linkPose` and `link:exit` work as before. An NPC that goes out of range mid-crossing lands at the far end at once, with `character: null` in `link:exit`. A `walkTo` is not saved: its crossing ends with the walk, and `walk.remove()` lands the character at the far end.
101
+ - During a crossing the walker has no gravity or collision; its talk, goal and behavior wait. `npc.placeAt` ends it (`link:exit` still comes). A control holder above the walker (a cutscene, a ragdoll, a `walkTo` on an NPC) does not wait: the walker lands at the far end at once, with `link:exit`. A walker with no speed (a `move.speed` mod of 0) also lands at once, unless `link:enter` sets `seconds`.
102
+ - An NPC's crossing is saved (`rec.nav.link`). After a load it goes on from the same spot: `link:enter` is not sent again (a clip started there does not restart); `linkPose` and `link:exit` work as before. An NPC out of range mid-crossing lands at the far end at once, with `character: null` in `link:exit`. A `walkTo` is not saved: its crossing ends with the walk, and `walk.remove()` lands the character at the far end.
98
103
  - `linkPose` must depend only on its arguments, or a loaded crossing jumps. The game cannot hold a walker on a link until a clip ends: give `seconds` the clip's length.
99
- - With `crowd: true` the crowd takes a link about 1 m short of its end, so the NPC walks the rest and crosses from the end like any walker; the agent is pulled back to the NPC after the crossing, and only the character's own crossing counts. Recast does not say which link an agent took, so the nearest link end is used: keep the ends of two links apart. Recast times its traversal by the distance in x, z, so ends closer than the NPC's speed / 30 m on the mesh (one x, z, say, a ladder up through a solid deck) are over before the NPC can see them: such a link is not for crowd NPCs. Any opening is far enough: the deck stops short of it, as above.
104
+ - With `crowd: true` the crowd takes a link about 1 m short of its end, so the NPC walks the rest and crosses from the end like any walker; the agent is pulled back to the NPC after the crossing, and only the character's own crossing counts. Recast does not say which link an agent took, so the nearest link end is used: keep the ends of two links apart. Recast times a traversal by x, z distance, so ends closer than speed / 30 m (a ladder straight up through a solid deck) are over before the NPC sees them: not for crowd NPCs. Through an opening the ends are far enough apart.
100
105
  - A link has no queue. Walkers on it share the line and pass through each other, up and down at once, and other agents do not avoid them: six crowd NPCs pacing through one hatch never jammed (44 crossings in 46 s), often two on it 0.2 m apart. Taking turns is the game's.
101
106
  - A walker is not done while a link is left on its path, however close the goal is in x, z, so a goal at the top of a ladder is reached at the top. An NPC standing within `arriveDistance` of such a goal with no path yet, or one steered by the crowd, still stops at the foot: give the goal a place away from the ladder.
102
107
  - Paths choose a link by its length, like walking: there is no extra cost for a jump. Start and goal heights still come from `engine.surface`, so a path from under a deck starts on top of it.
@@ -113,12 +118,25 @@ engine.collision.addSegment([-18, 0, -12], [-18, 0, -4]);
113
118
  engine.collision.addSegment([-18, 0, 0], [-18, 0, 12], { thickness: 0.4 });
114
119
  ```
115
120
 
116
- Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster instead (re-sampled when you add or remove a field): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
121
+ Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster (re-sampled when a field is added or removed): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
122
+
123
+ ## Gates some characters pass: collider layers
124
+
125
+ A collider with a `layer` stops every mover but those whose `passes` names it (a pen, a members' door). Walking, paths and the navmesh obey it.
126
+
127
+ ```js fragment
128
+ engine.collision.addBox(gate, { halfWidth: 2, halfDepth: 0.3, layer: 'gate' }); // any add*
129
+ engine.npcs.add({ id: 'pig', name: 'Pig', passes: ['gate'] }); // or addPlayer, findPath
130
+ ```
131
+
132
+ Content: `collide: { layer: 'gate' }` on a prop or template; a Blender level: custom property `layer` on a `col_` / `collider` object or its parent.
133
+
134
+ `character.passes` may be rewritten. Each layer list gets a navmesh, like a size (section 5). Rigid bodies, `lineClear`, the camera and `nav({ crowd: true })` NPCs ignore layers.
117
135
 
118
136
  ## Line of sight, stealth vision cones and straight-line checks: collision.lineClear
119
- `engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?", the wall test of a guard's stealth vision cone (the cone itself is your own distance and angle check on `guard.facing`) for a 3D segment: boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m above it; a collider's `y` / `height` count). It is a boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (pass the character radius for "can I walk straight there").
137
+ `engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?" for a 3D segment (the wall test of a guard's vision cone; the cone is your own angle check on `guard.facing`): boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m up). A boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (the character radius answers "can I walk straight there").
120
138
  ```js fragment
121
- const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
139
+ const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
122
140
  const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
123
141
  ```
124
142
  The A* fallback smooths paths with the same idea: it samples each shortcut at most one character radius apart (so a thin fence cannot be skipped), starts from the character's real position, and its cell size follows `radius` (1-2 m) unless you pass `step`.
@@ -1,6 +1,9 @@
1
1
  # Animation state machine (skeletal animation)
2
2
 
3
- **In this recipe**: the model (1), clip names (2), skinned characters (3), procedural bodies (3b), 2D sprite characters (3c), which modules need a character (3d), other objects (4), gameplay-driven progress (5), checking (6).
3
+ > **Covers:** skeletal animation: clips mapped to game actions, skinned and sprite characters, objects that animate, look-at and foot IK.
4
+ > **Use when:** a model should move its body.
5
+ > **Shortest:** `engine.assets.animate(model, config)`.
6
+ > **Sections:** 1 The model · 2 Mapping game action · 3 A character with · 3b Procedural bodies are · 3c Sprite characters a · 3d Which modules need · 3e IK heads that · 4 Non-character objects a · 5 Gameplay controls progress · 6 Verify
4
7
 
5
8
  There is a single entry point: `engine.assets.animate(model, config)` -> Animator (advanced every frame by the engine; never call mixer.update yourself).
6
9
  For characters (player, NPCs), passing `model` builds the Animator automatically and switches clips by character state (idle walk run swim jump fall drive).
@@ -26,9 +29,9 @@ engine.assets.manifest({ name: 'heroes', models: { hero: { url: '/models/hero.gl
26
29
  fade: 0.2,
27
30
  states: { idle: { clip: 'Idle_Sword' }, walk: { clip: 'Walk' }, attack: { clip: 'Sword_Slash', loop: false, timing: 0.62 }, hurt: { clip: 'HitRecieve', loop: false } },
28
31
  } } } });
29
- engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // no clips / animation in code
32
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // no clips / animation in code
30
33
  await engine.player.whenReady;
31
- engine.assets.mapping(engine.player.anim.root); // the entry's mapping, or null
34
+ engine.assets.mapping(engine.player.anim.root); // the entry's mapping, or null
32
35
  ```
33
36
  A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and the entry's `fade` beats `characters({ animation })`.
34
37
 
@@ -45,18 +48,18 @@ A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and
45
48
 
46
49
  ## 3. A character with a skinned model (most common)
47
50
  ```js
48
- engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero,
49
- clips: { idle: 'Idle', walk: 'Walk', run: 'Run', jump: 'Jump' }, // character state -> clip name in the glTF; states you leave out use the capitalised name if the model has that clip
51
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero,
52
+ clips: { idle: 'Idle', walk: 'Walk', run: 'Run', jump: 'Jump' }, // character state -> clip name in the glTF; states you leave out use the capitalised name if the model has that clip
50
53
  });
51
- engine.player.playAction('Wave'); // one-shot clip (skipped if the clip doesn't exist); returns to the previous state when done
52
- engine.player.anim.state; // current state name
54
+ engine.player.playAction('Wave'); // one-shot clip (skipped if the clip doesn't exist); returns to the previous state when done
55
+ engine.player.anim.state; // current state name
53
56
  ```
54
57
  **The game's own states** (crouch, climb, glide, dash, roll) go on top of the built-in ones through the `states` option, without taking the mover
55
58
  over: it runs after the mover's state each step and returns a state name or null (keep the built-in `facts.base`); the clip comes from `clips`
56
59
  like any other state, a speed change stays `engine.mod('move.speed')`. A state only names the pose: climbing also needs someone to move the body
57
60
  (recipe 57, Moved by script, has a ladder).
58
61
  ```js
59
- engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
62
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
60
63
  states: (c, f) => f.grounded && engine.input.down('crouch') ? 'crouch' : !f.grounded && f.vy < 0 && gliding ? 'glide' : null });
61
64
  ```
62
65
  Deep water follows `water`: `'swim'` (default), `'block'` (never enters), `'wade'` (walks the bottom), or `(c, { depth }) => mode` per spot;
@@ -64,9 +67,9 @@ Deep water follows `water`: `'swim'` (default), `'block'` (never enters), `'wade
64
67
  For smooth walk/run blending, use `animation` instead of `clips` and write a `move` blend tree (when the model has no walk/run states, move is used
65
68
  automatically; the `speed` parameter is in m/s):
66
69
  ```js
67
- engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, animation: { states: {
70
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero, animation: { states: {
68
71
  idle: { clip: 'Idle' },
69
- move: { blend: [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }], param: 'speed', sync: true }, // sync: align footsteps
72
+ move: { blend: [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }], param: 'speed', sync: true }, // sync: align footsteps
70
73
  jump: { clip: 'Jump', loop: false },
71
74
  } } });
72
75
  ```
@@ -77,19 +80,17 @@ The default transition time for every character is `characters({ animation: { fa
77
80
  `engine.characters.material = new THREE.MeshToonMaterial({ color: 0xd9a066 })` swaps them all, as given. `colors: { body }` gives one character a copy in
78
81
  that color. A model keeps its own materials.
79
82
 
80
- **By asset name.** `model` also takes the name of a registered model asset: a file model, or a procedural builder. The character is built at once
81
- with a gray capsule; when the asset loads, a skeleton-correct copy replaces it under the same root, so position, facing, state, collision and the
82
- world view stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
83
+ **By asset name.** `model` also takes a registered model asset's name (file or builder). A file shows a gray capsule until the copy replaces it under the
84
+ same root (position, facing, state and collision stay); then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
83
85
  names; a failed load keeps the capsule and warns once; a character disposed before loading ends never gets the model. `p.anim` is set after `await p.whenReady` (unless the load failed).
84
86
 
85
87
  ## 3b. Procedural bodies are assets too (`model: 'humanoid'`)
86
- Every character picks its body with `model`, the same path for a GLB and a procedural builder. An asset pack can supply a code-built humanoid (box limbs swung by the engine
87
- while walking, running, swimming, jumping); a builder is built at once, so its joints (`player.armL`, `legR`...) exist right after `createPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
88
+ An asset pack can supply a code-built humanoid (box limbs the engine swings while walking, running, swimming, jumping); a builder is built at once, so its joints (`player.armL`, `legR`...) exist right after `addPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
88
89
  ```js fragment
89
- import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
90
+ import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
90
91
  engine.assets.manifest(assets);
91
- engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
92
- engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } }); // per-character part colors
92
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
93
+ engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } }); // per-character part colors
93
94
  ```
94
95
  - **Colors**: a builder's materials are its own three.js materials, and colors shared by many bodies come from `this.palette` (recipe 05);
95
96
  `colors: { body, skin, legs, hair }` recolors one character's marked parts.
@@ -98,18 +99,17 @@ engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } })
98
99
  meshes `userData.part = 'body'` for `colors`. A hand-built one-off passes `{ rig }` instead ([02-npc](02-npc.md)).
99
100
 
100
101
  ## 3c. Sprite characters: a 2D billboard or flat body in plain three.js
101
- A 2D sprite character is a plain three.js object handed to `model`, so there is no sprite module to learn. `THREE.Sprite` always faces the camera (a billboard);
102
- a `Mesh` with a `PlaneGeometry` stays flat and turns with `character.root`, takes light and can cast a shadow, which a `Sprite` does neither of.
103
- Frames are drawing, so they live in `picture/` (recipe 62) and gameplay never touches them. `onPose` gives them the character's state each frame:
102
+ A 2D sprite character is a plain three.js object handed to `model`. `THREE.Sprite` always faces the camera; a `Mesh` with a `PlaneGeometry` turns with
103
+ `character.root`, takes light and can cast a shadow. Frames live in `picture/` (recipe 62); `onPose` gives them the character's state each frame:
104
104
  ```js fragment
105
105
  // picture/sprites.js: a sheet of cols x rows frames; which row is which is your sheet's layout
106
106
  const ROW = { idle: 0, walk: 1, run: 1, jump: 2, fall: 2 };
107
107
  export function spriteBody(texture, cols, rows, framesPerSecond) {
108
- const map = texture.clone(); // offset lives on the texture, so one clone per character; the image stays shared
108
+ const map = texture.clone(); // offset lives on the texture, so one clone per character; the image stays shared
109
109
  map.needsUpdate = true;
110
110
  map.repeat.set(1 / cols, 1 / rows);
111
111
  const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map }));
112
- sprite.center.set(0.5, 0); // feet on the character's origin
112
+ sprite.center.set(0.5, 0); // feet on the character's origin
113
113
  let t = 0;
114
114
  const animate = (c, dt) => {
115
115
  t += dt;
@@ -119,14 +119,14 @@ export function spriteBody(texture, cols, rows, framesPerSecond) {
119
119
  }
120
120
  // main.js: the sheet is a name in assets.js like any texture
121
121
  const hero = spriteBody(await engine.assets.texture('hero-sheet', { pixelated: true }), 4, 3, 8);
122
- engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero.sprite }).onPose(hero.animate);
122
+ engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero.sprite }).onPose(hero.animate);
123
123
  ```
124
124
  **In an orthographic view of a 3D scene** use `pixelSprite` from `threedog/pixel` instead of a `Sprite` or a free plane (recipe 62 section 4b): a plain `Mesh` that stands upright, so walls behind it do not cut its head, and shows one texel per art pixel. `model` takes it as it is. It ignores the turn of `character.root`, and `onPose` picks the frame:
125
125
  ```js fragment
126
126
  const hero = pixelSprite({ grid: engine.cameraRig.pixelSnap.grid, material, width: 16, height: 24, columns: 4, rows: 3, snap: 'followed' });
127
- const ch = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero });
128
- const right = engine.cameraRig.pixelSnap.grid.axes().right; // the same vector every frame
129
- ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x + Math.cos(c.facing) * right.z < 0)); // no state machine here: which frame shows is the game's
127
+ const ch = engine.characters.addPlayer({ ...presets.player.thirdPerson, model: hero });
128
+ const right = engine.cameraRig.pixelSnap.grid.axes().right; // the same vector every frame
129
+ ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x + Math.cos(c.facing) * right.z < 0)); // no state machine here: which frame shows is the game's
130
130
  ```
131
131
  `c.facing` is an angle in radians around Y (0 looks along +Z), so `c.facing < 0` is not "looks left": which way is left depends on how the camera is turned. Mirror when the heading `(sin, cos)` points against the screen's right axis, as above. Run once in a view turned 45 degrees: walking toward the screen's right gave "not mirrored"; the other direction was not run.
132
132
  `character.root` and `hero.position` stay exact, so physics and saves see the true position. A one-off `new Character(engine, { model: hero })` still needs `engine.add(character.root)`, as in recipe 02.
@@ -139,7 +139,7 @@ ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x
139
139
  Tried with a `pixelSprite` mesh and a `Character` whose `model` is one (`threedog new-game name --pixel` is the starting game). Each row below was run once in a real browser, in a few lines; "not run" means only the docs were read.
140
140
  | Module | On a sprite / plain object / position | Result |
141
141
  |---|---|---|
142
- | `characters` (`createPlayer`, `new Character`, `walkTo`, `onPose`) | the sprite is the character's `model` | works: moves, collides, `state` and `facing` drive `onPose`; `walkTo` on an NPC character walked there |
142
+ | `characters` (`addPlayer`, `new Character`, `walkTo`, `onPose`) | the sprite is the character's `model` | works: moves, collides, `state` and `facing` drive `onPose`; `walkTo` on an NPC character walked there |
143
143
  | `interactions.add(object, ...)` | any mesh or sprite, no character | works: E near it, `once`, `counter`, saved as used |
144
144
  | `dialogue` | no object at all (a name and flags) | works: flags are in the save |
145
145
  | `triggers.add({ position })` | a position; `who` is the actor or an id | works: fired for the player character |
@@ -150,7 +150,18 @@ Tried with a `pixelSprite` mesh and a `Character` whose `model` is one (`threedo
150
150
  | `audio.sfx`, `audio.tone`, `ambience.add` | no object | ran without error (no sound file named, so nothing audible was checked) |
151
151
  | `weather.set`, `calendar.at`, `sky` | no object | installed and started; `weather.set('rain')` kept the name `clear` without a weather table (give the module one), `calendar.at` firing: not run |
152
152
  | `makeWindow(engine, opts)` | no object | created a window object (`open`, `toggle`, `remove`) |
153
- Needs an engine character: `createPlayer`, `walkTo`, `onPose`, schedules, characters' collision and ground. Everything else above takes a position or any `THREE.Object3D`. A sprite that only stands there (a signpost, an NPC that never walks) needs no `Character`; one that walks, follows ground or is scheduled does.
153
+ Needs an engine character: `addPlayer`, `walkTo`, `onPose`, schedules, characters' collision and ground. Everything else above takes a position or any `THREE.Object3D`. A sprite that only stands there (a signpost, an NPC that never walks) needs no `Character`; one that walks, follows ground or is scheduled does.
154
+
155
+ ## 3e. IK: heads that look, feet on the ground
156
+ Two layers after the clips on any Animator, off until added:
157
+ ```js fragment
158
+ const look = npc.anim.addAim({ bones: ['Neck', 'Head'], target: engine.player.root, limit: 70 });
159
+ const feet = engine.player.anim.addFeet(); // feet on stairs and slopes
160
+ ```
161
+ - `set({ weight })` fades over `fade` s; weight 0 leaves the animation pose exactly, `remove()` restores it at once; `target: null` looks ahead.
162
+ - `forward: [x, y, z]` (the last bone's axes): a head facing another axis than the bind pose says.
163
+ - `legs: [[upper, lower, foot], ...]` when it cannot tell the legs by bone name (it throws, listing them).
164
+ - Feet use the character's ground, platforms included (`ground: (x, z, y) => h` overrides); off while it jumps or swims, beyond `far`, or hidden.
154
165
 
155
166
  ## 4. Non-character objects (a dog, a windmill, a door)
156
167
  ```js
@@ -160,28 +171,28 @@ const anim = engine.assets.animate(dog, {
160
171
  states: {
161
172
  idle: { clip: 'Idle' },
162
173
  move: { blend: [{ clip: 'Walk', at: 1 }, { clip: 'Run', at: 5 }], param: 'speed' },
163
- bark: { clip: 'Bark', loop: false, then: 'idle', lock: true }, // one-shot; lock: go() doesn't interrupt it while it plays
174
+ bark: { clip: 'Bark', loop: false, then: 'idle', lock: true }, // one-shot; lock: go() doesn't interrupt it while it plays
164
175
  },
165
- transitions: { '*>idle': 0.4 }, // transition seconds for specific switches
176
+ transitions: { '*>idle': 0.4 }, // transition seconds for specific switches
166
177
  });
167
178
  anim.go('idle');
168
- anim.set('speed', 3); anim.go('move'); // just set the speed every frame
179
+ anim.set('speed', 3); anim.go('move'); // just set the speed every frame
169
180
  anim.action('bark');
170
181
  engine.events.on('anim:end', ({ root, state }) => { if (root === dog) console.log(state, 'finished'); });
171
- anim.dispose(); // no longer needed: stop per-frame updates (call this when deleting the model)
182
+ anim.dispose(); // no longer needed: stop per-frame updates (call this when deleting the model)
172
183
  ```
173
184
  **Gameplay timing never reads the animation**: the mixer advances per frame and `anim:end` is emitted per frame, so dropped frames, fast-forward
174
185
  (step's frameEvery) and a model being torn down when it is far away all make it drift from game time. When an attack lands, cooldowns, recovery and
175
186
  "finish the swing before moving" are timed in fixed steps:
176
187
  ```js
177
- engine.input.action('attack', { label: 'Attack', keys: ['KeyF', 'Mouse0'] }); // no module binds it for you
178
- let t = -1; // seconds since the swing started (-1 = not swinging); put it in a world record if it must be saved
188
+ engine.input.define('attack', { label: 'Attack', keys: ['KeyF', 'Mouse0'] }); // no module binds it for you
189
+ let t = -1; // seconds since the swing started (-1 = not swinging); put it in a world record if it must be saved
179
190
  engine.onFixed(dt => {
180
191
  if (t < 0) { if (!engine.input.pressed('attack')) return; t = 0; }
181
192
  const before = t; t += dt;
182
- if (before < 0.3 && t >= 0.3) hitEnemiesInFront(); // hit check at 0.3 s
183
- if (t >= 0.6) t = -1; // can swing again after 0.6 s
184
- engine.player.anim.sync(t < 0 ? null : 'attack', t); // the animation follows t (the attack state of section 5)
193
+ if (before < 0.3 && t >= 0.3) hitEnemiesInFront(); // hit check at 0.3 s
194
+ if (t >= 0.6) t = -1; // can swing again after 0.6 s
195
+ engine.player.anim.sync(t < 0 ? null : 'attack', t); // the animation follows t (the attack state of section 5)
185
196
  });
186
197
  ```
187
198
  ## 5. Gameplay controls progress: `sync(state, t)`
@@ -192,19 +203,19 @@ alone, so a character's per-frame locomotion cannot override it. `sync(null)` ha
192
203
  state cross-fades like `go()` (the `transitions` table applies).
193
204
  `timing` on the state maps gameplay seconds to clip seconds:
194
205
  ```js fragment
195
- const anim = engine.player.anim; // or engine.assets.animate(model, {...})
206
+ const anim = engine.player.anim; // or engine.assets.animate(model, {...})
196
207
  Object.assign(anim.states, {
197
208
  // gameplay: windup 0-0.16, hit 0.16-0.28, recovery 0.28-0.62. The clip raises the sword until 0.24 s and brings it down by 0.5 s:
198
- attack: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.24], [0.28, 0.5], [0.62, 1]] }, // piecewise linear
199
- roll: { clip: 'Roll', loop: false, timing: 0.62 }, // a number: stretch the whole clip over 0.62 gameplay seconds
209
+ attack: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.24], [0.28, 0.5], [0.62, 1]] }, // piecewise linear
210
+ roll: { clip: 'Roll', loop: false, timing: 0.62 }, // a number: stretch the whole clip over 0.62 gameplay seconds
200
211
  hurt: { clip: 'HitRecieve', loop: false, timing: 0.45 },
201
- death: { clip: 'Death', loop: false }, // no timing: clip seconds = t (clamped at the last frame)
212
+ death: { clip: 'Death', loop: false }, // no timing: clip seconds = t (clamped at the last frame)
202
213
  });
203
- engine.onFixed(() => { // one call site: whatever gameplay is doing decides the pose
214
+ engine.onFixed(() => { // one call site: whatever gameplay is doing decides the pose
204
215
  if (f.dead) anim.sync('death', f.deadT);
205
216
  else if (f.stun > 0) anim.sync('hurt', f.stunMax - f.stun);
206
217
  else if (f.act) anim.sync(f.act.id, f.act.t);
207
- else anim.sync(null); // free: locomotion (idle / walk / run) takes over
218
+ else anim.sync(null); // free: locomotion (idle / walk / run) takes over
208
219
  });
209
220
  ```
210
221
  - Calibrate `timing` once by looking: sync the raw clip (no timing) at a few `t` and watch the weapon hand (`describe()` or a bone's world position);
@@ -215,7 +226,7 @@ engine.onFixed(() => { // one call
215
226
  Use `anim:end` only for presentation (change an expression, play the next clip). Native objects: `anim.mixer` (AnimationMixer), `anim.actions` (clip
216
227
  name -> AnimationAction). Things without a skeleton that only move/rotate as a whole use `engine.timeline.tween`, not an Animator.
217
228
 
218
- Footsteps: `engine.events.on('character:step', ({ character }) => ...)` hears each foot come down (`character.groundType()` is what it stepped on), and `character:land` each landing; the engine's own footstep sound listens the same way, so yours adds to it. Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
229
+ Footsteps: `engine.events.on('character:step', ({ character }) => ...)` hears each foot come down (`character.groundType()` is what it stepped on), and `character:land` each landing; the engine's own footstep sound listens the same way, so yours adds to it. Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose (IK included: a bone written here keeps the game's value) is
219
230
  applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
220
231
 
221
232
  ## 6. Verify
@@ -1,13 +1,16 @@
1
1
  # Custom module
2
2
 
3
- **In this recipe**: 1. Template (example: stamina, in the game as `stamina.js`) · Type: what the module may own · 2. Hooks and order cheat sheet · 3. Extra steps when it goes into the engine · 4. Verify
3
+ > **Covers:** a module of your own: template, what it may own, hooks and order, what it must clean up.
4
+ > **Use when:** a mechanic with its own state, per-frame logic and saving.
5
+ > **Shortest:** `export const stamina = () => ({ name: 'stamina', install(e, ctx) { … } })`.
6
+ > **Sections:** 1 Template example stamina · Type what the module · 2 Hooks and order · 3 Extra steps when · 4 Verify
4
7
 
5
8
  When to write a module: a "mechanic" that has its own state, per-frame logic and saving (stamina, a heat meter, wave spawning, oxygen, a combo
6
9
  counter). The contracts every module should follow (state, game time, skip, describe, ops) and a second copyable module are in
7
10
  `49-game-module-contract.md`; this page is the template and the hook cheat sheet. A module is a file of your game (next to `main.js`, or in `plugins/`);
8
11
  keep art and text out of its code (style values, `i18n`) so it can go to another game through your asset library (`threedog lib add`).
9
12
 
10
- **A whole system to reuse.** A folder `systems/<name>/` with a `system.json` (`{ "summary", "module", "plug", "requires", "entries", "content", "text" }`) carries the module, its content piece, its words and its tests (`tests/*.mjs`, game specs) as one unit: fishing, a day-night shop, wave spawning, tides. `threedog lib add systems/fishing --kind system` refuses colors, art files and text in the code and a `requires` left out of `system.json`, then proves an entry with tests by pulling it into an empty game and running them (`--no-proof` skips that). `threedog lib pull fishing` puts it in `systems/fishing/`, writes its wiring file in `plugins/`, puts its tests in `tests/specs/` and merges its content in `content/index.js`.
13
+ **A whole system to reuse.** A folder `systems/<name>/` with a `system.json` (`{ "summary", "module", "plug", "requires", "entries", "content", "text" }`) carries the module, its content piece, its words and its tests (`tests/*.mjs`, game specs) as one unit: fishing, a day-night shop, wave spawning, tides. `threedog lib add systems/fishing --kind system` refuses colors, art files and text in the code and a `requires` left out of `system.json`, then proves an entry with tests by pulling it into an empty game and running them (`--no-proof` skips that). `threedog lib pull fishing` puts it in `systems/fishing/`, writes its wiring file in `plugins/`, its tests in `tests/specs/` and merges its content into `content/index.js`.
11
14
 
12
15
  ## 1. Template (example: stamina, in the game as `stamina.js`)
13
16
  ```js
@@ -16,7 +19,7 @@ import { readParams } from 'threedog';
16
19
 
17
20
  export function stamina(opts = {}) {
18
21
  const PARAMS = { max: { type: 'number', default: 100 }, drain: { type: 'number', default: 20 }, regen: { type: 'number', default: 10 } };
19
- const { max, drain, regen } = readParams('stamina', PARAMS, opts); // a misspelled option throws in dev with the fix (a release build warns once), a wrong type or a missing required option throws in every build; put PARAMS on the module as params to show it in engine.catalog()
22
+ const { max, drain, regen } = readParams('stamina', PARAMS, opts); // a misspelled option throws in dev with the fix (a release build warns once), a wrong type or a missing required option throws in every build; put PARAMS on the module as params to show it in engine.catalog()
20
23
  let e = null, ctx = null, tired = null, shown = -1;
21
24
  const api = {
22
25
  value: max, max,
@@ -24,25 +27,25 @@ export function stamina(opts = {}) {
24
27
  restore(n) { api.value = Math.min(max, api.value + n); },
25
28
  };
26
29
  return {
27
- name: 'stamina', type: 'rules', label: 'Stamina', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
30
+ name: 'stamina', type: 'rules', label: 'Stamina', requires: ['characters'], optional: ['hud'], stage: 'gameplay', // once installed, engine.stamina === api
28
31
  install(engine, c) {
29
- e = engine; ctx = c; // what the module adds through ctx leaves with it (uninstall, replaces, a rolled-back use)
30
- e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } }); // don't hard-code UI text
31
- e.saves.register('stamina', { save: () => api.value, load: v => { if (typeof v === 'number') api.value = v; } });
32
+ e = engine; ctx = c; // what the module adds through ctx leaves with it (uninstall, replaces, a rolled-back use)
33
+ e.i18n.add({ 'zh-CN': { 'stamina.label': '体力' }, en: { 'stamina.label': 'Stamina' } }); // don't hard-code UI text
34
+ e.saves.define('stamina', { save: () => api.value, load: v => { if (typeof v === 'number') api.value = v; } });
32
35
  return api;
33
36
  },
34
- fixed(dt) { // timing and value changes go in fixed (60 Hz, doesn't run while paused)
37
+ fixed(dt) { // timing and value changes go in fixed (60 Hz, doesn't run while paused)
35
38
  const p = e.player; if (!p) return;
36
39
  api.value = p.state === 'run' ? Math.max(0, api.value - drain * dt) : Math.min(max, api.value + regen * dt);
37
40
  // no stamina: run speed = walk speed. A modifier, not a write to p.runSpeed: the base stays the game's, and haste / mud entries still combine
38
- if (api.value <= 0 && !tired) tired = ctx.mod('move.runSpeed', { id: 'player', set: p.speed }); // owner: the module
41
+ if (api.value <= 0 && !tired) tired = ctx.mod('move.runSpeed', { id: 'player', set: p.speed }); // owner: the module
39
42
  else if (api.value > 0 && tired) { tired.remove(); tired = null; }
40
43
  },
41
- frame() { // UI goes in frame; update only when the value changed (hud.bar redraws on every call)
44
+ frame() { // UI goes in frame; update only when the value changed (hud.bar redraws on every call)
42
45
  const v = Math.round(api.value);
43
46
  if (v !== shown) { shown = v; e.hud?.bar('stamina', { value: v, max, label: e.t('stamina.label') }); }
44
47
  },
45
- describe() { return { value: Math.round(api.value), max }; }, // this becomes describe().stamina
48
+ describe() { return { value: Math.round(api.value), max }; }, // this becomes describe().stamina
46
49
  };
47
50
  }
48
51
  ```
@@ -93,16 +96,16 @@ A module that does two kinds of thing is two definitions returned together (`wea
93
96
  - The `type` decides what an error does: in a `picture` or `ui` module (gameplay works without it) an error in a hook only switches that module off
94
97
  (`module:disabled`, listed in `describe().disabledModules`); in any other type it freezes the game in development/tests and is recorded in `engine.error`.
95
98
  - `requires` means the provider works, not only that it is installed: until a required provider runs, the module is `'blocked'` in `engine.explain({ module })` (no init, no hooks) and `engine.catalog(name).blockedBy` says on what. If it can live without the provider, list it in `optional` instead. A `critical` module blocked by a failure stops `start()`.
96
- - Whatever the module registers goes through `ctx`: `ctx.ops.define`, `ctx.saves.register`, `ctx.ui.define`, `ctx.stream.addReadyCheck`, `ctx.budget.metric`, `ctx.things.addSource` / `explainWith`,
99
+ - Whatever the module registers goes through `ctx`: `ctx.ops.define`, `ctx.saves.define`, `ctx.ui.define`, `ctx.stream.addReadyCheck`, `ctx.budget.metric`, `ctx.things.addSource` / `explainWith`,
97
100
  `ctx.ground.provide` / `addColliders`. They take the same arguments as the engine call, and `engine.catalog(name).resources` lists them. They leave with the module, so `engine.unuse` then
98
101
  `engine.use` of the same module works; a save part's data stays in the save and goes back to the part when it registers again.
99
102
  - Listeners and timers the module adds go through `ctx.track(...)`: `ctx.track(e.events.on('item:add', fn))`, also `onFixed` / `onFrame` /
100
103
  `clock.after` / `audio.measure` / a `makeWindow` window, anything with `remove()`. They leave with the module: when its `engine.use(...)` batch
101
104
  rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook (the spec `threedog test "Lifecycle: every built-in"`
102
105
  checks every engine module). A class the module builds takes `ctx` as a constructor argument. DOM listeners use
103
- `addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`); scene GPU memory,
104
- jobs and stream entries are collected by `engine.dispose()`. The `dispose(e)` hook only collects what the core can't, such as Workers, the
105
- physics world, WASM objects and real-time timers, and is called in reverse install order.
106
+ `addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`); jobs and stream
107
+ entries are collected by `engine.dispose()`; scene GPU memory is its creator's: `engine.dispose()` does not free the meshes, materials and textures you made, so track their removal: `ctx.track({ remove: () => engine.remove(mesh) })` (`engine.remove` disposes geometry and materials, not their textures: three's `material.dispose()` leaves its maps, so dispose a texture you made when nothing uses it). The `dispose(e)`
108
+ hook frees the rest (Workers, the physics world, WASM objects, real-time timers), in reverse install order.
106
109
  - Your data in a replaceable provider: `ctx.feeds('collision', () => addMyWalls())` runs before the `use()` of a new holder returns.
107
110
  - Foundation slots are the ones a running game cannot swap: `world` alone, because it owns every record. Choose your own holder before `start()`; every other slot takes `replaces` at any time.
108
111
  - A module's changes to shared values go through `ctx.mod(point, { mul: 0.8, layer: 'effect' })` (= `ctx.track(e.mod(point, { owner: ctx.name, ... }))`),
@@ -118,10 +121,10 @@ A module that does two kinds of thing is two definitions returned together (`wea
118
121
  - Saved state the module writes joins the ops guard (experimental): `e.ops.guard('stamina.set')` in each writing method (a no-op in production builds,
119
122
  no DEV check needed), `e.ops.allow(fn)` around writes that are allowed anyway (recipe 23 section 5).
120
123
  - **Per-playthrough state** is a save part: whatever changes during play and matters for what happens next (a zone's `once` / cooldown, a
121
- transition's progress, a hand-picked music track, a check timer, markers an effect placed) goes in `e.saves.register(...)`. The engine calls it
124
+ transition's progress, a hand-picked music track, a check timer, markers an effect placed) goes in `e.saves.define(...)`. The engine calls it
122
125
  on all three paths: save, load, and new game (a new game loads the state captured when `start()` finished), so there is nothing to reset by
123
- hand. What cannot be saved ends with its playthrough: a background result goes through `engine.commits` (a load or new game drops old ones;
124
- keep `e.commits.epoch` on a queued request and drop it when that changed), and an effect of a running playthrough (an open dialogue, a
126
+ hand. What cannot be saved ends with its playthrough: a background result goes through `ctx.commits` (a load or new game drops old ones;
127
+ keep `ctx.commits.epoch` on a queued request and drop it when that changed), and an effect of a running playthrough (an open dialogue, a
125
128
  running cutscene, the music playing) stops on `ctx.track(e.events.on('session:end', ...))`. What is derived from save parts is rebuilt on
126
129
  `'session:start'` and `'save:loaded'`, and what a rollback took down on `'session:failed'`. A `'session:end'` listener only stops things: it starts nothing for the next state. A module's `describe()` should show such state: the session spec (`threedog test "session fresh page"`) compares `describe()` after a new game with a fresh page, and the Lifecycle spec round-trips the engine's own.
127
130
  - When you only need a per-frame callback and no module structure: `const h = engine.onFrame(dt => ...)` / `engine.onFixed`, and `h.remove()` cancels it.