threedog 0.8.0 → 1.0.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 (372) hide show
  1. package/CHANGELOG.md +219 -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
@@ -4,7 +4,7 @@
4
4
 
5
5
  Needs the module `flow()` (not in openWorld; add it yourself: `engine.use(openWorld({ camera: 'follow', ...}), flow())`).
6
6
  - **Flow states**: title, playing (built-in `playing`), paused (built-in `paused`: freezes gameplay + locks input), ending, ... Only one is active at a time.
7
- - **Scene transition** `transition(fn)`: lock input -> fade to black -> fade music out -> (with `{ autosave: 'auto' }` save slot 'auto'; off by
7
+ - **Scene transition** `transition(fn)`: lock input -> fade to black -> fade music out -> (with `{ autosave: 'auto' }` save slot 'auto'; off by If the world does not settle within `engine.loading.timeoutMs`, it rejects with `module-not-ready` and gives the screen and input back. Autosave waits for the end of a transition.
8
8
  default) -> run fn -> wait until every module is ready -> fade in -> unlock. Repeated calls queue up automatically.
9
9
 
10
10
  ## 1. Pause / title / ending (in main.js)
@@ -34,9 +34,14 @@ state when the menu closes; without flow it calls `engine.freeze('settings')` di
34
34
  Stopped while frozen: the fixed step (movement, physics), module `fixed`, the game clock `clock`, quest checks (they run in the fixed step), timeline
35
35
  `wait` / tweens / camera / paths. Still running: rendering, UI, `onFrame`, the fade-to-black `fadeScreen`.
36
36
 
37
- Restarting a run from a UI button (retry, "play again"): do not reset positions, health and spawns inside the click handler or an `onFrame` callback; that is
38
- mid-frame and can leave half the world on the old tick. Apply it on a fixed tick: `engine.nextFixed(resetRun)`
39
- (runs at the start of the next fixed step, in a stable order), or set a flag in the handler and reset in `onFixed`.
37
+ Restarting a run from a UI button (retry, "play again"): a whole new run is `engine.session.newGame()`; it works from a frozen screen too, and flow goes to `'playing'` by itself.
38
+ To reset only part of the run, do not write positions, health and spawns inside the click handler or an `onFrame` callback; that is mid-frame and can leave half the world on the old tick.
39
+ Apply it on a fixed tick with `engine.nextFixed(fn)` or a flag read in `onFixed`. No fixed step runs while frozen, so on an end screen with `freeze: true` leave the freeze first:
40
+ ```js
41
+ engine.flow.define('gameOver', { freeze: true, lockInput: true });
42
+ const resetRun = () => engine.vars.bump('tries', 1); // the game's own reset: positions, health, spawns
43
+ const retry = async () => { engine.flow.go('playing'); await engine.nextFixed(resetRun); }; // this order: frozen, nextFixed never fires
44
+ ```
40
45
 
41
46
  ### Back key (Esc): the UI focus stack
42
47
  Windows (inventory, quests, settings), dialogue and cutscenes are pushed onto the stack in the order they open (`uiFocus(engine)` in `ui/Focus.js`),
@@ -58,7 +63,7 @@ already showing. The title's buttons go through `engine.session` (section 4): a
58
63
  To open straight into play, pick the start state up front instead of leaving the title afterwards; time and weather come from the engine's
59
64
  own URL keys (`?time=22:20&weather=storm`, applied after `engine:ready`, weather at once, then `wait` seconds are advanced), so only the game's
60
65
  own state needs a key of its own.
61
- ```js
66
+ ```js fragment
62
67
  const q = new URLSearchParams(location.search), moment = q.get('moment'); // the game's own key: which lamps are lit, the score ...
63
68
  engine.use(openWorld({ camera: 'follow' }), flow({ start: moment ? 'playing' : 'title' }));
64
69
  engine.flow.define('title', { freeze: true, lockInput: true,
@@ -83,7 +88,7 @@ advances only on `engine.step`, so a `weather.set(name, { seconds: 0.1 })` made
83
88
  color is one frame old (share `engine.uniforms.uSkyHorizon` instead, recipe 08).
84
89
 
85
90
  ## 2. Changing scene / teleporting
86
- ```js
91
+ ```js fragment
87
92
  // A level-based game: switch to another map
88
93
  await engine.flow.transition(async () => {
89
94
  await engine.level.load('/models/town2.glb'); // or a name from the assets manifest
@@ -94,15 +99,14 @@ await engine.flow.transition(async () => {
94
99
  // Teleport within the same map: no save, music keeps playing
95
100
  engine.flow.transition(() => engine.player.placeAt([40, 0, -20]), { music: 'keep' });
96
101
  ```
97
- When the level changes, the old level's things are cleared automatically: trigger zones built by `triggers.fromMarkers`, and pickups / trigger zones /
98
- props in content whose position uses a level marker.
99
- An NPC like that is not deleted: its data (in `engine.world`, with zone = level name) stays and only the model is removed; it is rebuilt automatically
102
+ When the level changes, trigger zones built by `triggers.fromMarkers` are cleared automatically. NPCs, pickups and props in content whose position uses a level
103
+ marker are not deleted: their data (in `engine.world`, with zone = level name) stays and only the model is removed; it is rebuilt automatically
100
104
  when you return to this map, with its state intact.
101
105
  Things the game builds itself that belong to this map are registered with `engine.level.track(handle)` (`{ remove() }`) and deleted together when the
102
106
  map changes.
103
107
  Loading a save across levels: the save records the level name, so `await engine.saves.load('slot1')` first switches back to that map, waits for it to
104
- finish loading, and then puts the player and everything else back (the level must be loaded by name, `level({ url })`; a code-built `level({ scene })`
105
- can't be recorded).
108
+ finish loading, and then puts the player and everything else back. The level must be loaded by name, `level({ url })`. For an area built in code that name
109
+ is a builder in the assets manifest (recipe 66, "Two areas built in code"); a `level({ scene })` object has no name to record.
106
110
 
107
111
  Saves live in the browser's IndexedDB (falling back to localStorage, with one notice). `save()` / `remove()` / `load()` return a Promise (a failed write shows a notice), while
108
112
  `list()` / `export()` are synchronous (saves are read into memory at startup). Attachments, file backup and `storageKey`: `../api/saves.md`.
@@ -136,21 +140,20 @@ engine.input.action('menuConfirm', { label: 'OK', keys: ['Space'], context: 'men
136
140
  whether input is locked.
137
141
  - In tests: after `engine.flow.go('paused'); engine.step(1)` the player position, `engine.clock.now`, quest progress and timelines are unchanged;
138
142
  after `await engine.flow.transition(fn)` returns, `transitioning` is false (if fn throws, the error goes to the caller and the screen still fades back in).
139
- - Related tests: `threedog test 游戏流程`, `threedog test 接缝`.
140
143
 
141
144
  ## 4. New game / continue / back to title / retry (engine.session)
142
145
  Every playthrough starts from a clean slate, so a second new game is exactly like the first:
143
- ```js
146
+ ```js fragment
144
147
  await engine.session.newGame(); // the state right after start(): world, containers, vars, quests, clock, sky, weather, random
145
148
  await engine.session.load('slot1'); // continue (title "Continue", settings "Load"); retry: engine.session.load('checkpoint')
146
149
  await engine.session.quit(); // back to the title (settings "Back to title"); the title's Start calls newGame
147
150
  engine.session.track(engine.events.once('npc:talk', onTalk)); // anything the game adds during play: removed when the playthrough ends
148
151
  ```
149
- Ending a playthrough skips a running cutscene, removes tracked handles, drops clock timers added after start(), drops background results not yet
152
+ Ending a playthrough drops a running cutscene, removes tracked handles, drops clock timers added after start(), drops background results not yet
150
153
  applied (commits), stops the music, applies the start state and snaps the camera to the player. flow goes back to its start state, then to
151
154
  `'playing'`. Events: `session:end`, `session:start { kind: 'new' | 'load', slot? }` (play an intro per new game there, not on `engine:ready`).
152
155
  - When a save part's `load()` throws, newGame / `session.load` resolve `false` and the old playthrough goes on: its data is rolled back, its
153
- tracked handles and timers stay, flow returns to the state it left, and `session:failed { kind, slot? }` fires instead of `session:start`.
156
+ tracked handles and timers stay, flow returns to the state it left, and `session:failed { kind, slot? }` fires instead of `session:start` (also from a rolled-back `saves.load` or `saves.apply`, with `kind: 'quick'`) (for a quit: instead of the title, kind 'quit').
154
157
  - `saves.load(slot)` is a quick load onto the running playthrough (keeps what the game added); `session.load(slot)` ends the playthrough first and
155
158
  refuses an unreadable save without touching the game. Deleting a save is `saves.remove(slot)`.
156
159
  - Listeners and hooks registered at boot stay (they are the game); register play-time ones with `session.track`.
@@ -5,7 +5,7 @@
5
5
  Modules: `sky()` (draws the dome from `engine.calendar`, sun and moon, and computes the signals; it writes no light, fog or exposure, those are your `picture/` code, recipe 62; the time itself is `calendar()`, recipe 06), `weather()` (the game's weather types, smooth transitions, rain and snow,
6
6
  lightning; their picture is `weather({ rain, snow, lightning })`, recipe 44). The engine has only a neutral fallback.
7
7
 
8
- ```js
8
+ ```js fragment
9
9
  engine.use(sky({ keyframes: ROWS, sunSize: 600, clouds: { coverage: 0.6 }, dim: { stars: false } })); // start values
10
10
  engine.uniforms.uSunBrightness.value = 4; // sun, moon, star and dome cloud numbers: engine.uniforms, the dome's own objects, on both renderers
11
11
  engine.uniforms.uCloudCover.value = 0.8; // also uSunSize uSunGlow uMoonSize uMoonBrightness uMoonColor uStars uStarScale uSkyCurve uSkyCloudScale uSkyCloudSpeed uCloudOpacity uCloudSoft uCloudColor uCloudShade
@@ -70,7 +70,7 @@ Time of day still reaches it through `engine.uniforms` (`uSunDir`, `uDaylight`,
70
70
  ```js
71
71
  engine.weather.set('rain', { seconds: 20 }); // transition to rain over 20 seconds (a type of the game's table, see 2)
72
72
  engine.weather.set('storm', { seconds: 0 }); // at once: the full storm before the next step (a screenshot or test right after the call)
73
- engine.weather.setAuto(true); // change weather at random (openWorld({ camera: 'follow', autoWeather: true }) also works)
73
+ engine.weather.auto = true; // change weather at random (openWorld({ camera: 'follow', autoWeather: true }) also works)
74
74
  engine.events.on('weather:lightning', () => { /* thunder */ });
75
75
  engine.events.on('weather:change', ({ from, to }) => { /* once per change of name, when the blend starts; set() with the same name again does not fire */ });
76
76
  ```
@@ -79,7 +79,7 @@ engine.events.on('weather:change', ({ from, to }) => { /* once per change of nam
79
79
  `weather({ types })` is the whole list of the game's weather; without it there is only a calm `clear` (the engine assumes no climate). Seven temperate
80
80
  ones (clear cloudy overcast rain storm snow fog) are an opt-in preset: `weather(presets.weather.temperate)`; extend with
81
81
  `types: { ...presets.weather.temperate.types, dust: {...} }`.
82
- The preset supplies types and an `autoPool`; the weather changes by itself only with `auto: true` (or `engine.weather.setAuto(true)`). To pin one
82
+ The preset supplies types and an `autoPool`; the weather changes by itself only with `auto: true` (or `engine.weather.auto = true`). To pin one
83
83
  for a picture: `engine.weather.set('clear')`, or a shot's `--weather clear` (it also turns `auto` off); a shot prints the weather under the picture.
84
84
  Left-out fields are calm (no cloud, rain, snow, grey, lightning; sun, fog, wind 1). There is no patch option for one field
85
85
  of a preset type: spread that one type, `const T = presets.weather.temperate.types; weather({ types: { ...T, rain: { ...T.rain, fog: 0.5 } } })`.
@@ -185,7 +185,7 @@ In scope: the GLSL noise helpers `float threedogHash(vec2 p)` and `float threedo
185
185
  the patch's `uniforms` (declared for you; number, `THREE.Color`, `THREE.Vector2/3/4`, array of 2-4 numbers, or `THREE.Texture`). Change one later
186
186
  with `engine.sky.uniforms.uEdge.value = 0.1` (both renderers). A bad `kind`, GLSL without the function, or an unsupported uniform value throws with the fix.
187
187
  Flat painted cloud blobs with a hard edge, multiplied by a texture:
188
- ```js
188
+ ```js fragment
189
189
  // sky({ clouds: { color: 0xfff1dc, shade: 0x9aa8c4 } }) gives lit and shade; the function goes through the hook
190
190
  engine.sky.clouds({ uniforms: { uPaper: paperTexture, uEdge: 0.06 }, // paperTexture: any THREE.Texture, repeat wrapping
191
191
  glsl: `vec4 threedogClouds(vec3 d, float time, vec3 sunDir, float night, vec3 lit, vec3 shade, float cover){
@@ -214,7 +214,7 @@ renamed (`threedogSkyLayer0`, `1`, ...), so layers from different parts of the g
214
214
  ## 10. Flat backdrop: no horizon at all
215
215
  For a scene that should have no horizon (a menu stage, a board game, a diorama):
216
216
  ```js fragment
217
- sky: { backdrop: 0xefebe4 }, // one color
217
+ sky({ backdrop: 0xefebe4 }); // one color
218
218
  engine.sky.backdrop = engine.sky.isDay ? 0xefebe4 : 0x2c3346; // live, from your own frame code; null gives the dome back
219
219
  ```
220
220
  - Hides the dome (no gradient, horizon line, sun / moon disk, stars or clouds) and sets `scene.background` to the color. A plain background
@@ -67,7 +67,7 @@ recompile). In dev the console warns (code `light-recompile`) when programs were
67
67
  For many torches, street lamps, campfires, muzzle flashes or neon signs use the light pool: a fixed number of real lights, created once at install,
68
68
  moves to the sources that matter most (near the camera, bright, high `priority`) and fades with intensity, so the light setup never changes. Install
69
69
  it before `engine.start()` so the startup compile covers its lights:
70
- ```js
70
+ ```js fragment
71
71
  import { lightPool } from 'threedog';
72
72
  engine.use(lightPool({ point: 8 })); // 8 PointLights; lightPool({ spot: 2, shadows: 1 }) adds spots / lets one point light cast
73
73
  for (const t of torches) engine.lightPool.add(t, { // an Object3D is followed; a position stays put
@@ -120,7 +120,7 @@ rules, `fonts` lists font asset names to load at start (the files sit in an asse
120
120
  ## 2. Using your own models instead of procedural ones
121
121
  Models are assets: content names them, an asset pack maps the names to files or generators. Register a later manifest with the same
122
122
  name to swap one:
123
- ```js
123
+ ```js fragment
124
124
  engine.assets.manifest(yourAssets); // assets from an asset pack you have: trees, rocks, flowers... built in code
125
125
  engine.assets.manifest({ name: 'mine', models: { pine: () => myPineGeometry(), well: '/models/well.glb' } }); // replaces pine, adds well
126
126
  ```
@@ -147,7 +147,7 @@ GLB files from Blender are copied the same way and checked with recipe 46 sectio
147
147
 
148
148
  ## 2b. Wind, cloud shadows and season tint on your own materials
149
149
  The engine's shader effects are named patches that work on any material that has the usual three.js chunks (WebGL only):
150
- ```js
150
+ ```js fragment
151
151
  import { applyEffects } from 'threedog';
152
152
  const leaves = applyEffects(new THREE.MeshToonMaterial({ color: 0x5a8a3a }), { wind: 0.03, season: 'foliage' }); // clouds default on
153
153
  engine.vegetation.define('bush', { geometry, material: leaves }); // vegetation adds them itself; effects: false keeps the material untouched
@@ -18,8 +18,8 @@ Export glTF/GLB (tick "Custom Properties") into `art/models/` (create it if miss
18
18
  hierarchy are kept; faces are not reduced. Only changed files are processed; `-- --force` redoes everything.
19
19
 
20
20
  ## 3. Putting it in the game (main.js)
21
- ```js
22
- import { createEngine, presets, level, collision, followCamera, characters, interactions, dialogue, triggers, content, hlod } from 'threedog';
21
+ ```js fragment
22
+ import { presets, level, collision, followCamera, characters, interactions, dialogue, triggers, content, hlod } from 'threedog';
23
23
  engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(), interactions({ ...presets.interactions.nearest }), dialogue(), triggers(), content(), hlod());
24
24
  engine.events.once('level:loaded', () => { // once: level:loaded fires again on every level change
25
25
  engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: engine.level.spawn });
@@ -47,7 +47,7 @@ engine.start();
47
47
  Without `terrain()`, `vegetation()` grows on its own chunks over whatever provides the ground: the level, a code-built ground (`engine.setGround`), or
48
48
  the flat default. Rules read `engine.surface / slope / groundType`, so pick the level's surfaces by ground type (a mesh's `groundType` custom
49
49
  property, else its material name) with `rule.biomes`, and limit the scatter with `area`:
50
- ```js
50
+ ```js fragment
51
51
  engine.use(level({ url: '/models/town.glb' }), vegetation({ area: { min: [-80, -80], max: [80, 80] }, viewChunks: 3 }), collision());
52
52
  engine.vegetation.define('grass', { geometry: grassGeo, nearOnly: true, rule: { perChunk: 500, biomes: { lawn: 1 } } });
53
53
  engine.vegetation.define('tree', { model: oak, rule: { perChunk: 6, biomes: { lawn: 0.6, park: 1 }, maxSlope: 0.4, collider: 0.4 } });
@@ -59,7 +59,7 @@ sets `minHeight / maxHeight`. Content `vegetation` works the same way. With `ter
59
59
  distance are terrain options). Rapier (`rigid()`) bodies collide with them too (cylinders from `engine.ground.forEachCollider`, gone when felled).
60
60
 
61
61
  Where a species grows is decided in the same `define()` call, with up to three parts (on a level, a code-built ground or terrain alike):
62
- ```js
62
+ ```js fragment
63
63
  // rule: random scatter per chunk (above). positions: the game's own spots instead, [x, z] or [x, z, scale, yaw], planted at the ground height
64
64
  engine.vegetation.define('hedge', { model: hedge, positions: hedgeSpots /* [[x, z], ...] from your level data */, rule: { collider: 0.5 } });
65
65
  // densityMap: thins the rule's or the positions' result, 0..1 per spot -- a function of game data, or a gray image with the heightmap keys
@@ -76,3 +76,15 @@ A game that wants every instance under its own code still builds a plain `THREE.
76
76
  (`kind: 'trigger'`) and NPCs.
77
77
  Text version: `npm run shot -- /your-page.html --describe-only`.
78
78
  - Collision: `engine.collision.walkable({ x, z })` is false inside a col_ box; ground: `engine.surface(x, z)` equals the step / floor height.
79
+
80
+ ## 6. A level and a terrain together
81
+ Each takes the ground slot on its own, so installing both is refused. `compositeGround` holds the slot and asks one of them per point:
82
+ ```js fragment
83
+ engine.use(terrain({ part: true }), level({ scene: town, part: true }),
84
+ compositeGround({ parts: [{ of: 'level', region: (x, z) => x >= -30 && x <= 34 && Math.abs(z) <= 20, priority: 1 }, { of: 'terrain' }] }));
85
+ ```
86
+ - `region` is omitted (everywhere), `(x, z) => boolean`, or `{ volume }`, the same `{ contains({ x, y, z }) }` water and trigger zones take (asked at `y` 0). Higher `priority` wins where regions overlap.
87
+ - A region has no height: everything above and below a point belongs to one part. A cellar under a hillside goes in the level, and the level's mesh carries the ground over it too.
88
+ - The navmesh is built from the level parts only. Outside them paths use A*.
89
+ - Physics follows the regions: `rigid` gets terrain triangles only where the terrain answers, so a hill under a level's region is not solid. It is still drawn; lower it there or keep it out of sight.
90
+ - Water over a room: a character, `describe()` and floating bodies ask `waterAt` at their own height, so `addWaterBody({ query })` returning `null` below a lake's bed leaves the room under it dry. A plain `radius` or `halfWidth` body has no bottom and counts at every height.
@@ -40,7 +40,7 @@ Rigid bodies and vehicles do not change a model's shadow settings: set `mesh.cas
40
40
  it doesn't compete with jumping) brakes, and without one the engine warns once; press E again to exit.
41
41
  - Saving: the player save records which vehicle the player is in (its `id`); loading an on-foot save while driving exits the vehicle first, and
42
42
  loading a driving save puts the player back in the car.
43
- - Code: `engine.player.enter(v)`, `engine.player.exit()`; `engine.player.vehicle` is the vehicle being driven (null when on foot); `v.driver` is who is driving, `v.passengers` who rides, `character.seat` the seat (0 drives; a second `enter` takes a free passenger seat, which does not steer).
43
+ - Code: `engine.player.enter(v)`, `engine.player.exit()` (takes the first walkable exit of `exitPosition(seat, n)`; none: answers `false` and the rider stays, `exit({ force: true })` always gets out); `engine.player.vehicle` is the vehicle being driven (null when on foot); `v.driver` is who is driving, `v.passengers` who rides, `character.seat` the seat (0 drives; a second `enter` takes a free passenger seat, which does not steer). Placing a rider (`placeAt`, a teleport, a write to its record's position) ends the ride, as `exit()` does; to take it along, move the vehicle.
44
44
  - NPCs/scripts driving: `v.drive(throttle -1..1, steer -1..1 (right is positive), brake 0-1)`; the last values set are used on every fixed step.
45
45
  - Events: `vehicle:enter`, `vehicle:exit` (`{ character, vehicle }`). Removal: `v.remove()` (anyone inside exits first; the model stays,
46
46
  `engine.remove(car)` deletes it).
@@ -68,7 +68,7 @@ velocities and sleep, and a load gives that state back to the body with the same
68
68
  **Joints** (hinges, doors, ropes, chains) are plain Rapier on engine bodies; the engine has no wrapper. `R.world` is the Rapier world and `entry.body` the Rapier body. newGame and a load rebuild the physics world (physics starts over like a fresh
69
69
  page) and free the old world's joints with it; the engine does not copy them. It emits `rigid:rebuilt` once the bodies are back, and that is
70
70
  where a game re-creates its joints, with the same code that made them:
71
- ```js
71
+ ```js fragment
72
72
  const R = engine.rigid, J = R.rapier.JointData;
73
73
  const post = R.addBox(postMesh, { fixed: true }), door = R.addBox(doorMesh, { mass: 8 });
74
74
  function hang() { // makes the joints; called after the bodies are added, and again after every rebuild
@@ -98,17 +98,28 @@ stay). Removing a body removes its joints (Rapier does that).
98
98
 
99
99
  ## 3b. Ragdoll (experimental)
100
100
 
101
- ```js
101
+ ```js fragment
102
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()); // back to animation where the body lies; a get-up clip is yours to play
103
+ engine.clock.after(4, () => rd.remove(), { channel: 'real' }); // back to animation where the body lies; a get-up clip is yours to play
104
104
  ```
105
105
  - **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
106
  Parts: `hips chest head upperArmL lowerArmL upperArmR lowerArmR upperLegL lowerLegL upperLegR lowerLegR`.
107
107
  - **Limits** are `[min, max]` radians from the bind pose, per part or kind: `{ limits: { lowerLeg: { bend: [0, 2] } } }`. `bend` is forward (a knee: backward), then `side` and `twist`.
108
108
  - **The bones stay plain three.js.** Each fixed step writes rotations, and hips' position only, so bones keep their length. Attach things with `character.onPose`. Once `rd.settled`, nothing is written and your bone writes stay. Hands, feet and bones between parts keep their pose.
109
- - **One owner.** While limp, control is held on the layer `physics` (recipe 57), the animator writes nothing, the capsule is off, the camera follows the hips, `state` is `'ragdoll'` and `root` follows the body. `remove()` gives each back; a camera you moved stays moved. In a vehicle it throws: `exit()` first. `remove()` before `placeAt`. A mixer you made yourself is yours to stop.
109
+ - **One owner.** While limp, control is held on the layer `physics` (recipe 57), the animator writes nothing, the capsule is off, the camera follows the hips, `state` is `'ragdoll'` and `root` follows the body. `remove()` gives each back; a camera you moved stays moved. In a vehicle it throws: `exit()` first. `placeAt`, or a write to its record's position, carries the whole body there at rest, still limp. A mixer you made yourself is yours to stop.
110
110
  - **Physics.** One rigid body per part (`rd.parts.head.body`; ray hits carry the bone in `object`), so buoyancy and ground freezing apply. Parts do not collide with each other, nor ragdolls with one another.
111
111
  - **Not saved.** A load or new game ends it. A world rebuild without a load keeps it and re-creates its joints on `rigid:rebuilt`. Deleting the character frees everything.
112
+ - **Collision on three axes.** `engine.collider3d` is the slot rigid holds: `addSolid({ position, size | radius, rotation })` puts a fixed solid at any tilt, `overlap(position, radius)` and `sweep(from, to, radius)` answer for a flying mover or a path source. `engine.collision` does not know these solids, so walkers on the simple mover pass through. A game's own provider passes `modules/rigid/collider3d.contract.js` and takes the slot with `engine.use(mine(), { replaces: 'collider3d' })`.
113
+ - **Not a human.** The rule `ragdoll.graph` says what the parts are. The default `'humanoid'` is a physics helper that reads the 11 parts from bone names, not a choice of body for your game; every other body plan passes its own graph, one part without a parent, the rest hanging from it:
114
+ ```js
115
+ engine.mod('ragdoll.graph', { owner: 'game', id: 'wolf', set: {
116
+ body: { bone: 'Spine', mass: 20 },
117
+ head: { bone: 'Head', parent: 'body', mass: 4 },
118
+ legFL: { bone: 'FrontL', parent: 'body', kind: 'leg', forward: [0, 0, 1] },
119
+ tail: { bone: 'Tail1', parent: 'body', limits: { bend: [-1, 1], side: [-1, 1] } },
120
+ } });
121
+ ```
122
+ Without `id` it covers every body; a function `(facts, engine) => graph` picks per body; `false` makes `ragdoll()` return null.
112
123
  - **Left out:** partial or blended ragdoll (an arm thrown by a hit while the rest animates); `remove()` cuts to the animation.
113
124
 
114
125
  ## 4. Verify
@@ -117,4 +128,5 @@ engine.clock.after(4, () => rd.remove()); // back to animation where the body
117
128
  player stands outside the door.
118
129
  - Vehicle speed is only in the object form `engine.describe().player.vehicle` (the player line of describeText does not show it);
119
130
  `describe().player.mover` and `grounded` are there too.
120
- - Related test: `threedog test 载具` (test page in the engine repository: `packages/engine/tests/vehicle/`, with a complete car and steps).
131
+
132
+ A load seats a rider by vehicle id and seat. Your own vehicle joins with `engine.characters.addVehicle(boat)`, before or after the load.
@@ -7,7 +7,8 @@ There is a single pathfinding entry point: `engine.characters.findPath(from, to)
7
7
  update it, so a game that reshapes walkable ground at runtime leaves `nav()` out.
8
8
 
9
9
  ## 1. Install (main.js)
10
- ```js
10
+ A level is a file or a `THREE.Object3D` built in code: `level({ scene: group })`, its meshes named as in `10-blender-level.md`.
11
+ ```js fragment
11
12
  import { level, collision, followCamera, characters, nav } from 'threedog';
12
13
  engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(),
13
14
  nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
@@ -15,11 +16,11 @@ engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), char
15
16
  - Mesh source: the walkable meshes in the level (naming convention in `10-blender-level.md`). Walls = the level's `col_` boxes + every
16
17
  `addBox / addCircle` in the collision module;
17
18
  they sync automatically as dynamic obstacles: add an obstacle in game and the affected tiles rebuild themselves, no manual refresh.
18
- - Recast (about 1 MB) is downloaded only in start(); until it is ready findPath falls back to A*.
19
+ - Recast (728 KB, 218 KB gzipped) starts loading when `nav()` is installed, and a game without `nav()` never downloads it; the path worker's bundle holds a second copy. Until it is ready findPath falls back to A*.
19
20
 
20
21
  ## 2. Use
21
- ```js
22
- const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, z }...] or null (unreachable)
22
+ ```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
23
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
24
25
  wall.remove(); // remove the obstacle
25
26
  engine.npcs.add({ name: 'Courier', position: [4, 0, -5], schedule: [{ at: 0, position: [4, 0, 5] }] }); // the NPC finds its own way there
@@ -32,13 +33,13 @@ Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd n
32
33
  - In a test: after `engine.haltLoop()` call `findPath` and look at the waypoints (going around a wall they pass through the gap); after `addBox`,
33
34
  `engine.step(0.1)` and query again: the path should switch sides.
34
35
  - Did the NPC arrive: after `engine.step(30)`, check `engine.npcs.get('Courier').position`.
35
- - To see the mesh: `nav({ debug: true })` + `npm run shot -- /your-page.html`. Related test: `threedog test 导航网格` (test page in the engine repository:
36
+ - To see the mesh: `nav({ debug: true })` + `npm run shot -- /your-page.html`.
36
37
  `packages/engine/tests/nav/`).
37
38
 
38
39
  ## 4. Many paths at once: findPathAsync
39
40
  `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*)
40
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`.
41
- ```js
42
+ ```js fragment
42
43
  const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { // status 'ok' | 'noPath' | 'notReady', as findPath({ detailed: true })
43
44
  guard.path = path;
44
45
  }, { radius: 0.5 });
@@ -48,7 +49,7 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
48
49
  - Built-in NPCs already use it; keep `findPath` for the few calls that need a path this step (player click-to-move).
49
50
  - threads on / off / slow / crashed give identical paths on the identical step: the worker mirrors the navmesh (exported bytes) and the collision colliders;
50
51
  if either changes while a batch is in flight, that batch is recomputed on the main thread on the new state.
51
- - With A*, ground shape (water, slope) is sampled on a 1 m raster cached 5 s (colliders and terrain trees are tested exactly), and the search stays inside
52
+ - With A*, ground shape (height, water, slope) is sampled on a 1 m raster cached 5 s, every floor of it, so what stands under a bridge or a storey counts as it does for `findPath` (colliders and terrain trees are tested exactly), and the search stays inside
52
53
  the start-goal box plus a margin, so an async path can differ slightly from `findPath`'s.
53
54
  - A save taken while a request is in flight does not keep it: the NPC asks again after loading. Tests: `threedog test "paths:"`.
54
55
 
@@ -57,6 +58,49 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
57
58
  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
58
59
  request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
59
60
 
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.
62
+ - 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.
64
+ - 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
+ - Height, step and slope are the same for all sizes: only the radius differs.
66
+ - `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
+
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.
69
+
70
+ ## 6. NPC links across gaps
71
+ 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
+ ```js fragment
73
+ 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
76
+ ] });
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
78
+ ```
79
+ - 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).
81
+ - 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
+ - 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
+
84
+ 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
+ ```js
86
+ engine.events.on('link:enter', ({ character, crossing }) => { // crossing: { link, from, to, seconds, time }
87
+ if (crossing.link === 'gap') { crossing.seconds = 0.7; character.playAction('jump'); }
88
+ });
89
+ 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
92
+ 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
+ position.set(a.x + (b.x - a.x) * side, a.y + (b.y - a.y) * rise, a.z + (b.z - a.z) * side);
94
+ };
95
+ ```
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.
98
+ - `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.
100
+ - 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
+ - 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
+ - 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.
103
+
60
104
  ## Fences and rivers (collision)
61
105
 
62
106
  Walls and water that are not meshes: `engine.collision.addSegment(a, b, { thickness })` is a thin wall along a line; `addBlocked(fn)` marks ground impassable where `fn(x, z)` is true. Both return `{ remove() }` and are free when unused.
@@ -73,7 +117,7 @@ Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathi
73
117
 
74
118
  ## Line of sight, stealth vision cones and straight-line checks: collision.lineClear
75
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").
76
- ```js
120
+ ```js fragment
77
121
  const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
78
122
  const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
79
123
  ```
@@ -1,6 +1,6 @@
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), other objects (4), gameplay-driven progress (5), checking (6).
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).
4
4
 
5
5
  There is a single entry point: `engine.assets.animate(model, config)` -> Animator (advanced every frame by the engine; never call mixer.update yourself).
6
6
  For characters (player, NPCs), passing `model` builds the Animator automatically and switches clips by character state (idle walk run swim jump fall drive).
@@ -21,13 +21,14 @@ states: { idle: { clip: 'Idle_Sword' }, attack: { clip: 'Sword_Slash', loop: fal
21
21
  ```
22
22
  **Keep the mapping as data, on the model's manifest entry** (it describes the file, so it travels with it in an asset pack). `assets.animate(model)`
23
23
  and characters start from it; config passed in code adds states and wins per state. Swapping the model then only edits its manifest entry:
24
- ```js
24
+ ```js fragment
25
25
  engine.assets.manifest({ name: 'heroes', models: { hero: { url: '/models/hero.glb', animation: {
26
26
  fade: 0.2,
27
27
  states: { idle: { clip: 'Idle_Sword' }, walk: { clip: 'Walk' }, attack: { clip: 'Sword_Slash', loop: false, timing: 0.62 }, hurt: { clip: 'HitRecieve', loop: false } },
28
28
  } } } });
29
29
  engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // no clips / animation in code
30
- engine.assets.mapping(engine.player.anim.root); // after whenReady: the entry's mapping, or null
30
+ await engine.player.whenReady;
31
+ engine.assets.mapping(engine.player.anim.root); // the entry's mapping, or null
31
32
  ```
32
33
  A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and the entry's `fade` beats `characters({ animation })`.
33
34
 
@@ -55,7 +56,7 @@ over: it runs after the mover's state each step and returns a state name or null
55
56
  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
56
57
  (recipe 57, Moved by script, has a ladder).
57
58
  ```js
58
- createPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
59
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
59
60
  states: (c, f) => f.grounded && engine.input.down('crouch') ? 'crouch' : !f.grounded && f.vy < 0 && gliding ? 'glide' : null });
60
61
  ```
61
62
  Deep water follows `water`: `'swim'` (default), `'block'` (never enters), `'wade'` (walks the bottom), or `(c, { depth }) => mode` per spot;
@@ -84,7 +85,7 @@ names; a failed load keeps the capsule and warns once; a character disposed befo
84
85
  ## 3b. Procedural bodies are assets too (`model: 'humanoid'`)
85
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
86
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.
87
- ```js
88
+ ```js fragment
88
89
  import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
89
90
  engine.assets.manifest(assets);
90
91
  engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
@@ -100,7 +101,7 @@ engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } })
100
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);
101
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.
102
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:
103
- ```js
104
+ ```js fragment
104
105
  // picture/sprites.js: a sheet of cols x rows frames; which row is which is your sheet's layout
105
106
  const ROW = { idle: 0, walk: 1, run: 1, jump: 2, fall: 2 };
106
107
  export function spriteBody(texture, cols, rows, framesPerSecond) {
@@ -120,11 +121,37 @@ export function spriteBody(texture, cols, rows, framesPerSecond) {
120
121
  const hero = spriteBody(await engine.assets.texture('hero-sheet', { pixelated: true }), 4, 3, 8);
121
122
  engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero.sprite }).onPose(hero.animate);
122
123
  ```
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
+ ```js fragment
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
130
+ ```
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
+ `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.
123
133
  - **What the engine still does**: everything but the drawing. The mover, ground and collision, `state`, `facing`, `walkTo`, the camera and the save work as for any body; `anim`
124
134
  has no clips to play. A one-off NPC is `new Character(engine, { model })` the same way ([02-npc](02-npc.md)).
125
135
  - **Facing**: a `Sprite` ignores `root`'s turn and a negative scale. Pick a row from `c.facing`, or mirror with a negative `map.repeat.x` and the matching `offset`.
126
136
  - **Edges**: `alphaTest` on the material gives hard edges and no sorting trouble between overlapping sprites. For a side or top-down view see recipe 21 section 6; for a pixel look, recipe 62 section 4b.
127
137
 
138
+ ## 3d. Which modules need an engine character, which take a sprite or any position
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
+ | Module | On a sprite / plain object / position | Result |
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 |
143
+ | `interactions.add(object, ...)` | any mesh or sprite, no character | works: E near it, `once`, `counter`, saved as used |
144
+ | `dialogue` | no object at all (a name and flags) | works: flags are in the save |
145
+ | `triggers.add({ position })` | a position; `who` is the actor or an id | works: fired for the player character |
146
+ | `pickups.spawn(position, { mesh })` | a position and your own mesh; `give` as a function without `inventory()` | spawned with a sprite mesh; collecting: not run |
147
+ | `quests` | steps with `target` an object or `{ x, z }` and `done(e)` | works to start and report steps; a step moved on by a dialogue flag: not run past the flag |
148
+ | `collision.addBlocked(fn)` | a function of x, z (the player was kept in the arena) | works; `addObject(mesh)`: not run |
149
+ | `characters.findPath` | positions | returned a path; `nav.findPath` needs the `nav` module: not run |
150
+ | `audio.sfx`, `audio.tone`, `ambience.add` | no object | ran without error (no sound file named, so nothing audible was checked) |
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
+ | `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.
154
+
128
155
  ## 4. Non-character objects (a dog, a windmill, a door)
129
156
  ```js
130
157
  const dog = await engine.assets.model('dog'); engine.add(dog);
@@ -164,7 +191,7 @@ action ends; the animation only shows `t`.
164
191
  alone, so a character's per-frame locomotion cannot override it. `sync(null)` hands control back; the next `go()` switches as usual. Entering a synced
165
192
  state cross-fades like `go()` (the `transitions` table applies).
166
193
  `timing` on the state maps gameplay seconds to clip seconds:
167
- ```js
194
+ ```js fragment
168
195
  const anim = engine.player.anim; // or engine.assets.animate(model, {...})
169
196
  Object.assign(anim.states, {
170
197
  // 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,4 +225,3 @@ applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
198
225
  clip weights sum to 1).
199
226
  - Characters: `describe().player.state` (idle/walk/run...) matches `engine.player.anim.state`.
200
227
  - `anim.check([...actions])` is `[]`.
201
- - Related tests: `threedog test "Animation state machine"`, `threedog test 骨骼动画链路`, `threedog test 骨骼动画最小链路`.
@@ -1,5 +1,7 @@
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
4
+
3
5
  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
4
6
  counter). The contracts every module should follow (state, game time, skip, describe, ops) and a second copyable module are in
5
7
  `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/`);
@@ -66,32 +68,43 @@ A module that does two kinds of thing is two definitions returned together (`wea
66
68
  ## 2. Hooks and order cheat sheet
67
69
  - `install(e, ctx)` returns the public object; `init(e, ctx)` (may be async) prepares at start; `ctx.track(handle)` ties a listener or timer to
68
70
  the module (next bullet but four); while `isReady(e)` returns false the loading screen waits for it
69
- (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e)` (may be async) runs after a save loaded, to rebuild
70
- what the loaded state needs nearby, with gameplay frozen until it resolves.
71
+ (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e, turn)` (may be async; recipe 20 says what `turn` is for) runs after a save loaded, to rebuild
72
+ what the loaded state needs nearby, with gameplay frozen and ops refused (`'loading'`) until it resolves. It rebuilds by writing state directly, inside
73
+ `e.ops.allow(...)` when the write is guarded, not through `e.ops.run`.
71
74
  - `fixed(dt, e)` movement, timing, gameplay keys (`input.pressed` read in fixed is this step's snapshot, independent of frame rate); `frame(dt, e)`
72
75
  animation, camera, UI (it reads this frame's latest input); `afterRender(dt, e)` after rendering.
73
76
  - `describe(e, ctx)`: see recipe 49 contract 4; `ctx.near(object or {x,z}, { name, kind })` reports things nearby. `skip(dt, e, done)`: recipe 49 contract 3.
74
77
  - `applyState(e, p)`: called by `engine.applyState` / URL parameters with the keys `time`, `season`, `weather`, `cutscene`, `play` and `at` (core handles the rest); `stateKeys: ['time']` lists what the module handles, and it refuses with `{ refused: { key: reason } }`.
75
78
  - `stage`: only when the hooks run (first -> last): `control` timeline, camera -> `ground` terrain, level -> `environment` weather, sky, water -> `gameplay`
76
79
  interactions, dialogue -> `effects` particles, objective markers -> `late` (the default) characters, physics -> `audio` music. Within
77
- a stage, to read another module's result for this frame, write `after: ['its-name']` (or `before`); across stages the stage always wins, so a
80
+ a stage, to read another module's result for this frame, write `after: ['its-name']` (or `before`). The name may be a capability, `after: ['ground']`: whichever module provides it
81
+ now, so the order survives a `replaces`. Across stages the stage always wins, so a
78
82
  `before` / `after` that contradicts it (a `control` module `after` an `audio` one) makes `engine.use` throw `module-order` naming both modules: give
79
83
  them the same stage or drop the line. `engine.use(a, b)` is all-or-nothing: if `b` fails, nothing of `a` stays installed.
84
+ - Installed is not running: `engine.has('nav')` says it is installed; after `await engine.loading.settled()`, `engine.explain({ module: 'nav' })` says whether it runs and, if not, why.
85
+ - A module with `provides: ['inventory']`, or one another module `requires`, is checked in dev against that capability's contract when it binds: a missing method is one
86
+ `module-contract` warning and a line in `engine.catalog(name).problems`. The module still runs: only the game knows which calls it makes.
80
87
  - Between modules: notify with `e.events.emit('stamina:empty')` and let others `on` it; use optional dependencies as `e.hud?.` and list them in
81
88
  `optional: ['hud']` (for engine modules R16 of `npm run check` verifies this). Never import another module's files directly.
82
89
  - A module the game cannot run without sets `critical: true`: if its `init` fails, `engine.start()` rejects with the module name and reason (default
83
90
  false: a failed init is reported and start goes on). A module installed after start gets no `fixed` / `frame` before its `init` finished:
84
- `engine.moduleStates` shows `initializing` / `running` / `failed`, and `await engine.loading.settled()` waits for it. A module whose `isReady` never
91
+ `engine.explain({ module })` shows `initializing` / `running` / `failed`, and `await engine.loading.settled()` waits for it. A module whose `isReady` never
85
92
  turns true makes `start()` reject after `engine.loading.timeoutMs` (default 120 s), naming it.
86
93
  - 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
87
- (`module:disabled`, listed in `engine.disabledModules`); in any other type it freezes the game in development/tests and is recorded in `engine.error`.
94
+ (`module:disabled`, listed in `describe().disabledModules`); in any other type it freezes the game in development/tests and is recorded in `engine.error`.
95
+ - `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`,
97
+ `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
+ `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.
88
99
  - Listeners and timers the module adds go through `ctx.track(...)`: `ctx.track(e.events.on('item:add', fn))`, also `onFixed` / `onFrame` /
89
100
  `clock.after` / `audio.measure` / a `makeWindow` window, anything with `remove()`. They leave with the module: when its `engine.use(...)` batch
90
101
  rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook (the spec `threedog test "Lifecycle: every built-in"`
91
- checks every engine module). A class the module builds takes `ctx.track` as a constructor argument. DOM listeners use
102
+ checks every engine module). A class the module builds takes `ctx` as a constructor argument. DOM listeners use
92
103
  `addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`); scene GPU memory,
93
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
94
105
  physics world, WASM objects and real-time timers, and is called in reverse install order.
106
+ - Your data in a replaceable provider: `ctx.feeds('collision', () => addMyWalls())` runs before the `use()` of a new holder returns.
107
+ - 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.
95
108
  - 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, ... }))`),
96
109
  so they leave with it too. A module that must be the only one of its kind declares `provides: ['inventory']`; others `requires: ['inventory']`
97
110
  (a capability, never a module name), and a game swaps it with `engine.use(mine(), { replaces: 'inventory' })` (`55-mods-time-wrap.md`). `engine.unuse('name')` removes a module with nothing in its place, and refuses while another still requires it. Picture slots: `62-picture-code.md` 3e:
@@ -110,8 +123,7 @@ A module that does two kinds of thing is two definitions returned together (`wea
110
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;
111
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
112
125
  running cutscene, the music playing) stops on `ctx.track(e.events.on('session:end', ...))`. What is derived from save parts is rebuilt on
113
- `'session:start'` and `'save:loaded'`. A module's `describe()` should show such state: the session spec (`threedog test Session`) compares every
114
- installed module's describe after two new games, and the Lifecycle spec round-trips the engine's own.
126
+ `'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.
115
127
  - When you only need a per-frame callback and no module structure: `const h = engine.onFrame(dt => ...)` / `engine.onFixed`, and `h.remove()` cancels it.
116
128
 
117
129
  ## 3. Extra steps when it goes into the engine