threedog 1.1.0 → 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 (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +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 +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +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/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -1,5 +1,10 @@
1
1
  # Shooting and picking (cast a ray from the screen center or the mouse position, with any camera)
2
2
 
3
+ > **Covers:** a ray from the screen center or the pointer: shooting, selecting, tapping.
4
+ > **Use when:** the player aims, clicks or taps at something in the scene.
5
+ > **Shortest:** `engine.pick(x, y)` or `engine.rays`.
6
+ > **Sections:** 1 A first-person shooting · 2 What happens after · 3 Testing
7
+
3
8
  Works with any camera (`follow`, `firstPerson`, `rts`, `fixed`): a click-to-select strategy game, a puzzle that taps tiles or a first-person shooter all
4
9
  use the same ray. The example below is the first-person case; a score display needs `hud()`.
5
10
  The ray API is `engine.pick(ndcX, ndcY, opts)`: screen coordinates -1..1 (0, 0 is the screen center, which is also the first-person crosshair); it
@@ -9,17 +14,17 @@ ray registration is needed.**
9
14
  ## 1. A first-person shooting range (copy it and it runs)
10
15
  ```js
11
16
  import { createEngine, presets, openWorld, hud, THREE } from 'threedog';
12
- import { createPicture } from './picture/index.js'; // the game's own picture, plain three.js (recipe 62)
17
+ import { createPicture } from './picture/index.js'; // the game's own picture, plain three.js (recipe 62)
13
18
  import { terrainPreset } from '@threedog/terrain-noise';
14
19
 
15
20
  const engine = createEngine({ canvas: document.getElementById('view'), lights: false, saveKey: 'range' });
16
- engine.use(openWorld({ seed: 7, terrain: terrainPreset(), camera: 'firstPerson' }), hud()); // camera (required): 'follow' | 'firstPerson' | 'rts' | 'fixed', or pass a module like firstPersonCamera({ height: 1.7 })
21
+ engine.use(openWorld({ seed: 7, terrain: terrainPreset(), camera: 'firstPerson' }), hud()); // camera (required): 'follow' | 'firstPerson' | 'rts' | 'fixed', or pass a module like firstPersonCamera({ height: 1.7 })
17
22
  engine.use(createPicture());
18
23
  const { picture } = engine;
19
- engine.input.action('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF'] }); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
20
- engine.characters.createPlayer({ ...presets.player.aim, spawn: engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 }) });
24
+ engine.input.define('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF'] }); // the left mouse button is a key too (Mouse0 / Mouse1 / Mouse2); either it or KeyF works
25
+ engine.characters.addPlayer({ ...presets.player.aim, spawn: engine.characters.findSpawn([0, 0, 0], { minH: 3, maxH: 14 }) });
21
26
  Object.assign(window, { engine, picture });
22
- await engine.start(); // place targets after the terrain is generated
27
+ await engine.start(); // place targets after the terrain is generated
23
28
 
24
29
  // Targets: ordinary three.js objects. Put your own data in target.userData; managing them with a Map / Set is faster than traversing the scene
25
30
  const targets = [];
@@ -33,16 +38,16 @@ const p0 = engine.player.position;
33
38
  for (let i = 0; i < 6; i++) addTarget(p0.x + (i - 2.5) * 3, p0.z - 15);
34
39
 
35
40
  let score = 0;
36
- engine.hud.counter('score', { label: 'Hits', value: 0 });
37
- engine.describe.add('range', () => ({ score, targets: targets.length })); // dev bridge: threedog describe range; in code the part sits under its name: engine.describe('range').range.score
41
+ engine.hud.addCounter('score', { label: 'Hits', value: 0 });
42
+ engine.describe.add('range', () => ({ score, targets: targets.length })); // dev bridge: threedog describe range; in code the part sits under its name: engine.describe('range').range.score
38
43
 
39
- engine.onFixed(() => { // firing is gameplay: read it in fixed so the result is independent of frame rate
40
- if (!engine.input.pressed('shoot')) return; // "just pressed" from the fixed-step snapshot; one click counts once
41
- const hit = engine.pick(0, 0, { targets }); // cast from the screen center; hit.object may be a child mesh of the target, so find the target as below
44
+ engine.onFixed(() => { // firing is gameplay: read it in fixed so the result is independent of frame rate
45
+ if (!engine.input.pressed('shoot')) return; // "just pressed" from the fixed-step snapshot; one click counts once
46
+ const hit = engine.pick(0, 0, { targets }); // cast from the screen center; hit.object may be a child mesh of the target, so find the target as below
42
47
  const t = hit && targets.find(x => x === hit.object || x.getObjectById(hit.object.id));
43
48
  if (!t) return;
44
49
  engine.remove(t); targets.splice(targets.indexOf(t), 1);
45
- engine.hud.counter('score', { value: ++score }); // calling again with the same id = update
50
+ engine.hud.addCounter('score', { value: ++score }); // calling again with the same id = update
46
51
  });
47
52
  ```
48
53
  - **Where fire and reload live**: the engine has no weapon system. In a game with ammo they are the game's ops (`engine.ops.define('weapon.fire', ...)`, recipe 23), so a key, a test and the dev bridge run one path; the fixed step above only calls `engine.ops.run`.
@@ -56,7 +61,7 @@ engine.onFixed(() => { // firing is gameplay:
56
61
  - **The first click**: on desktop, first person by default needs one click on the canvas to lock the mouse. That press only locks: it is not delivered
57
62
  as `Mouse0` and not as a click, so it cannot fire (every later click after Esc and a re-lock behaves the same). `swallowLockClick: false` on the
58
63
  camera delivers it too.
59
- - **Adding a gamepad button**: `engine.input.action('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF', 'PadRT'] })`; the key names go into the settings key table and the
64
+ - **Adding a gamepad button**: `engine.input.define('shoot', { label: 'Shoot', keys: ['Mouse0', 'KeyF', 'PadRT'] })`; the key names go into the settings key table and the
60
65
  UI prompts. A touch tap does not count as `Mouse0` (give phones a button: `engine.input.touchButton('shoot', 'Shoot')`).
61
66
  - To hit terrain / houses / registered static objects, don't pass `targets` (the default hits what was registered with `rays.addStatic`); to hit rigid
62
67
  bodies too, pass `targets: 'all'`.
@@ -66,13 +71,13 @@ engine.onFixed(() => { // firing is gameplay:
66
71
  - For bullets with flight time (arcs, enemies dodging): don't use a ray; write `world.add({ kind: 'bullet', ... })` + `world.simulate`, see `18-world.md`.
67
72
  - Distance limit: `engine.pick(0, 0, { targets, far: 60 })`.
68
73
  - Recoil: `pick` casts from the camera as last drawn, so a `rig.yaw` / `rig.pitch` write reaches it on the next drawn step. For several shots in one step with recoil between them, build the direction from the rig's angles and use `engine.raycast`.
69
- - Score, ammo: `hud.counter` / `hud.bar`; numbers that must be saved go in `engine.vars` (`engine.vars.bump('score')`); after changing them call
70
- `hud.counter` again to sync the display.
74
+ - Score, ammo: `hud.addCounter` / `hud.bar`; numbers that must be saved go in `engine.vars` (`engine.vars.bump('score')`); after changing them call
75
+ `hud.addCounter` again to sync the display.
71
76
 
72
77
  ## 3. Testing
73
78
  ```js fragment
74
79
  engine.haltLoop();
75
- engine.input.simulate('shoot'); engine.step(0.1); engine.input.simulate('shoot', false); // simulate a click on the action bound to Mouse0 (use your action name)
80
+ engine.input.simulate('shoot'); engine.step(0.1); engine.input.simulate('shoot', false); // simulate a click on the action bound to Mouse0 (use your action name)
76
81
  // To hit a specific target: first aim the camera at it with engine.cameraRig.lookAt(target), then click
77
82
  ```
78
83
  From the command line: `threedog press Mouse0` (the same as pressing a keyboard key), then look at `describe range`:
@@ -1,7 +1,9 @@
1
1
  # Content vocabulary, key actions in actions.js, saving and loading at startup
2
2
 
3
- **In this recipe**: 1. Condition words / effect words · 1b. Content packs · 2. actions.js: a game's own key actions · 3. Interact keys ·
4
- 4. Continue and new game · 4b. Best times and high scores · Save failures and versions · Save format
3
+ > **Covers:** content words (conditions and effects), content packs, key actions, saving and loading.
4
+ > **Use when:** game rules written as data, or saving progress.
5
+ > **Shortest:** `engine.saves.save('slot1')` / `engine.session.load('slot1')`.
6
+ > **Sections:** 1 Condition words / · 1b Content packs several · 2 actions.js a game's · 3 Interact keys which · 4 Continue and new · 4b Best times and · Save failures and versions · Save format
5
7
 
6
8
  ## 1. Condition words / effect words
7
9
  The full vocabulary is in the last section of `../api/content.md` (**generated from `modules/content/rules.js`**, so it never goes stale):
@@ -21,7 +23,7 @@ ops, used from content as `{ op: ['noun.verb', { args }] }` / `{ can: [...] }` (
21
23
  Register once and the loader, `threedog check` and GAMEMAP all know the file:
22
24
  ```js
23
25
  // content/rules.js
24
- import { craftOp } from '../crafting.js'; // the game's own code
26
+ import { craftOp } from '../crafting.js'; // the game's own code
25
27
  export default {
26
28
  kinds: {
27
29
  recipes: {
@@ -32,7 +34,7 @@ export default {
32
34
  check(data, ctx) {
33
35
  for (const [id, r] of Object.entries(data)) if (!ctx.data.items?.[r.makes]) ctx.err(`recipe ${id} makes unknown item ${r.makes}`);
34
36
  },
35
- map: data => Object.entries(data).map(([id, r]) => `${id} -> ${r.makes}`), // optional GAMEMAP lines
37
+ map: data => Object.entries(data).map(([id, r]) => `${id} -> ${r.makes}`), // optional GAMEMAP lines
36
38
  // optional: the keys of each entry (core/base/params.js format, no default); threedog check reports unknown keys, wrong types, out of range
37
39
  fields: { needs: 'object', makes: 'string', seconds: { type: 'number', min: 0, optional: true, desc: 'crafting time' } },
38
40
  },
@@ -43,20 +45,17 @@ export default {
43
45
  // content/recipes.js
44
46
  export default { bread: { needs: { flour: 2 }, makes: 'bread' } };
45
47
  ```
46
- Add `recipes` to `content/index.js` like any other file, and `rules` too: the loader knows a kind only from the `rules` it is handed (`threedog check`
47
- says so when one is missing). `load` is optional: a game that imports the file itself leaves it out and still gets the check and the map entry.
48
- A name `content/index.js` lists that is neither an engine file nor a registered kind is an error, and so is `content.load({ enemies })` without the kind:
49
- both say how to register it. A kind may not reuse an engine file name. A file the index does not list is no content, so `threedog check` gives one warning.
50
- A game's own data that the engine never reads, such as translated story text, belongs outside `content/`: a folder of its own that the game
51
- imports itself, or `engine.i18n.add()` when it is text the UI fetches with `engine.t`. To have it checked and on the map, register a kind with no `load`.
48
+ Add `recipes` and `rules` to `content/index.js`: the loader knows a kind only from the `rules` it is handed. `load` is optional (the check and the map entry still apply).
49
+ An unregistered name in `content/index.js` or `content.load({ enemies })` is an error saying how to register it; a kind may not reuse an engine file name; a file the index does not list gets one warning.
50
+ Data the engine never reads (translated story text) belongs outside `content/`, or in `engine.i18n.add()` for text fetched with `engine.t`; a kind with no `load` still gets it checked and mapped.
52
51
 
53
- **Field tables.** Every content entry has one: the engine's own, a template's `fields` (recipes/30-templates.md) or a kind's `fields` as above. `threedog check` validates every entry
54
- against its table (a misspelled `scael` names `scale`), and `engine.content.fields(name)` returns the same table for tools such as an editor panel.
52
+ **Field tables.** Every content entry has one (the engine's own, a template's `fields` (recipes/30-templates.md), a kind's `fields`): `threedog check` validates against it
53
+ (a misspelled `scael` names `scale`), and `engine.content.fields(name)` returns it for tools.
55
54
 
56
55
  ## 1b. Content packs: several data sets in one load
57
56
  A pack with a `level` commits when its file is here. If a newer `level.load`, save load or unload comes first, the newest level stands and only the pack's `level` gives way: the rest goes in once that load has ended, on the level that won. A place only the pack's level had fails with `content-place`, as any unknown place does, and the pack goes back whole.
58
57
 
59
- `content.load` answers for its own load. Bad data throws on the line. The Promise it returns resolves once the pack committed, and rejects when it failed, after the old level and registrations are back; saves and loads asked meanwhile wait for that. If the old level could not come back, `err.notRestored` lists why. A load nobody awaits is reported all the same.
58
+ Bad data throws on the line. The Promise `content.load` returns resolves once the pack committed and rejects when it failed, after the old level and registrations are back; saves and loads asked meanwhile wait. A load nobody awaits is reported all the same. `err.notRestored` lists why the old level could not come back.
60
59
 
61
60
  ```js fragment
62
61
  try { await engine.content.load(dlc); }
@@ -67,9 +66,9 @@ A content pack is the same object `content/index.js` exports (`{ items, template
67
66
  folder or an npm package: data only, assets by name (never a path or a function; `npm run check` and a dev warning report both). Load several together:
68
67
  ```js fragment
69
68
  import base from './content/index.js';
70
- import forest from 'forest-content'; // its props name templates from base and models from the forest asset pack
71
- import packs from './assets.js'; // export default [forestAssets, ...]: the asset packs ({ name, base, models, textures, sounds, fonts })
72
- engine.assets.manifest(packs); // the same objects `npm run check` reads the names from
69
+ import forest from 'forest-content'; // its props name templates from base and models from the forest asset pack
70
+ import packs from './assets.js'; // export default [forestAssets, ...]: the asset packs ({ name, base, models, textures, sounds, fonts })
71
+ engine.assets.manifest(packs); // the same objects `npm run check` reads the names from
73
72
  engine.content.load([base, forest], { places: { home } });
74
73
  ```
75
74
  - Packs load in list order, so a pack may use what an earlier one defines. A pack's own `places` load with it; the `places` option goes on top (a place computed at startup).
@@ -79,9 +78,8 @@ engine.content.load([base, forest], { places: { home } });
79
78
  are ids like items (two packs, one name: an error); ambience and music rule lists concatenate.
80
79
 
81
80
  ## 2. actions.js: a game's own key actions
82
- Format of `content/actions.js`: **action name -> { keys: default keys, label: display text }**. Actions that the engine brings along (move...) need
83
- not be written; inventory, quests and photo only declare their action, and run, jump and interact
84
- are not core keys either: they come from the game (`presets.bindings.*`, this file or `createEngine({ bindings })`).
81
+ Format of `content/actions.js`: **action name -> { keys: default keys, label: display text }**. Engine actions (move...) need not be written; modules
82
+ only declare theirs, and run, jump and interact keys come from the game (`presets.bindings.*`, this file or `createEngine({ bindings })`).
85
83
  ```js
86
84
  // content/actions.js
87
85
  export default {
@@ -90,42 +88,39 @@ export default {
90
88
  load: { keys: ['KeyL'], label: 'Load' },
91
89
  };
92
90
  ```
93
- Don't forget to add it to the exports in `content/index.js` (`export default { ..., actions }`), otherwise `engine.content.load(data)` will not load
94
- it (it calls `engine.input.action(name, { label, keys })`). What happens on press is written in main.js, read inside a fixed step so it lands on a tick:
91
+ Add it to `content/index.js` (`export default { ..., actions }`); the load calls `engine.input.define(name, { label, keys })`. The press is read in main.js inside a fixed step:
95
92
  `engine.onFixed(() => { if (engine.input.pressed('kick')) engine.ops.run('ball.kick', {}, { source: 'player' }); })` (a gameplay action is an op,
96
- recipes/23-ops.md). A game that does not use content calls `engine.input.action('kick', { label: 'Push / kick', keys: ['KeyF'] })` directly.
93
+ recipes/23-ops.md). A game that does not use content calls `engine.input.define('kick', { label: 'Push / kick', keys: ['KeyF'] })` directly.
97
94
 
98
- **The engine does not perform the `save` / `load` actions for you**: they only register the keys; after the press you call the engine yourself in
99
- main.js. Saving and loading are async (`Promise<boolean>`): await them, and say "saved" only on `true` (on `false` the engine already showed why).
100
- Loading a slot to keep playing from it is `engine.session.load`, which leaves nothing of the current playthrough behind:
95
+ **The `save` / `load` actions only register keys**: call the engine yourself after the press. Both are async (`Promise<boolean>`): say "saved" only on `true`
96
+ (on `false` the engine already showed why). Loading a slot to play on is `engine.session.load`, which leaves nothing of the current playthrough:
101
97
  ```js
102
98
  import { toast } from 'threedog';
103
- engine.onFixed(() => { // read keys in the fixed step like every gameplay key; the async work runs after it
99
+ engine.onFixed(() => { // read keys in the fixed step like every gameplay key; the async work runs after it
104
100
  if (engine.input.pressed('save')) engine.saves.save('slot1').then(ok => ok && toast(engine, 'Saved'));
105
101
  if (engine.input.pressed('load')) engine.session.load('slot1').then(ok => !ok && toast(engine, 'No save yet'));
106
102
  });
107
- engine.saves.autosave(3); // autosave to 'auto' every 3 minutes of play (waits while paused, on the title screen and during newGame / load)
103
+ engine.saves.autosave(3); // autosave to 'auto' every 3 minutes of play (waits while paused, on the title screen and during newGame / load)
108
104
  ```
109
105
 
110
106
  ## 3. Interact keys: which object, and who acts
111
107
  `interactions({ pick })` decides what the interact key uses (no default, `[interaction-setup]` names the fix). It takes no key: bind one in `createEngine({ bindings: presets.bindings.interact })`, or with `engine.input.bind`.
112
- `radius` is measured from the object's origin, not its edge. For a large object (a boat, a house) raise it, or add the interaction to a small marker
113
- object at the spot where it is used.
108
+ `radius` is measured from the object's origin, not its edge: for a large object raise it, or put the interaction on a small marker where it is used.
114
109
 
115
110
  Pick the rule that fits the camera, not the genre default:
116
111
  ```js
117
- engine.use(interactions({ ...presets.interactions.nearest })); // E, nearest within 2.5 m (top-down, third person)
112
+ engine.use(interactions({ ...presets.interactions.nearest })); // E, nearest within 2.5 m (top-down, third person)
118
113
  engine.use(interactions({ pick: 'facing' })); // only what the actor faces (within 60°): the door behind you stays dark
119
114
  engine.use(interactions({ pick: 'aim', radius: 2 })); // closest to the screen-center ray: first person, shooters
120
- engine.use(interactions({ pick: (list, ctx) => list.find(c => c.id.startsWith('npc')) ?? list[0] })); // own rule; list = enabled ones in range, nearest first
121
- engine.interactions.pickMode = 'aim'; // switch at runtime (entering a first-person mode)
115
+ engine.use(interactions({ pick: (list, ctx) => list.find(c => c.id.startsWith('npc')) ?? list[0] })); // own rule; list = enabled ones in range, nearest first
116
+ engine.interactions.pickMode = 'aim'; // switch at runtime (entering a first-person mode)
122
117
  ```
123
118
  One object with two verbs = two interactions with different key actions; each key picks among its own action, and `engine.interactions.options` lists
124
119
  one `{ action, id, label }` per key for a prompt that shows both:
125
120
  ```js fragment
126
- engine.input.action('take', { label: 'Take', keys: ['KeyF'] });
127
- engine.interactions.add(thing, { label: 'Inspect', onUse: inspect }); // E
128
- engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take }); // F
121
+ engine.input.define('take', { label: 'Take', keys: ['KeyF'] });
122
+ engine.interactions.add(thing, { label: 'Inspect', onUse: inspect }); // E
123
+ engine.interactions.add(thing, { label: 'Take', action: 'take', enabled: () => ready, onUse: take }); // F
129
124
  ```
130
125
  **Hold and walk-over.** `hold: seconds` makes the key a hold (pump a well, defuse, pick a lock): the engine counts it on fixed steps, interrupts it
131
126
  when the key is released, the actor leaves the radius, `enabled()` turns false or input locks (`interaction:hold` / `interaction:interrupt
@@ -135,13 +130,12 @@ when the key is released, the actor leaves the radius, `enabled()` turns false o
135
130
  skip the hold; an approach returns `{ approaching }`, a promise of onUse's result).
136
131
  ```js fragment
137
132
  engine.interactions.add(well, { label: 'Pump', hold: 1.5, onUse: fill });
138
- engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'shells' }); // mesh gone after E, counted: recipe 03 "Pick and count"
133
+ engine.interactions.add(shell, { id: 'shell-1', label: 'Pick up', once: true, counter: 'shells' }); // mesh gone after E, counted: recipe 03 "Pick and count"
139
134
  engine.interactions.add(clerk, { label: 'Talk', radius: Infinity, approach: true, onUse: talk });
140
135
  ```
141
- **Who acts** is `engine.actor` (a world record id, default `'player'`). Interactions, trigger zones, objective-marker distances, the world simulation
142
- center and the default `ctx.actor` of ops all measure from `engine.actorPosition()`. To let the user drive a boat or switch squad members, set
143
- `engine.actor = 'boat_1'` and back to `'player'`; nothing else changes. Module code reads `engine.actorPosition()`, never `engine.player.position`
144
- (rule R17 warns).
136
+ **Who acts** is `engine.actor` (a world record id, default `'player'`): interactions, trigger zones, marker distances, the world simulation center and ops'
137
+ default `ctx.actor` measure from `engine.actorPosition()`. Drive a boat or switch squad members with `engine.actor = 'boat_1'`. Module code reads
138
+ `engine.actorPosition()`, never `engine.player.position` (rule R17).
145
139
  The actor is handed down, never assumed: `label / enabled / onUse` get `(object, { actor })` (the actor of `interaction.use`: the local user, a net
146
140
  peer, an NPC); trigger callbacks get `(t, who, id)` and the events carry `id` (`who` may list actor ids: `who: () => [e.actor, ...peerIds]`); content
147
141
  `has / lacks / give / take` use the bag of the running op's actor (else `engine.actor`), and `engine.content.run(effect, { actor })` /
@@ -154,26 +148,23 @@ engine.triggers.add({ position: gate, who: () => [engine.actor, ...guards], onEn
154
148
  ## 4. Continue and new game (the engine does not load automatically on start)
155
149
  After a page refresh the game is a new run; to "continue last time", load **after** `await engine.start()` through `engine.session`, the standard form:
156
150
  ```js
157
- await engine.start(); // modules and the save index are ready, so saves.list / check are synchronous
158
- if (engine.saves.check('auto') === null) await engine.session.load('auto'); // continue from the autosave if it can be loaded
151
+ await engine.start(); // modules and the save index are ready, so saves.list / check are synchronous
152
+ if (engine.saves.check('auto') === null) await engine.session.load('auto'); // continue from the autosave if it can be loaded
159
153
  ```
160
- - `engine.session.load(slot)` and `engine.session.newGame()` both return `Promise<boolean>`: always `await`. `session.load` starts from the new-game
161
- state and puts the save on top, so a part the save lacks (a module added in a later version) starts fresh instead of keeping the current run's
162
- state. `engine.saves.load(slot)` is a quick load onto the running playthrough; never build Continue from it.
163
- - A running cutscene and an open conversation are not saved: any load ends them without their remaining steps. Save at a point the game can continue from: a save taken inside a
164
- cutscene whose last step sets the flag a quest waits for comes back without that flag.
154
+ - `engine.session.load(slot)` and `engine.session.newGame()` return `Promise<boolean>`. `session.load` starts from the new-game state and puts the save on top,
155
+ so a part the save lacks starts fresh. `engine.saves.load(slot)` is a quick load onto the running playthrough; never build Continue from it.
156
+ - A running cutscene and an open conversation are not saved: any load ends them without their remaining steps (a flag their last step sets is missing), so save where the game can continue.
165
157
  - Loading restores the player, the view (the camera rig's yaw and pitch: a first-person game needs no save code for it), world data (world changes and deletions), inventory, quests, clock and random state; initial data in content files
166
158
  (`initial`) is the same whether it is loaded before or after the save, so ignore the order.
167
159
  - A load rebuilds the props and other world records: an Object3D your code kept from before (a door mesh, a lamp) is gone afterwards. Keep the
168
160
  record id, not the mesh, and look it up again on `save:loaded`: `engine.world.get(id)` for the record, `engine.world.view(id)` for its model
169
161
  now (null while not built or far away).
170
- - For a "main menu: Continue / New game": show "Continue" only when `engine.saves.check(slot) === null`; on click `await engine.session.load(slot)`;
171
- "New game" is `await engine.session.newGame()`.
162
+ - Main menu: show "Continue" only when `engine.saves.check(slot) === null`; "New game" is `await engine.session.newGame()`.
172
163
  - During development, to jump straight into a save: URL `?save=slot1` (`threedog state` also understands `save=`).
173
164
  - In tests, `engine.saves.save('x'); await engine.saves.flush();` writes before reading back.
174
165
 
175
166
  ## 4b. Best times and high scores: data that outlives saves
176
- Best lap times, a leaderboard or high scores belong to the player, not to one playthrough: in a save part a new game would wipe them. Persist them beside the saves, in `localStorage` under `engine.saves.storageKey(name)`, a key that shares the game's name and stays out of the save slots:
167
+ Best times, a leaderboard or high scores belong to the player, not one playthrough (a new game would wipe a save part): keep them in `localStorage` under `engine.saves.storageKey(name)`, which shares the game's name and stays out of the slots:
177
168
  ```js
178
169
  const key = engine.saves.storageKey('records');
179
170
  const records = () => JSON.parse(localStorage.getItem(key) ?? '{ "laps": [] }');
@@ -187,7 +178,8 @@ const addLap = time => { const r = records(); r.laps.push(time); localStorage.se
187
178
  running game and the stored save stay as they were. Ask first with `engine.saves.check(slot)` → `null | 'missing' | 'corrupt' | 'tooNew' | 'migrate'`.
188
179
  - A part whose `save()` throws makes the whole save fail (`false`, the slot keeps its previous save); a part whose `load()` throws rolls the game back
189
180
  to how it was before the load (`false`). So does a listener of an event the load emits (`world:load`) or a module's `afterLoad` that throws. Both go
190
- through the error tiers (`engine.error` in dev, code `save-part-threw` / `save-load-threw`).
181
+ through the error tiers (`engine.error` in dev and in release, code `save-part-threw` / `save-load-threw`; dev freezes the game on it).
182
+ - A rollback that cannot put a part back (no restorable `save()`, no new-game state, or a content `undo` that throws) warns `rollback-incomplete`: reload the page.
191
183
  - One replacement at a time: `saves.apply`, `saves.load` and `session.newGame` / `load` / `quit` wait their turn in the order asked, so the end state is
192
184
  always one whole save, and a load that fails rolls back to the whole state before it. Idle, a save with only synchronous parts applies at once. While
193
185
  a replacement runs ops return `'loading'`.
@@ -208,12 +200,12 @@ const addLap = time => { const r = records(); r.laps.push(time); localStorage.se
208
200
  ## Save format
209
201
  A save is one envelope; `engine.saves.collect()` returns it and `export` / `exportFile` carry it unchanged:
210
202
  ```js fragment
211
- { format: 1, // the envelope's own version: a save with a higher format is refused as tooNew (none = 1)
212
- savedAt: 1730000000000, // real time of the save
213
- versions: { world: 5, quests: 2, clock: 1 }, // each part's version (none = 1)
214
- parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } } // each saves.register part's data, by key
203
+ { format: 1, // the envelope's own version: a save with a higher format is refused as tooNew (none = 1)
204
+ savedAt: 1730000000000, // real time of the save
205
+ versions: { world: 5, quests: 2, clock: 1 }, // each part's version (none = 1)
206
+ parts: { world: {...}, quests: {...}, clock: {...}, vars: {...} } } // each saves.define part's data, by key
215
207
  ```
216
- - **Parts and versions**: each `engine.saves.register(key, { version, migrate, save, load })` owns one part. `load` takes one argument, the data: `load: data => …`, never `load(engine, data)`, the shape of a module hook (`npm run check` warns, rule R33). When `save()` changes shape, raise
208
+ - **Parts and versions**: each `engine.saves.define(key, { version, migrate, save, load })` owns one part. `load` takes one argument, the data: `load: data => …`, never `load(engine, data)`, the shape of a module hook (`npm run check` warns, rule R33). When `save()` changes shape, raise
217
209
  `version` by 1 and add `migrate[oldVersion] = data => newData`; load runs the steps in order on a copy, so `load` only sees the current shape.
218
210
  This is how a game's own saved data migrates across its releases (there is no other system): keep one saved file per released game version, never edit it, and load each in a test with `engine.saves.apply(sample)` (the engine does the same for its own parts in `tests/specs/save-compat.mjs`).
219
211
  - **Parts nobody owns are kept**: a part in the loaded save whose module is not installed in this run (a feature turned off for a version) is written
@@ -1,8 +1,9 @@
1
1
  # Camera: first / third person, top-down strategy, fixed shots, switched at runtime
2
2
 
3
- **In this recipe**: 1. Press V to switch between first and third person · 2. What the engine does for you when switching · 3. Other common things ·
4
- 4. Over the shoulder, lock-on framing, mouse lock · 4b. Looking up, ground and walls, driving the view yourself · 4c. Chase camera behind a car · 5. Take over the player ·
5
- 6. Orthographic view, and taking the camera over yourself · 7. Your own camera module
3
+ > **Covers:** the four cameras (follow, first person, strategy, fixed), switching, framing, limits.
4
+ > **Use when:** choosing or tuning how the player sees the game.
5
+ > **Shortest:** `openWorld({ camera: 'firstPerson' })`.
6
+ > **Sections:** 1 Press V to · 2 What the engine · 3 Other common things · 4 Over the shoulder · 4b Looking up, ground · 4c Chase camera behind · 5 Take over the · 6 Orthographic view, and · 7 Your own camera
6
7
 
7
8
  Four cameras; the kind names are always: `'follow'` third-person follow · `'firstPerson'` first person · `'rts'` top-down strategy · `'fixed'` fixed shots.
8
9
  Pick one at the start: `openWorld({ camera: 'firstPerson' })`, or by hand `engine.use(followCamera({ distance: 10 }))` /
@@ -11,25 +12,20 @@ Pick one at the start: `openWorld({ camera: 'firstPerson' })`, or by hand `engin
11
12
 
12
13
  ## 1. Press V to switch between first and third person (copy it)
13
14
  ```js
14
- engine.input.action('toggleView', { label: '切换视角', keys: ['KeyV'] });
15
- engine.onFrame(() => { // UI-type actions read pressed in onFrame
15
+ engine.input.define('toggleView', { label: 'Switch view', keys: ['KeyV'] });
16
+ engine.onFrame(() => { // UI-type actions read pressed in onFrame
16
17
  if (!engine.input.pressed('toggleView')) return;
17
- engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' : 'follow'); // kind is the current kind
18
+ engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' : 'follow'); // kind is the current kind
18
19
  });
19
20
  ```
20
21
  Starting in first person and switching later: `openWorld({ camera: 'firstPerson' })` can still `setCamera('follow')`; you don't need to install two cameras.
21
22
 
22
23
  ## 2. What the engine does for you when switching
23
- - **Target and heading carry over**: the followed character stays the same; the horizontal heading (`yaw`) is carried over, so there is no sudden turn
24
- after switching. Pitch means different things for each camera and is not carried over.
25
- - **First person hides the body but keeps the shadow**: the character model is moved to a dedicated layer (`hideLayer`, default 30) that the camera
26
- cannot see but the shadow camera can; a model that loads later is hidden too. When you switch away the body shows again immediately.
27
- - **Mouse lock**: switching to first person (a key press counts as a user gesture) locks the mouse automatically, Esc leaves; switching away releases
28
- it. No lock on phones.
29
- - **Field of view (fov)**: switching away returns to the value from when the camera was installed; the first-person / strategy cameras each set it
30
- from their own `fov` option.
31
- - **Settings are kept**: the camera you switched away from is kept, so switching back keeps the zoom distance and pitch. To use a different set of
32
- parameters pass options (that camera is rebuilt with the new parameters):
24
+ - **Target and heading carry over** (the followed character and `yaw`; pitch is not, it means different things per camera).
25
+ - **First person hides the body but keeps the shadow**: the model moves to `hideLayer` (default 30), which the shadow camera still sees; a model loaded later too. A light the player carries (within one body width of the body) leaves the hidden body out of its shadow: recipe 34.
26
+ - **Mouse lock**: switching to first person by a key press locks the mouse, Esc leaves, switching away releases it. No lock on phones.
27
+ - **Field of view**: switching away returns to the value from install; first-person and strategy cameras set their own `fov` option.
28
+ - **Settings are kept**: switching back keeps the zoom and pitch; pass options to rebuild that camera with new ones:
33
29
  ```js
34
30
  engine.setCamera('firstPerson', { height: 1.7, fov: 80 });
35
31
  engine.setCamera('follow', { distance: 8, pitch: 0.3 });
@@ -37,30 +33,26 @@ engine.setCamera('follow', { distance: 8, pitch: 0.3 });
37
33
  - A wrong kind name throws and lists the valid ones; a wrong option name gets the closest name suggested in development.
38
34
 
39
35
  ## 3. Other common things
40
- - **Cycling through several**:
41
- `const VIEWS = ['follow', 'firstPerson', 'rts']; engine.setCamera(VIEWS[(VIEWS.indexOf(engine.cameraRig.kind) + 1) % VIEWS.length]);`
36
+ - **Which way yaw points**: first person and follow, yaw 0 looks toward -z, `Math.PI / 2` toward -x, `Math.PI` toward +z (forward = -(sin yaw, cos yaw)). Facing +z: `engine.cameraRig.yaw = Math.PI` (recipe 63 §7).
37
+ - **Cycling**: find `engine.cameraRig.kind` in a list of kinds, `setCamera` the next.
42
38
  - **A fixed camera needs shots first**: `engine.setCamera('fixed', { shots: { hall: { position: [0, 6, 12], lookAt: [0, 0, 0] } }, start: 'hall' })`. A shot stays where it was placed; a view that pans at a fixed angle is the follow camera (section 6).
43
39
  - **Camera-specific methods** exist only after switching: `engine.cameraRig.lookAt(position)` (first person), `cut('name')` (fixed shots),
44
40
  `screenToGround(...)` (rts). Check `kind` before calling.
45
- - **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);` works in that order: `lookAt` aims from the body's
46
- current position, not from the last drawn frame. Call it after the move (the angles do not follow later moves).
47
- - **Saves and new games**: a save holds the view (`yaw`, `pitch`), and `session.load` / `saves.load` put it back. A new playthrough rebuilds the installed camera on the same object, so a kept `const rig = engine.cameraRig` stays valid (one from `setCamera` with options does not). A kind switched to with `setCamera` is not restored: only the heading carries, so call `setCamera` again on `session:start` if the game keeps that choice.
48
- - **Player movement direction follows the camera**: `engine.cameraRig.forward()` / `right()` change automatically after switching.
41
+ - **Teleport, then lookAt**: `await engine.stream.teleport(p); engine.cameraRig.lookAt(target);` in that order: `lookAt` aims once from the body's current position.
42
+ - **Saves and new games**: a save holds the view (`yaw`, `pitch`), and `session.load` / `saves.load` put it back. A new playthrough rebuilds the installed camera on the same object: a kept `engine.cameraRig` stays valid (one from `setCamera` with options does not). A kind switched to with `setCamera` is not restored (only the heading carries): call `setCamera` again on `session:start` to keep the choice.
49
43
  - **Cutscene takeover**: while anyone holds `engine.takeCamera(owner)` (`engine.cameraOverride` is not null) the camera module leaves the camera alone; see [the engine API](../api/engine.md).
50
- - **Shooting games**: bind first-person firing to a mouse-button action, see `19-shooting-picking.md`.
51
44
 
52
45
  ## 4. Over the shoulder, lock-on framing, mouse lock (follow camera)
53
46
  ```js fragment
54
- engine.use(followCamera({ distance: 3, shoulder: 0.7, pitch: 0.15, pointerLock: true })); // shooter / action-adventure view
55
- engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain property)
56
- engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
47
+ engine.use(followCamera({ distance: 3, shoulder: 0.7, pitch: 0.15, pointerLock: true })); // shooter / action-adventure view
48
+ engine.cameraRig.shoulder = -0.7; // switch shoulders at any time (plain property)
49
+ engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, looking at the enemy"; frame(null) lets go
57
50
  ```
58
51
  - **`shoulder`**: meters the aim point (and so the camera) moves to the right along `right()`; negative = left, 0 = centered (default).
59
- - **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` is a state machine: `state` is `off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`, plus `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
52
+ - **`pointerLock`** (default false): a click on the canvas locks the mouse, so moving it turns the view with no dragging; Esc releases, and `engine.page.releaseLock()` releases from code without opening the pause menu. Not on phones. If the browser refuses the lock the camera falls back to dragging; `describe().camera.pointerLock` has `state` (`off` / `unsupported` / `waiting-click` / `requesting` / `locked` / `refused`), `covered` (what sits on the canvas centre and eats the click), `cameraOverride` (a takeover blocks locking) and `lastFailure { reason, agoSec }`; the text line shows the same.
60
53
  The press that locks is swallowed (no `Mouse0`, no click) so it cannot attack or fire; `swallowLockClick: false` delivers it.
61
54
  Leave it off when the mouse buttons are for UI or clicking the ground.
62
- - **`yaw` means which side of the player the camera is on**: `camera = focus + (sin yaw, cos yaw) * distance`, so the camera looks along
63
- `forward() = -(sin yaw, cos yaw)`. To make it look toward a direction, negate it; better not to compute it at all and use `frame(target)`.
55
+ - **`yaw` is which side of the player the camera is on**: `camera = focus + (sin yaw, cos yaw) * distance`, looking along `forward() = -(sin yaw, cos yaw)`; prefer `frame(target)` to computing it.
64
56
  - **`frame(target, { strength = 6 })`**: `target` is an Object3D or `{ x, z }`; call it once when the lock starts, not every frame. While framing,
65
57
  mouse / stick yaw is ignored and a `yaw` you write directly is pulled back, because `frame()` owns the heading; `frame(null)` hands it back.
66
58
  `forward()` turns with it, so camera-relative movement strafes around the target.
@@ -68,8 +60,8 @@ engine.cameraRig.frame(enemy.root); // lock-on: turn to "behind the player, lo
68
60
 
69
61
  ## 4b. Looking up, ground and walls, driving the view yourself (follow camera)
70
62
  ```js
71
- engine.use(followCamera(presets.camera.thirdPersonAction)); // locked mouse, look up ~60° and down, ground shortens the arm, walls pull in
72
- engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the same idea on your own options
63
+ engine.use(followCamera(presets.camera.thirdPersonAction)); // locked mouse, look up ~60° and down, ground shortens the arm, walls pull in
64
+ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the same idea on your own options
73
65
  ```
74
66
  - **Pitch sign**: positive = the camera is above the look point looking down; **negative = looking up**. Looking up needs `minPitch < 0`.
75
67
  - **`ground`** decides what happens when the camera would go below the ground:
@@ -79,10 +71,9 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
79
71
  Default: `'shorten'` when `minPitch < 0`, otherwise `'raise'`.
80
72
  - **Walls** (with `collision()` installed) pull the arm in at once and let it out slowly; the shortest arm is `collision({ cameraMin })` (default 1.5 m).
81
73
  **What blocks by default**: every `addCircle` / `addBox` / `addSegment` collider, over its footprint and up to its height, and every mesh registered
82
- with `engine.rays.addStatic(mesh, { occluder: true })` (`level()` registers its buildings and `col_` meshes). A mesh alone blocks nothing, so a tree
83
- crown or an eave that reaches past its collider lets the camera inside. Register that mesh: it stops the arm and adds no gameplay collider (it does
74
+ with `engine.rays.addStatic(mesh, { occluder: true })` (`level()` registers its buildings and `col_` meshes). A mesh alone blocks nothing (a crown or eave past its collider lets the camera in): registering it stops the arm without a gameplay collider (it does
84
75
  join `engine.raycast`). `collision({ cameraOcclusion: 'colliders' })` tests colliders only.
85
- A content prop or template with `collide` blocks with its whole mesh, crown and eaves included, with no game code. A hand-written mesh stays opt-in: `addStatic(mesh, { occluder: true })`. In a level, `userData.occluder = false` on a node (or a parent) keeps it from blocking, and a hidden mesh does not block (`col_` meshes do). `addStatic` skips `InstancedMesh` and `SkinnedMesh` (dev warns once): rays do not hit them, so give them a collider or register a plain stand-in mesh.
76
+ A content prop or template with `collide` blocks with its whole mesh, crown and eaves included, with no game code. A hand-written mesh stays opt-in: `addStatic(mesh, { occluder: true })`. In a level, `userData.occluder = false` on a node (or a parent) stops it blocking; a hidden mesh does not block (`col_` meshes do). `addStatic` skips `InstancedMesh` and `SkinnedMesh` (dev warns once; rays do not hit them): give them a collider or a plain stand-in mesh.
86
77
  Give the colliders the camera may pass through `occluder: false`
87
78
  (`engine.collision.addCircle(tree, { radius: 0.4, occluder: false })`, or `collide: { circle: 0.4, occluder: false }` / `occluder: false` on a content prop or template): walkers are still stopped, the arm ignores them. A dense forest of
88
79
  blocking trunks collapses the camera onto the player; `collision({ canopyHeight })` covers only the terrain's own trees.
@@ -97,16 +88,16 @@ engine.use(followCamera({ minPitch: -0.9, ground: 'shorten' })); // or the sam
97
88
  ```js fragment
98
89
  let yaw = null;
99
90
  engine.onFrame(dt => {
100
- const q = car.body.rotation(); // car: what addWheeled returned
101
- const want = Math.atan2(2 * (q.x * q.z + q.w * q.y), 1 - 2 * (q.x * q.x + q.y * q.y)) + Math.PI; // a car drives along its +z; the view looks along -z at yaw 0
91
+ const q = car.body.rotation(); // car: what addWheeled returned
92
+ const want = Math.atan2(2 * (q.x * q.z + q.w * q.y), 1 - 2 * (q.x * q.x + q.y * q.y)) + Math.PI; // a car drives along its +z; the view looks along -z at yaw 0
102
93
  yaw ??= want;
103
- yaw += Math.atan2(Math.sin(want - yaw), Math.cos(want - yaw)) * Math.min(1, 5 * dt); // the shortest way round, catching up at 5 per second
94
+ yaw += Math.atan2(Math.sin(want - yaw), Math.cos(want - yaw)) * Math.min(1, 5 * dt); // the shortest way round, catching up at 5 per second
104
95
  engine.cameraRig.setView({ yaw });
105
96
  });
106
97
  ```
107
98
 
108
99
  ## 5. Take over the player: your own movement, facing and lock-on
109
- The engine has no default here: `createPlayer` needs `control` (a preset such as `presets.player.thirdPerson` gives keys relative to the camera, Shift
100
+ The engine has no default here: `addPlayer` needs `control` (a preset such as `presets.player.thirdPerson` gives keys relative to the camera, Shift
110
101
  run, Space jump, turning toward where it walks and `cameraFollow: true`). Each piece below replaces one part and keeps the rest (world record, saving,
111
102
  `describe().player`).
112
103
  ```js fragment
@@ -114,21 +105,21 @@ import { pickTarget, switchTarget } from 'threedog';
114
105
 
115
106
  // how the input steers the player: 'camera' (keys relative to the camera) | (player, input, dt) => ({ x, z, run? }) | null (stand still)
116
107
  let lock = null, hitStun = 0, knockX = 0, knockZ = 0;
117
- const player = engine.characters.createPlayer({ cameraFollow: true, faceMode: 'manual', control: steer }); // moveInput().run reads the bound 'run' action
118
- engine.input.bind({ lockOn: ['KeyQ'], switchTarget: ['KeyR'] }); // no module binds a key by itself
108
+ const player = engine.characters.addPlayer({ cameraFollow: true, faceMode: 'manual', control: steer }); // moveInput().run reads the bound 'run' action
109
+ engine.input.bind({ lockOn: ['KeyQ'], switchTarget: ['KeyR'] }); // no module binds a key by itself
119
110
  const enemies = () => engine.world.query({ kind: 'enemy', near: player.position, radius: 20 });
120
111
 
121
- function steer(player, input, dt) { // called once per fixed step while the input is in charge of the player
122
- const m = engine.characters.moveInput(); // the 'camera' key direction as a value, relative to the camera (a reused object: copy x / z if you keep it)
123
- if (engine.input.pressed('lockOn')) { // pick what is in view; press again to let go
112
+ function steer(player, input, dt) { // called once per fixed step while the input is in charge of the player
113
+ const m = engine.characters.moveInput(); // the 'camera' key direction as a value, relative to the camera (a reused object: copy x / z if you keep it)
114
+ if (engine.input.pressed('lockOn')) { // pick what is in view; press again to let go
124
115
  lock = lock ? null : pickTarget(player, engine.cameraRig.forward(), enemies(), { radius: 15 });
125
116
  engine.cameraRig.frame(lock ? engine.world.view(lock.id) : null);
126
117
  }
127
118
  if (lock && engine.input.pressed('switchTarget')) lock = switchTarget(player, engine.cameraRig.forward(), lock, enemies(), 1) ?? lock;
128
- player.faceMode = lock ? 'target' : 'move'; // 'move' toward velocity | 'camera' along the camera | 'target' toward faceTarget | 'manual' only face() turns it
119
+ player.faceMode = lock ? 'target' : 'move'; // 'move' toward velocity | 'camera' along the camera | 'target' toward faceTarget | 'manual' only face() turns it
129
120
  player.faceTarget = lock ? engine.world.view(lock.id) : null;
130
- if (hitStun > 0) { hitStun -= dt; player.push(knockX, knockZ, dt); return null; } // knockback / roll: fixed velocity, never turns
131
- return m; // the engine calls player.move() with it (one move per step)
121
+ if (hitStun > 0) { hitStun -= dt; player.push(knockX, knockZ, dt); return null; } // knockback / roll: fixed velocity, never turns
122
+ return m; // the engine calls player.move() with it (one move per step)
132
123
  }
133
124
  ```
134
125
  - **`control`** is how the input steers the player: `'camera'` or a function. A function keeps jump and vehicles and only replaces direction
@@ -157,14 +148,14 @@ The default stays perspective. On resize the view height stays `size` and the wi
157
148
  ```js fragment
158
149
  // one fixed isometric shot (shorthand for a single shot named 'main')
159
150
  engine.setCamera('fixed', { position: [14, 14, 14], lookAt: [0, 0, 0], projection: 'orthographic', size: 16 });
160
- // per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
151
+ // per shot: shots: { hall: { position, lookAt, projection: 'orthographic', size: 12 }, yard: { position, lookAt } } // yard stays perspective
161
152
  // follow the player from a fixed angle
162
153
  engine.setCamera('follow', { pitch: 0.6, yaw: 0.8, distance: 20, projection: 'orthographic', size: 14, mouseLook: false, ground: 'none' });
163
154
  ```
164
155
  **A view that pans at a fixed angle** (isometric, tactics, city builders) is that follow camera, not a fixed shot. `mouseLook: false` stops the drag and the wheel from moving the view, and `ground: 'none'` stops hills from tilting it. It follows the player, or with no player any object the game moves:
165
156
  ```js fragment
166
- const view = new THREE.Object3D(); // the point the view is centered on
167
- engine.cameraRig.follow(view); // again on 'session:start': a new playthrough follows the player or nothing
157
+ const view = new THREE.Object3D(); // the point the view is centered on
158
+ engine.cameraRig.follow(view); // again on 'session:start': a new playthrough follows the player or nothing
168
159
  engine.onFrame(dt => { view.position.x += engine.input.axis.x * 12 * dt; view.position.z -= engine.input.axis.y * 12 * dt; });
169
160
  ```
170
161
  `smoothing` sets how tightly the view keeps up (higher is tighter).
@@ -181,11 +172,11 @@ Several holders can take it (a cutscene, then a named view on top): the latest i
181
172
 
182
173
  ```js fragment
183
174
  let t = 0;
184
- const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
175
+ const cam = engine.takeCamera('my-orbit', { focus: engine.player.position }); // focus (optional): where the world loads around
185
176
  const frame = engine.onFrame(dt => {
186
177
  t += dt; engine.camera.position.set(Math.cos(t) * 12, 8, Math.sin(t) * 12); engine.camera.lookAt(0, 1, 0);
187
178
  });
188
- // done: frame.remove(); cam.remove(); // the rig resumes from its own state
179
+ // done: frame.remove(); cam.remove(); // the rig resumes from its own state
189
180
  ```
190
181
 
191
182
  To draw through your own three.js camera, assign it. A real `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` is taken as it is, and any other class, a subclass too, is refused:
@@ -194,12 +185,12 @@ To draw through your own three.js camera, assign it. A real `THREE.PerspectiveCa
194
185
  const original = engine.camera;
195
186
  const ortho = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 500);
196
187
  ortho.position.set(10, 10, 10); ortho.lookAt(0, 0, 0);
197
- engine.camera = ortho; // rendering, post, picking, shadows, audio and the camera module go on with it
188
+ engine.camera = ortho; // rendering, post, picking, shadows, audio and the camera module go on with it
198
189
  // give it back: engine.camera = original;
199
190
  ```
200
191
 
201
192
  The aspect follows the canvas, on assignment and on every resize: an orthographic camera keeps its height and its width follows. `engine.autoView.manual('aspect')` before assigning keeps your own frustum. The engine leaves `far` and `fov` of a real orthographic camera alone.
202
- A camera module goes on placing the camera you assigned, and a camera you assign during a shot stays until the next view is asked for. `projection: 'orthographic', size` sets the height of a real orthographic camera; on a real perspective one the rig's own orthographic camera stands in until the next perspective view, which brings yours back. `pixelSnap` writes the height it needs. A chain taken with `engine.post.own()` is yours to point at the new camera, and a `pixelGrid` you made yourself keeps the camera you gave it.
193
+ A camera module goes on placing the camera you assigned, and one assigned during a shot stays until the next view is asked for. `projection: 'orthographic', size` sets the height of a real orthographic camera; on a real perspective one the rig's own orthographic camera stands in until the next perspective view brings yours back. `pixelSnap` writes the height it needs. A chain taken with `engine.post.own()` is yours to point at the new camera; a `pixelGrid` you made keeps the camera you gave it.
203
194
 
204
195
  **Side view (side-scroller).** `presets.player.sideScroller` moves the player along world X only (A / D, `z` stays) and turns it toward the move. Face the camera along -Z with `yaw: 0`, so +X is screen right (`yaw: Math.PI` looks from the far side and flips left and right), on `followCamera`:
205
196
  ```js fragment
@@ -208,6 +199,6 @@ engine.use(followCamera({ projection: 'orthographic', size: 15, yaw: 0, pitch: 0
208
199
 
209
200
  ## 7. Your own camera module
210
201
  Everything else in the engine reads only what `modules/camera/contract.js` lists from `engine.cameraRig`: `forward()` / `right()` (control: 'camera',
211
- faceMode 'camera', targeting), `follow(object, opts?)` (createPlayer, getting in and out of a vehicle), `focusPoint()` (photo, where the world loads)
202
+ faceMode 'camera', targeting), `follow(object, opts?)` (addPlayer, getting in and out of a vehicle), `focusPoint()` (photo, where the world loads)
212
203
  and `screenToGround(ndcX, ndcY)` (click-to-move, placing things; every built-in kind has it). A module named `cameraRig` with those five methods
213
204
  replaces the built-in cameras: `tests/contract/fakeCamera.js` in the engine repository is one in ~35 lines and the player walks with it.