threedog 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -8,9 +8,9 @@
8
8
  - `antialias?: boolean` MSAA anti-aliasing (kept with post effects on), default on for desktop and off for low-tier devices; with a renderer of your own, its own antialias. It is fixed with the canvas: a player's settings row changes it at the next launch
9
9
  - `pixelRatio?: number` Render resolution, default min(device pixel ratio, 1.5); the low tier uses at least 0.75 x device pixel ratio (never below 1). describe().render.scale reports it
10
10
  - `pixelSize?: number` Real screen pixels per art pixel, a whole number from 1 up: art pixels of exactly one size at any display scale, through page zoom and moves to another display. Sets image-rendering: pixelated, antialias defaults to off, adaptive resolution stops, and the last few real pixels (fewer than k) at the right and bottom stay empty. Example: `createEngine({ canvas, pixelSize: 3 })`
11
- - `adaptiveResolution?: boolean` Automatically lower resolution when the frame rate is too low, default true. Never silent: a dev warning once, and describe().render.scale.autoLowered
11
+ - `adaptiveResolution?: boolean` Automatically lower quality when frames cost too much (resolution, and post effects that declare a cheaper or skippable form; engine.adaptive.steps), default true. Never silent: a dev warning once, and engine.budget.notice()
12
12
  - `targetFps?: number` Target frame rate for automatic resolution lowering, default 55
13
- - `ui?: UIOptions` All screen UI: replace or turn off any part (loading, toast, title, hud.marker, hud.counter, hud.bar; the default title screen is off), and the look of the default parts (theme, css, fonts, templates). Example: `createEngine({ canvas, ui: { loading: { title: 'My Game' }, title: { title: 'My Game' }, toast: false } })`
13
+ - `ui?: UIOptions` All screen UI: replace or turn off any part (loading, toast, title, hud.marker, hud.counter, hud.bar, hud.button; the default title screen is off), and the look of the default parts (theme, css, fonts, templates). Example: `createEngine({ canvas, ui: { loading: { title: 'My Game' }, title: { title: 'My Game' }, toast: false } })`
14
14
  - `audio?: AudioConfig` Volume of each channel, 0–1
15
15
  - `fov?: number` Camera field of view (degrees), default 55
16
16
  - `near?: number` Camera near clipping plane (meters), default 0.3
@@ -19,6 +19,7 @@
19
19
  - `bindings?: Readonly<Record<string, string | readonly string[]>>` The game's keys per action (keyboard, 'Mouse0', gamepad 'PadA' in one list), owner 'game': replaces the basics (move / confirm / cancel / UI cursor) and binds every other action, e.g. { interact: ['KeyE', 'PadX'], ...presets.bindings.dialogNumbers }. Same as engine.input.bind(map)
20
20
  - `saveKey?: string` Save name prefix; must differ when several games share one site, default 'game'
21
21
  - `joystick?: 'auto' | boolean` On-screen joystick: 'auto' (only on touch devices) / true / false
22
+ - `blockBrowserKeys?: boolean` While playing (no menu, not paused), keys the game binds do not reach the browser, e.g. Ctrl+S; true by default. In dev builds F5, Ctrl+R, F12 stay the browser's (recipe 58)
22
23
  - `headless?: boolean` Headless mode: no real-time loop and no per-frame rendering, advances only on step() (for tests and screenshots). Adding ?threedog-headless to the URL also turns it on
23
24
  - `validate?: boolean` (experimental) Check parameter names at runtime and warn on misspelled names (the console prints "did you mean xxx"), default true; a release build can write false to turn it off
24
25
  - `decoders?: string` (experimental) Directory of Draco/KTX2 decoders (a URL containing draco/ and basis/), for when they live on a CDN. Normally not needed: the decoders bundled with three are packed by vite automatically
@@ -33,15 +34,15 @@
33
34
 
34
35
  ## engine methods
35
36
  - `engine.actorPosition(id?: string) → { x, y, z } | null` — Where an actor is now (default engine.actor): the player's position for 'player' (engine.focus without a player), else its model or world record position; null when unknown. Example: `engine.actor = 'boat_1'; engine.actorPosition()`
36
- - `engine.catalog(id?: string | { find?: string }) → any` — What this game can do, read from the existing registrations (modules, ops, save parts, describe, params schemas). No argument: the short list, an ARRAY of { id, kind, label, ops, saves, ... } (read .id, not Object.keys); a module id / op name: that entry expanded (null if unknown); { find }: the short list filtered. recipes/51-capability-catalog.md. Example: `engine.catalog().map(s => s.id); engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']`
37
+ - `engine.catalog(id?: string | { find?: string }, o?: { offered?: any[] }) → any` — What this game can do, read from the existing registrations (modules, ops, save parts, describe, params schemas). No argument: the short list, an ARRAY of { id, kind, label, ops, saves, ... } (read .id, not Object.keys); a module id / op name: that entry expanded (null if unknown); { find }: the short list filtered. 'picture': the picture menu, one row per capability (on now, runs here, cost class, one way on, recipe, main limit) and the combination checks; o.offered adds effects not in the chain yet (factories with .about). 'module:<id>' / 'op:<name>' / 'capability:<id>' pick the kind (a bare name tries picture, post, shadows first). recipes/51-capability-catalog.md. Example: `engine.catalog().map(s => s.id); engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']`
37
38
  - `engine.takeCamera(owner: string | ({ owner: string } & Partial<CameraOverride>), opts?: Partial<CameraOverride>) → OwnerHandle` — Take the camera over (camera modules leave it alone) until remove(); the latest holder is in charge, releasing hands it back to the previous one
38
- - `engine.mod(name: string, opts: import('./gameplay').ModOptions) → import('./gameplay').ModHandle` — (experimental) The one way several systems change a shared quantity: an entry per owner, combined by layer, ended by its handle; nothing remembers an old value. Example: `engine.time.channel('enemies'); engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }) // bullet time on a channel the game made`
39
+ - `engine.mod(name: string, opts: import('./gameplay').ModOptions) → import('./gameplay').ModHandle` — The one way several systems change a shared quantity: an entry per owner, combined by layer, ended by its handle; nothing remembers an old value. Example: `engine.time.channel('enemies'); engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }) // bullet time on a channel the game made`
39
40
  - `engine.wrap(target: T, method: string, fn: (next, args) => any, opts?: { owner?: string }) → Handle` — (experimental) The one way to change what a module's public method does without copying the module: fn(next, ...args) runs instead of it; call next(...args) for the method (do work before, after, or skip it). Several wrappers compose (the last wrapped runs first); remove() takes one out; listed in describe().wraps. Private (_) methods throw. The methods a module promises are its contract.js api. Example: `engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => carried() + weightOf(id) * n > 30 ? false : next(id, n, o), { owner: 'weight' })`
40
41
  - `engine.setCamera(kind: CameraKind, opts?: object) → CameraRig` — Switch the camera at runtime between kinds, once a camera module is installed (openWorld installs followCamera; with none it throws camera-none naming the module to install, e.g. engine.use(fixedCamera({ position, lookAt }))): the target and horizontal heading carry over; the first-person camera hides the character body automatically (the shadow stays) and locks / releases the mouse; the camera switched out is kept, with its parameters, for switching back. Passing opts rebuilds this kind of camera with the new parameters. A wrong kind throws and lists the available options. Example: `engine.onFrame(() => { if (engine.input.pressedRaw('toggleView')) engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' : 'follow'); });`
41
42
  - `engine.use(...mods: (ModuleInput | { replaces })[])` — Install one or more modules (in order; dependencies must be installed first). A last argument { replaces: 'slot' } swaps the module that holds that exclusive slot: it is unloaded first (its handles, changes and dispose) and put back if the new install fails. Example: `engine.use(myInventory(), { replaces: 'inventory' })`
42
43
  - `engine.unuse(name: string)` — Unload one installed module: its tracked handles, its slots and ctx.mod entries, its dispose. What it added some other way stays (dev reports a picture module's leftovers). Throws while another module still requires it. To swap a holder use engine.use(mine(), { replaces: 'slot' }). Example: `engine.unuse('rain');`
43
44
  - `engine.has(name: string) → boolean` — Whether a module of this name, or a provider of this capability, is installed. Installed only: engine.explain({ module: name }) says whether it is running
44
- - `engine.setGround(g: Partial<Ground>)` — Set the ground (called by the terrain and level modules); missing parts fall back to flat ground
45
+ - `engine.setGround(g: Partial<GroundProvider>)` — Set the ground (called by the terrain and level modules); missing parts fall back to flat ground
45
46
  - `engine.surface(x: number, z: number, refY?: number) → number` / `surface(at: PositionLike, refY?: number) → number` — Ground height (meters) at (x, z); a position or object also works: engine.surface(mesh.position). For multi-layer ground (bridges, caves, interiors) pass a reference height refY: returns the highest layer not above refY + one step (0.45 m), so standing under a bridge gives the ground and standing on it gives the deck; without it the highest layer is used (as before). Procedural terrain and flat ground have one layer and ignore refY. Off the outline of terrain({ shape }) it is -Infinity (no ground there; engine.ground.has(x, z) says so as a boolean)
46
47
  - `engine.slope(x: number, z: number, refY?: number) → number` / `slope(at: PositionLike, refY?: number) → number` — Slope at (x, z); a position or object also works
47
48
  - `engine.groundType(x: number, z: number, refY?: number) → string` / `groundType(at: PositionLike, refY?: number) → string` — Ground type at (x, z) (for footsteps, particles); a position or object also works. 'void' off the outline of terrain({ shape })
@@ -53,9 +54,9 @@
53
54
  - `engine.thing(idOrObj: string | Object3D) → Thing` — What a thing is and what a save keeps: a world record id, an engine.add id or name, or any Object3D (its registered ancestor). object is the live Object3D (not enumerable). Throws with the closest id when nothing matches. Change it with ops.run('thing.set' / 'thing.remove', { id, ... }). Example: `engine.thing('windmill').saved // 'code'`
54
55
  - `engine.remove(...objs: Object3D[])` — Fully delete an object (use it when you no longer want the object): removes it from its parent, unregisters rays, and releases the geometry and materials of it and its children (textures and geometry / materials shared by assets are not released)
55
56
  - `engine.onFixed(fn: (dt: number) => void, opts?: { channel?, phase? }) → Handle` — Fixed-step logic (60 times per second, dt in fixed seconds): movement, physics, cooldowns, and gameplay keys (read pressed() here: a per-step snapshot, independent of frame rate). dt is real seconds (always 1/60) unless { channel } names a time channel: then the channel's scaled dt. phase 'early' (default) runs before every module fixed hook (the player has not moved yet this step); 'late' after them, before the clock (hit checks, reading this step's result). Returns a handle { remove() }. Example: `engine.onFixed(() => checkHits(engine.player.position), { phase: 'late' })`
56
- - `engine.onFrame(fn: (dt: number) => void) → Handle` — Once per frame (dt in frame seconds): animation, camera, UI and UI keys (menus read this frame's latest input). Gameplay keys belong in onFixed. Returns a handle { remove() }
57
- - `engine.onRender(fn: (ctx) => void, opts?: { when?: 'before' | 'after' }) → Handle` — Around the main frame render, after the camera update and batching. when 'before' (default): render into your own render target here (mirror, minimap, portal, picking); the render target is reset to the screen afterwards. 'after': right after the frame (read pixels). The main frame render itself stays the engine's (post chain). Returns a handle { remove() }. Example: `const rt = new THREE.WebGLRenderTarget(256, 256); engine.onRender(({ renderer, scene }) => { renderer.setRenderTarget(rt); renderer.render(scene, mapCam); });`
58
- - `engine.renderOnce(target?: import('three').RenderTarget | null, camera?: import('three').Camera)` — Draw one picture now, outside the loop, on either renderer. `renderOnce()`: the frame the player sees, onto the canvas through engine.post (read the canvas in the same task, as photo mode does). `renderOnce(target)`: that frame through engine.post into a render target (the canvas's pixels). `renderOnce(target, camera)` with another camera: the scene from that camera, without post. On WebGPURenderer each call is a fresh node frame, so two calls in one task give two pictures (a RenderPipeline draws its scene pass once per frame). Example: `engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png'); engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target`
57
+ - `engine.onFrame(fn: (dt: number) => void) → Handle` — Once per frame (dt in frame seconds, capped at the fixed step's 0.1 s; 0 on the frame back from a hidden tab): animation, camera, UI and UI keys (menus read this frame's latest input). Gameplay keys belong in onFixed. Returns a handle { remove() }
58
+ - `engine.onRender(fn: (ctx) => void, opts?: { when?: 'before' | 'after' }) → Handle` — Around the main frame render, after the camera update and batching. when 'before' (default): render into your own render target here (mirror, minimap, portal, picking); the render target is reset to the screen afterwards. 'after': right after the frame (read pixels). The main frame render itself stays the engine's (post chain). fn gets { renderer, scene, camera, dt }: dt is this frame's seconds, the same value onFrame gets (no performance.now() bookkeeping needed). Returns a handle { remove() }. Example: `const rt = new THREE.WebGLRenderTarget(256, 256); engine.onRender(({ renderer, scene }) => { renderer.setRenderTarget(rt); renderer.render(scene, mapCam); });`
59
+ - `engine.renderOnce(target?: import('three').RenderTarget | null, camera?: import('three').Camera)` — Draw one picture now, outside the loop, on either renderer. `renderOnce()`: the frame the player sees, onto the canvas through engine.post (read the canvas in the same task, as photo mode does). `renderOnce(target)`: that frame through engine.post into a render target (the canvas's pixels: tone mapped, in the output color space, display values). `renderOnce(target, camera)` with another camera: the scene from that camera, without post, as three draws into a target: linear and not tone mapped (right as a texture on a material, which three then tone maps and encodes; read back as image pixels it looks dark). On WebGPURenderer each call is a fresh node frame, so two calls in one task give two pictures (a RenderPipeline draws its scene pass once per frame). Example: `engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png'); engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target`
59
60
  - `engine.bakeProbes(opts: { bounds, spacing, resolution?, include?, owner? }) → Promise<ProbeSet>` — (experimental) Bake a grid of light probes from the scene as it is now: three's probe grid renders a cube at every grid point and keeps spherical harmonics, and every lit pixel inside the grid then takes its own interpolated light, on WebGL and WebGPU alike. The grid adds to whatever ambient light the scene has (hemi, environment), which the bake also saw: lower those where the probes take over (a warning and describe().render.probes say so). Outside the grid there is no probe light. A load-time cost, not per frame: 6 renders per probe, a few probes per task so the page keeps drawing; ship the result with `toJSON()` + `engine.loadProbes(json)` instead of baking at every start. Adding a grid recompiles the lit materials once: bake at start-up, not mid-play. Example: `const probes = await engine.bakeProbes({ bounds: { min: [-20, 0, -20], max: [20, 6, 20] }, spacing: 4, include: o => !o.userData.moving }); saveFile('probes.json', JSON.stringify(probes.toJSON()));`
60
61
  - `engine.loadProbes(json: ProbeData, opts?: { owner?: string }) → ProbeSet` — (experimental) A probe set from a file made by `handle.toJSON()` (no baking), on either renderer whichever one baked it. A wrong shape is refused with code `probes-data` and nothing is added. Example: `const probes = engine.loadProbes(await (await fetch('probes.json')).json());`
61
62
  - `engine.loadLightmap(file: string | ArrayBuffer, opts?: { owner?: string }) → Promise<Lightmap>` — (experimental) Put a baked lightmap on the scene: `threedog bake light` wrote the file from the meshes the game marked `userData.static = true`; this rebuilds each with its second UV set and sets plain `material.lightMap`, on WebGL and WebGPU alike. Call it once the level is built, with its lights as they will be played. Nothing runs per frame. Keep the sun real-time; the ambient light the bake saw (hemisphere, environment) has to go, or it counts twice. A wrong file is refused with code `lightmap-data` and nothing is changed. `material.lightMapIntensity` is yours. describe().render.lightmap says what was skipped, moved or doubled. Example: `const light = await engine.loadLightmap('light/level.lightmap');`
@@ -68,14 +69,14 @@
68
69
  - `engine.start() → Promise<this>` — Start: initialize modules, preload assets, wait for the world to be ready
69
70
  - `engine.haltLoop(owner?: string | { owner?: string }) → OwnerHandle` — Pause the real-time loop: the picture stops and even rendering stops, only step() advances (for tests and screenshots). Use freeze() for a game menu pause
70
71
  - `engine.nextFixed(fn: () => T) → Promise<T>` — Run fn at the start of the next fixed step (via commits); a Promise of fn's value
71
- - `engine.freeze(owner?: string | { owner?, kind?, ambient? }, opts?: { kind?, ambient? }) → OwnerHandle` — Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, tick and every time view but ambient stop), frame hooks and rendering continue and the UI works. So gameplay logic (movement, timing, quest checks, cutscene waits) belongs in fixed, or check engine.frozen first in frame. owner is the freezer's name, default 'game'. uniforms.uTime (wind, water, clouds), skeletal animation and particles keep moving while frozen; { ambient: true } stops them too (a still)
72
+ - `engine.freeze(owner?: string | { owner?, kind?, still? }, opts?: { kind?: 'title'; still?: boolean }) → OwnerHandle` — Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, tick and every time view but ambient stop), frame hooks and rendering continue and the UI works. So gameplay logic (movement, timing, quest checks, cutscene waits) belongs in fixed, or check engine.frozen first in frame. owner is the freezer's name, default 'game'. uniforms.uTime (wind, water, clouds), skeletal animation and particles keep moving while frozen; { still: true } stops them too (a still)
72
73
  - `engine.step(seconds: number, opts?: { render?, frameEvery?, describe? }) → GameState | null` — Advance seconds of fixed-step time synchronously; seconds must be a finite number >= 0: 0 advances nothing (no step, no render), negative or non-finite throws (code step-seconds), any positive value runs at least one fixed step (60Hz; time channels and the calendar clock.now / sky time of day run at their own speeds; frame hooks run once every frameEvery fixed steps, default 2; describe: false returns null instead of building describe()). jobs ignore real time and finish every frame; results of stream's synchronous build are attached to the scene before returning. When render is true (default) one frame is rendered at the end. Returns the describe() result after advancing
73
74
  - `engine.skip(opts: SkipOptions) → Promise<{ seconds: number; clock:…` — Skip game time forward (sleep until morning, wait an hour) without stepping every fixed step. clock.after / every, sky.at / daily / between, day:start and season:change fire in time order as if stepped (each crossing once); world records with far catch up the span in one far(rec, dt). onFixed, module fixed hooks, physics and near simulation do not run; every time view (tick, real, ambient, channels, calendar) moves as if stepped. Input is locked and gameplay frozen during the skip; emits time:skip. fade 0 (default): the time has moved when skip returns. fade > 0: fade out, jump, save, fade in; the Promise resolves after the fade in (it needs frames). session.newGame / load / quit cancel a running skip: it resolves null. Example: `await engine.skip({ to: '06:00' })`
74
75
  - `engine.checkSkip(seconds: number, opts?: { ignore?: string[] }) → Promise<{ ok: boolean; code?: 'fr…` — Consistency check: engine.skip({ seconds }) vs stepping the same span in fixed steps; compares the saved state. Leaves the world at the stepped state (use a scratch playthrough or a test). Example: `const r = await engine.checkSkip(600); if (!r.ok) console.log(r.diffs);`
75
76
  - `engine.checkSave(opts?: { ignore?: string[] }) → Promise<{ ok: boolean; diffs: { p…` — Consistency check: save -> load gives the same saved state back (nothing is written to the browser). Example: `const r = await engine.checkSave(); if (!r.ok) console.log(r.diffs);`
76
77
  - `engine.describeText(opts?: { radius?, full?, path? }) → string` — The same information as English text, summary first: at most 30 lines (standard lines, the 5 nearest things, the game's describe.add sections, one line per module with its key counts, the engine tables such as shared / slots / owned as one count line), ending with how to expand. { path: 'world.byKind' } returns one part of describe() as JSON; { full: true } returns everything (all nearby things, every module's full data). Example: `engine.describeText() engine.describeText({ path: 'quests' }) engine.describeText({ full: true })`
77
78
  - `engine.explain(q: { op, args?, actor? } | { value: string } | { thing } | …) → { ok, code?, text, detail?, recent?, events?, … }` — Why something is the way it is. { op, args?, actor? }: text says whether it can run now, and if not the reason and the op's note on fixing it (reason first); detail has the last attempt and the events around it; recent / events are the raw last 5 attempts and event names within a step of the last one. { value }: who last wrote a watched value, with its history. { thing: id }: where the id comes from; detail is the whole ThingExplanation. { module } / { capability }: whether it runs and what blocks it. Other keys are answered by modules (definition field explain: { key(e, value, query) { return { ok, text } } }); the quests module answers { quest: id }. Example: `engine.explain({ op: 'shop.buy', args: { shop: 'bakery', item: 'bread' } }).text // 'shop.buy {...} cannot run now: noMoney (Not enough gold)'`
78
- - `engine.profile(on: boolean)` / `profile() → Record<string, number> | null` — Module hook timing: pass true to turn on, false to turn off (returns the engine); with no argument returns { moduleName: average milliseconds per rendered frame } and resets, or null when not on
79
+ - `engine.profile(on: boolean)` / `profile() → Record<string, { ms: nu… | null` — Module hook timing, on by default in dev builds: pass true to turn on afresh, false to turn off (returns the engine); with no argument returns { moduleName: { ms (median), mean, p95 } } per frame over the last 300 frame-hook cycles, or null when off. Only the module's own hooks count; fixed hooks count one fixed step per frame, its dearest (a slow frame's catch-up steps are not the module's cost)
79
80
  - `engine.dispose(opts?: { keepContext?: boolean })` — Destroy the engine: stop the main loop, call each module's dispose(e) in reverse install order, then reclaim listeners, timers, audio, UI and GPU memory (scene, assets cache, post-processing, renderer). After that no callbacks fire and step() returns null. Safe to call repeatedly. Don't use it for level changes; use level.track(handle). The engine's own renderer gives its WebGL context back (browsers keep about 16 live ones), so that canvas cannot host a new engine; keepContext: true keeps it. A renderer passed to createEngine({ renderer }) is never released.
80
81
  - `engine.counts() → EngineCounts` — Counts for leak hunting: they should not keep growing after repeatedly entering / leaving levels or opening / closing windows. geometries / textures come from three.js renderer.info.memory (counted only after rendering)
81
82
 
@@ -89,7 +90,7 @@
89
90
  - `focus: Vector3` Camera focus, updated every frame by the camera module: terrain, models etc. load around it. The center of gameplay simulation is world.anchor (the player by default), which does not follow the camera
90
91
  - `ground: Ground` Current ground
91
92
  - `movement: Readonly<MovementProfile>` Shared parameters for whether a character can walk somewhere (set by createEngine({ movement }), read-only); same-named options of individual modules are only overrides
92
- - `player: Character | null` The player (exists only after characters.createPlayer()). Its position belongs to the character's mover: other systems request movement (placeAt / move / vehicle enter), don't modify position directly
93
+ - `player: Character | null` The player (exists only after characters.addPlayer()). Its position belongs to the character's mover: other systems request movement (placeAt / move / vehicle enter), don't modify position directly
93
94
  - `actor: string` World record id of the one the local user controls (default 'player'): interactions, trigger zones, marker distances, the world simulation center and ops (ctx.actor) use it. Set it to hand control to a vehicle or squad member
94
95
  - `phase: 'constructed' | 'starting' | 'loading' | 'ready' | 'running' | 'disposed'` Where the engine is in its life: 'constructed' (start() not called) -> 'starting' (modules init) -> 'loading' (assets and the world; in both frame hooks only, no fixed step, so no game time passes and every machine opens at tick 0) -> 'ready' (world built: fixed steps run, engine:ready fires) -> 'running' (start() resolved) -> 'disposed'.
95
96
  - `ready: boolean` phase is 'ready' or 'running': the world is built and the loading screen is gone (every "is it ready" in the engine is such a boolean property)
@@ -126,7 +127,6 @@
126
127
  - `plugins: { add, off, on, list }` The plugins folder: files in the game's plugins/ plugged at start by what they export (core/engine/plugins.js); describe().slots lists them (add() off() on() list())
127
128
  - `rays: Rays` Ray registry (what engine.raycast hits)
128
129
  - `jobs: Jobs` Frame-spread job scheduler
129
- - `commits: Commits` (experimental) Background results that affect gameplay take effect on a fixed tick (chunk collision, spread jobs with apply...), see Commits
130
130
  - `threads: Threads` (experimental) Worker pool (createEngine({ threads })): lane() for your own worker script, pure() for self-contained functions, array() for shared typed arrays. Results that affect gameplay go through commits
131
131
  - `ops: Ops` One entry point for actions players and NPCs decide to do: define / run / can / list / recent, see Ops and recipes/23-ops.md
132
132
  - `views: Views` Named fixed camera views for repeatable screenshots: define / show / release (recipes/46-blender-art-route.md)
@@ -136,17 +136,17 @@
136
136
  - `startup: StartupReport | null` Startup timing report (null until start() completes)
137
137
  - `uniforms: EngineUniforms` This engine's shader uniforms, read by the built-in effects (wind, clouds, season, water, sky, rain). Share these objects in your own ShaderMaterial or patch instead of making your own uTime. Weather and sky write them; uTime is engine.time.now('ambient'). Example: `new THREE.ShaderMaterial({ uniforms: { uTime: engine.uniforms.uTime }, vertexShader, fragmentShader });`
138
138
  - `waterLevel: number` Global water level (meters); -Infinity when there is no water
139
- - `debug: DebugOverrides & { panel: DebugPanel | null }` Diagnostic overrides and view modes with an owner (override / clear / view: core, always there); panel is the F3 panel, null without the debug() module
139
+ - `debug: DebugApi` Diagnostic overrides and view modes with an owner (override / clear / view: core, always there); panel is the F3 panel, null without the debug() module
140
140
  - `shadows: Shadows` Shadow engineering on lights you hand in: enabled, cascades, box, budget, include (recipes/45): core, always there
141
141
  - `autoView: View` The camera and drawing-buffer values the engine changes on its own: manual() takes one (recipes/52): core, always there
142
142
  - `shaderTerms: Terms` Your own cloud shadow or season tint in place of the engine's (recipes/52): core, always there
143
- - `stateApplied: boolean` (experimental) Scenario is ready: start() completed, and the URL parameters / the latest applyState have all been applied. Tests and screenshots wait for it: page.waitForFunction(() => window.engine?.stateApplied)
143
+ - `stateApplied: boolean` Scenario is ready: start() completed, and the URL parameters / the latest applyState have all been applied. Tests and screenshots wait for it: page.waitForFunction(() => window.engine?.stateApplied)
144
144
  - `stateRefused: { key: string, value: any, reason: string }[]` (experimental) What the URL parameters or the latest applyState could not do, e.g. ?weather=typo. Read it after stateApplied
145
145
  - `headless: boolean` Whether in headless mode (createEngine({ headless: true }))
146
146
  - `halted: boolean` Whether the real-time loop is stopped: only step() advances the game (headless mode starts this way)
147
147
  - `fps: number` Smoothed frame rate
148
148
  - `frozen: boolean` Is anyone freezing gameplay?
149
- - `still: boolean` True while a freeze asked for a full still (freeze(owner, { ambient: true })): frame code that moves things reads this, as animation and particles do
149
+ - `still: boolean` True while a freeze asked for a full still (freeze(owner, { still: true })): frame code that moves things reads this, as animation and particles do
150
150
  - `describe: { add }` Call engine.describe(opts?: { radius?: number }) to get the current game state (a plain object, JSON.stringify-able); radius is how far counts as "nearby" (meters, default 30).
151
151
  - `inspect: { scene, materials, perf }` What is around an actor or a spot, and what that actor can do now (each op offer checked with can, possible first, at most 8; failed ones carry code and the op's reasons note). at: a world record id (that actor), [x, z] / { x, z } (a spot, ops as the player), or nothing (the player). radius default 10 m. Example: `engine.inspect(); // { actor: 'player', at: { x, z }, near: [...], ops: [{ op: 'shop.buy', args, ok: false, code: 'noMoney', why: 'Not enough gold' }] }`
152
152
 
@@ -180,7 +180,7 @@
180
180
  - `describe(e: Engine, ctx: DescribeContext) → any` — Optional: add state to engine.describe(). The (JSON-able) return value goes into the result keyed by the module name; nothing is added if it returns nothing. It may also fill in the standard fields of ctx.out, or use ctx.near() to report "nearby things"
181
181
  - `counts(e: Engine) → number | Record<string, number>` — Optional: leak-hunting counts for engine.counts(), put there under the module name (a number or an object of numbers that should not keep growing)
182
182
  - `applyState(e: Engine, params: StateParams) → void | PositionLike | { refused } | Promise<void>` — Optional: handle the keys of engine.applyState that this module owns (e.g. calendar handles time and season); for at, return the place's position; return { refused: { key: reason } } for a value it cannot apply
183
- - `dispose(e: Engine)` — Optional: called on engine.dispose() (in reverse install order). Only clean up what the core cannot: Workers, the physics world, real-time timers, Audio nodes you connected yourself. Events, onFixed / onFrame, clock timers, jobs, stream, ray registrations and GPU memory in the scene are reclaimed by the core; DOM listeners attached to engine.signal and UI attached to engine.uiRoot are cleaned up automatically too
183
+ - `dispose(e: Engine)` — Optional: called on engine.dispose() (in reverse install order). Only clean up what the core cannot: Workers, the physics world, real-time timers, Audio nodes you connected yourself. Events, onFixed / onFrame, clock timers, jobs, stream and ray registrations are reclaimed by the core. GPU memory is its creator's: free what you put in the scene with ctx.track({ remove: () => engine.remove(mesh) }) (design.md 6.2); DOM listeners attached to engine.signal and UI attached to engine.uiRoot are cleaned up automatically too
184
184
 
185
185
  ## createEngine({ ui })
186
186
  - **UIOptions** createEngine({ ui }): the look of the default parts (theme, css, fonts, templates); every other key is a part name
@@ -24,6 +24,7 @@
24
24
  - `ui:close` [id: string] A window was closed
25
25
  - `settings:shadows` [on: boolean] Shadows were toggled
26
26
  - `settings:change` [values: Record<string, any>] A value in the settings menu changed (the argument is all setting values)
27
+ - `post:add` [name: string] A post effect was added (its name)
27
28
  - `water:add` [body: WaterBody] A water body was added
28
29
  - `water:remove` [body: WaterBody] A water body was removed
29
30
  - `day:start` [day: number] A new day (the argument is the day number, starting at 1; needs the calendar module)
@@ -93,10 +94,10 @@
93
94
  - `net:close` [{}] Client (net): connection lost
94
95
  - `net:sync` [{ tick: number; full: boolean }] Client (net): host state applied (full: a whole snapshot, else a diff); redraw UI from state here
95
96
  - `net:result` [{ seq: number; name: string; ok: boolean; code: string | null; value… Client (net): the host's answer to an op request (seq from ops.run's return value; tick is the host's), sent after the state it caused
96
- - `engine:error` [EngineError] A gameplay error in development / testing; gameplay is frozen (error severity levels, see engine.error)
97
+ - `engine:error` [EngineError] A gameplay error: in development / testing gameplay is frozen; a release build keeps running and sends it once per site (engine.error holds the first; error severity levels, see engine.error)
97
98
  - `module:disabled` [{ name: string; message: string }] A picture or ui module errored and was disabled (the game continues)
98
99
  - `module:restored` [{ modules: any[] }]
99
- - `state:replaced` [{ undone: boolean }]
100
+ - `op:rolledBack` [{ op: string; parts: number }] An atomic op failed and its parts were put back (its own events already went out and stay): read derived state again. Not sent for a load's rollback (that ends in state:replaced)
100
101
  - `vehicle:enter` [{ character: Character; vehicle: Rideable }] A character boarded a vehicle
101
102
  - `vehicle:exit` [{ character: Character; vehicle: Rideable }] A character exited a vehicle
102
103
  - `flow:change` [{ from: string; to: string }] Game flow state changed
@@ -1,8 +1,9 @@
1
- # engine.ground (Ground) — Ground: whoever provides the ground height is the "terrain" (terrain module, level module, or the default flat y=0)
1
+ # engine.ground (GroundProvider) — Ground provider: whoever provides the ground height is the "terrain" (terrain module, level module, or the default flat y=0)
2
2
 
3
- - `ground.height(x: number, z: number, refY?: number) → number` — Ground height (meters) at (x, z). For multi-layer ground (bridges, caves) pass refY: takes the highest layer not above refY + one step (0.45 m); without it the highest layer is used. Single-layer ground ignores refY
4
- - `ground.slope(x: number, z: number, refY?: number) → number` — Slope at (x, z) (height difference / horizontal distance)
5
- - `ground.type(x: number, z: number, refY?: number) → string` — Ground type at (x, z) (landform name, e.g. 'meadow')
3
+ - `ground.height(x: number, z: number, refY?: number) → number` — Ground height (meters) at (x, z). For multi-layer ground (bridges, caves) pass refY: takes the highest layer not above refY + one step (0.45 m); without it the highest layer is used. Single-layer ground ignores refY. A game reads it with engine.surface(x, z)
4
+ - `ground.slope(x: number, z: number, refY?: number) → number` — Slope at (x, z) (height difference / horizontal distance). A game reads it with engine.slope
5
+ - `ground.type(x: number, z: number, refY?: number) → string` — Ground type at (x, z) (landform name, e.g. 'meadow'). A game reads it with engine.groundType
6
+ - `ground.water(x: number, z: number, refY?: number) → number` — Optional: water surface height at (x, z) when it differs per point (-Infinity = none); replaces waterLevel there. A game reads engine.waterAt
6
7
  - `ground.has(x: number, z: number) → boolean` — Is there ground at (x, z). Always true except off the outline of terrain({ shape }), where height is -Infinity and slope 0. Example: `if (engine.ground.has(x, z)) engine.snapToGround(chest);`
7
8
  - `ground.voidY() → number` — Height below which something has fallen out of the world (terrain:void): engine.terrain.voidY with terrain({ shape }), else -Infinity
8
9
  - `ground.forEachCollider(x: number, z: number, range: number, fn: (cx, cz, r) => void)` — Optional: iterate the circular colliders (tree trunks etc.) within range meters of (x, z)
@@ -11,5 +12,5 @@
11
12
  - `ground.staticTrimeshes() → { positions, indices }[]` — (experimental) Optional: static triangle mesh (the level module provides it for physics)
12
13
  - `ground.staticVersion() → number` — (experimental) Optional: version number of the static mesh; rebuild when it changes
13
14
  - Properties:
14
- - `waterLevel: number` Global water level (meters); -Infinity when there is no water
15
+ - `waterLevel: number` Global water level (meters); -Infinity when there is no water. A game reads engine.waterLevel
15
16
  - `chunkSize?: number` Optional: chunk edge length (meters)
package/docs/api/hud.md CHANGED
@@ -7,11 +7,13 @@ Objective markers, counters, progress bars (hud() module)
7
7
 
8
8
  ## Methods and properties
9
9
  - `hud.marker(target: HudTarget, opts?: HudMarkerOptions) → HudMarker` — Add an objective marker: target is an object, position or place name
10
- - `hud.counter(id: string, opts: { label?, icon?, value?, max?, anchor? })` — Counter or text status (calling again with the same id = update; calling every frame is fine): counter('fish', { label: '鱼', value: 2, max: 5 }), counter('clock', { value: '08:30' }); no value = the label alone, no label = the value alone (the id is not shown)
10
+ - `hud.addCounter(id: string, opts: { label?, icon?, value?, max?, anchor? }) → { id, set, remove }` — Counter or text status, returns { set(value), remove() } (calling again with the same id = update; calling every frame is fine): addCounter('fish', { label: '鱼', value: 2, max: 5 }), addCounter('clock', { value: '08:30' }); no value = the label alone, no label = the value alone (the id is not shown)
11
11
  - `hud.bump(id: string, n?: number) → number` — Add n (default 1) to a number counter, return the new value; one not declared yet starts at 0 with its id as the label
12
12
  - `hud.value(id: string) → number | string | undefined` — Current value of a counter or bar (number or text), undefined when there is none; reads what interactions.add({ counter }) has added up
13
13
  - `hud.bar(id: string, opts: { value, max?, label?, anchor? })` — Progress bar (calling again with the same id = update; calling every frame is fine, the DOM is untouched when the value is unchanged), value/max 0–max
14
- - `hud.remove(id: string)` — Delete a counter or progress bar
14
+ - `hud.button(id: string, opts: { label, run, icon?, anchor?, action? })` — Clickable button (calling again with the same id = update): label is text or an i18n key, run() is called on a click / tap. The press never reaches the game and focus goes back to it; a locked mouse has no cursor, so free it first (Esc)
15
+ - `hud.hint(id: string, opts: { action, label?, anchor? })` — (experimental) Key hint "E · Talk" (same id = update): the key text is engine.input.label(action) (the input.noKey text when the action needs a key and has none, as in the prompt), so it follows rebinding and keyboard / pad switching; label is text or an i18n key. A button with `action` shows its key too
16
+ - `hud.remove(id: string)` — Delete a counter, progress bar, button or key hint
15
17
  - Properties:
16
18
  - `markers: HudMarker[]` All markers
17
19
 
package/docs/api/input.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # engine.input (Input) — Input: read by "action", not by "key"
2
2
 
3
- - `input.action(name: string, o?: { context?, label?, optional?, keys?, owner? }) → { name: string; remove(): void }` — Declare an action: its context and display name, never its keys (the game binds those). Modules call ctx.input.action (owned by the module, removed with it); a game's own action can pass keys to declare and bind in one line. context: the input context it is read in (default 'walk'); readable only while that context is on the stack and not shadowed, see push(). optional: true = the module works without it (number keys for dialogue choices), so reading it unbound is silent. A second owner declaring the same action with another context throws input-action-context. Example: `ctx.input.action('choice1', { context: 'dialog', label: 'dialogue.choice', optional: true }); // in a module: no keys`
3
+ - `input.define(name: string, o?: { context?, label?, optional?, keys?, owner? }) → { name: string; remove(): void }` — Declare an action: its context and display name, never its keys (the game binds those). Modules call ctx.input.define (owned by the module, removed with it); a game's own action can pass keys to declare and bind in one line. context: the input context it is read in (default 'walk'); readable only while that context is on the stack and not shadowed, see push(). optional: true = the module works without it (number keys for dialogue choices), so reading it unbound is silent. A second owner declaring the same action with another context throws input-action-context. Example: `ctx.input.define('choice1', { context: 'dialog', label: 'dialogue.choice', optional: true }); // in a module: no keys`
4
4
  - `input.bind(name: string | Readonly<Record<string,…, keys?: string | readonly string[], { owner }?: { owner?: string }) → { owner: string; remove(): void }` — Bind keys to an action (the game's choice; owner 'game'). Takes one action or a whole map, e.g. a preset: bind(presets.bindings.rtsRotate). Binding again as the same owner replaces; a DIFFERENT owner binding the same action throws input-bound-twice in dev (release: the later wins). An action nobody declared yet is created in context 'walk' (a module declaring it later sets its context; order does not matter). Example: `engine.input.bind('jump', ['Space', 'PadA']);`
5
5
  - `input.touchButton(action: string, labelKey: string) → { remove(): void }` — Touch button (appears only on touch devices); pressing it triggers the action. labelKey is the string-table key of the button text (updates when the language changes). Returns { remove() }: a module tracks it, so the button leaves with the module
6
6
  - `input.simulate(action: string, down?: boolean)` — Press (down true) or release an action from code, through the same path as a real key: tests, AI drivers, replays. Presses the action's first bound key and holds it until simulate(action, false), so the player walks like with a held key. Takes action names (moveForward, moveLeft, run, interact, ...; engine.input.actions lists them), not keys; an unknown name throws unknown-name with the closest one. Example: `engine.input.simulate('moveForward'); engine.step(1); engine.input.simulate('moveForward', false)`
7
- - `input.seat(opts?: { pad?, keys? }) → Seat` — A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to createPlayer({ id, input }). pad: gamepad index; that pad leaves engine.input and answers the game's pad bindings here. keys: { action: keys } for this seat alone. Two seats on one pad or key throw `input-seat`. Example: `const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });`
7
+ - `input.seat(opts?: { pad?, keys? }) → Seat` — A local player's share of the input on a shared screen: its own keys and gamepad, read like engine.input (axis, down, pressed, released). Pass it to addPlayer({ id, input }). pad: gamepad index; that pad leaves engine.input and answers the game's pad bindings here. keys: { action: keys } for this seat alone. Two seats on one pad or key throw `input-seat`. Example: `const two = engine.input.seat({ pad: 1, keys: { moveForward: 'KeyI', moveBack: 'KeyK', moveLeft: 'KeyJ', moveRight: 'KeyL', jump: 'KeyU' } });`
8
8
  - `input.rebind(action: string, keys: string | string[] | null)` — The player's rebinding (the settings menu calls this and saves it): replaces the game's keys on the settings layer of 'input.keys'. keys null takes the player's choice away (the game's or the default keys show again). Works before the action is declared (a saved binding is restored at start, the module declaring the action comes later). Example: `engine.input.rebind('jump', ['KeyJ']); engine.input.rebind('jump', null); // back to the game's keys`
9
9
  - `input.rebound() → Record<string, string[]>` — The player's rebindings now in effect: { action: keys } (what the settings menu saves)
10
- - `input.keysOf(action: string) → readonly string[]` — (experimental) All keys bound to an action: the player's rebinding, else the game's bind, else the default preset (basics only); plus its touch button
10
+ - `input.keysOf(action: string) → readonly string[]` — All keys bound to an action: the player's rebinding, else the game's bind, else the default preset (basics only); plus its touch button
11
11
  - `input.isUnbound(action: string) → boolean` — True when an action needs a key and has none, so no player input can fire it. Not for an optional action, and not for one bound to [] on purpose (a mouse-only game): "no key at all" is the fault, whichever key the game or the player chose is not. Example: `if (engine.input.isUnbound('interact')) engine.input.bind(presets.bindings.interact);`
12
12
  - `input.label(action: string) → string` — Key name shown in the UI, e.g. "E"
13
13
  - `input.down(action: string) → boolean` — Held (a snapshot of this step in fixed, the latest state in frame)
14
14
  - `input.pressed(action: string) → boolean` — Just pressed. Read in onFixed / module fixed: pressed since the previous fixed step, true only for this step (counted once however the frame rate varies, never lost); read in onFrame / module frame: pressed this frame (UI keys only). Read gameplay keys in fixed. Example: `engine.onFixed(() => { if (engine.input.pressed('jump')) player.jump(); });`
15
- - `input.released(action: string) → boolean` — (experimental) Just released (which copy is read is the same as pressed; for things like release-to-fire after charging). Example: `if (engine.input.released('fire')) shoot(charge);`
15
+ - `input.released(action: string) → boolean` — Just released (which copy is read is the same as pressed; for things like release-to-fire after charging). Example: `if (engine.input.released('fire')) shoot(charge);`
16
16
  - `input.pressedRaw(action: string) → boolean` — Just pressed, ignoring input contexts (for menus and dialogue themselves, which run while a context blocks the game)
17
- - `input.push(name: string, opts?: { pass?: boolean; owner?: string }) → { name: string; remove(): void }` — Push an input context (an action group, like a Unity Action Map). The top context shadows lower actions bound to the same key. Opaque by default (nothing below is readable: menus, dialogue, cutscenes); { pass: true } lets unrelated lower actions keep working (vehicle, build mode). Applies at the start of the next fixed step; actions it blocks lose their held state (no stuck keys after a menu closes). Join a context with input.action(name, { context }); menu keys: pressedRaw. Example: `const h = engine.input.push('vehicle', { pass: true }); // vehicle-context actions (brake) work, and shadow gameplay actions on the same key h.remove();`
17
+ - `input.push(name: string, opts?: { pass?: boolean; owner?: string }) → { name: string; remove(): void }` — Push an input context (an action group, like a Unity Action Map). The top context shadows lower actions bound to the same key. Opaque by default (nothing below is readable: menus, dialogue, cutscenes); { pass: true } lets unrelated lower actions keep working (vehicle, build mode). Applies at the start of the next fixed step; actions it blocks lose their held state (no stuck keys after a menu closes). Join a context with input.define(name, { context }); menu keys: pressedRaw. Example: `const h = engine.input.push('vehicle', { pass: true }); // vehicle-context actions (brake) work, and shadow gameplay actions on the same key h.remove();`
18
18
  - `input.describe() → { stack, unbound, rebound }` — describe().input: the context stack, declared actions nobody bound (unbound: isUnbound) and the player's rebindings
19
19
  - `input.gate(action: string, owner?: string | { owner?, for?, clock? }) → { owner: string; remove(): void }` — Close one action while anyone holds its gate (stun: no jump; a tutorial: no attack yet), without a whole input context. Same rules as every engine.mod stack (it is the shared point 'input.gate', one entry per owner and action): only the owner opens it, { for } ends it by itself. A closed action reads as not down / pressed / released; describe().holds.gates lists the owners. Example: `const stun = engine.input.gate('jump', { owner: 'stun', for: 1.5 }); // no jumping for 1.5 s; stun.remove() reopens it early`
20
20
  - Properties:
@@ -9,7 +9,7 @@ Particles (particles() module)
9
9
  ## Methods and properties
10
10
  - `particles.define(name: string, opts?: ParticleOptions) → ParticleEffect` — Define an effect (same name replaces it, and emitters attached to it move to the new definition); params sit on top of particles({ effects, default }). Returns the effect object: .points is its THREE.Points (a Sprite on WebGPURenderer); .material is its plain three.js material (set your own and it is drawn as given, null gives the engine's back); .uniforms are the engine material's { value } objects (uMap, uHasMap, uScale, uMaxPx), which a ShaderMaterial of yours can share. A material of yours lasts until the effect is defined again. Example: `engine.particles.define('sparks', { blending: 'additive' }).material = myMaterial;`
11
11
  - `particles.has(name: string) → boolean` — Whether this effect has been defined
12
- - `particles.emit(name: string, position: PositionLike, opts?: { count?, overrides? })` — Burst: emit count particles at once (default 10) at position (Vector3 / Object3D / [x, y, z] / {x, y, z}). overrides affect this batch only (color, speed, direction...; max/texture/blending/soft cannot be changed temporarily)
12
+ - `particles.emit(name: string, position: PositionLike, opts?: { count?, overrides? })` — Burst: emit count particles at once (default 10) at position (Vector3 / Object3D / [x, y, z] / {x, y, z}). overrides affect this batch only (color, speed, direction...; max/texture/blending/soft/lit cannot be changed temporarily)
13
13
  - `particles.attach(name: string, object3d: THREE.Object3D, opts?: { rate?, ratePerMeter?, offset?, overrides? }) → ParticleEmitter` — Keep emitting while following an object: rate per second, ratePerMeter per meter it moves (spread along the path, on top of rate), offset in the object's local coordinates [x, y, z] (meters). Returns a handle { remove(), rate, ratePerMeter, active } (active = false pauses)
14
14
  - `particles.count(name?: string) → number` — Live particle count (no name = all)
15
15
  - `particles.clear(name?: string)` — Clear one effect's (or all) particles
@@ -40,6 +40,7 @@ Particles (particles() module)
40
40
  - `maxPixels?: number` Largest on-screen size of one particle in pixels (smoke drifting past the camera stays bounded), default 512
41
41
  - `ratePerMeter?: number` (experimental) Default particles per meter the emitter moves for attach, on top of rate, spread along the path it moved; default 0
42
42
  - `soft?: number` (experimental) Meters over which a particle fades where it meets what writes depth; default 0, off. Set at define, not in overrides. On WebGLRenderer it costs one depth-only draw of the scene per render while such an effect is on screen
43
+ - `lit?: boolean` (experimental) The scene's lights tint each particle's color (dust a lamp lights): point, spot, directional, ambient, hemisphere, as a matte card facing each light. No shadows, environment map or probes. Default false (the color is drawn as given). Set at define, not in overrides; costs live particles x lights per frame on the CPU, the same on both renderers
43
44
  - **ParticleEmitter** (extends Handle) Continuous emitter returned by attach() (a handle)
44
45
  - `rate: number` Particles per second (can be changed at any time)
45
46
  - `ratePerMeter: number` (experimental) Particles per meter the object moves, on top of rate (can be changed at any time)
package/docs/api/photo.md CHANGED
@@ -4,12 +4,15 @@ Photo mode (photo() module)
4
4
 
5
5
  - Options `PhotoOptions` (also includes the fields of PhotoTakeOptions):
6
6
  - `maxAlbum?: number` (experimental) How many photos the album keeps at most, default 50
7
+ - `pathTracer?: (() => Promise<any>) | null` (experimental) The game's import of its optional path tracer, called on the first photo.trace(): () => import('three-gpu-pathtracer/webgpu')
7
8
 
8
9
  ## Methods and properties
9
10
  - `photo.take(opts?: PhotoTakeOptions) → PhotoShot` — Capture a photo now without checks. Gameplay takes photos through the op: engine.ops.run('photo.take') (checks canTake, logged)
11
+ - `photo.trace(opts?: PhotoTakeOptions & { samples?, seconds? }) → Promise<PhotoShot>` — (experimental) A path-traced photo (WebGPU backend or a WebGLRenderer; the game's photo({ pathTracer })): samples (whole, >= 1, default 128) accumulate on a snapshot while the game runs, until seconds (>= 1, default 60); resolves to the shot, rejects naming why. scale defaults to 1 here. The op photo.trace starts it (r.value is this Promise)
10
12
  - `photo.subject() → { name, kind, distance } | null` — (experimental) What is in the middle of the frame (NPC, entity, named object, vegetation), null if nothing; this is the subject of take()
11
13
  - Properties:
12
14
  - `album: PhotoShot[]` Album (newest first)
13
15
  - `canTake: () => boolean | string` The op photo.take's can: return true, or false / a reason string to refuse (e.g. () => engine.inventory.has('film') // 'noFilm')
14
16
  - `format: string` (experimental)
15
17
  - `maxAlbum: number` (experimental)
18
+ - `tracing: { samples: number; of: number } | null` (experimental) While a path-traced photo accumulates: samples per pixel so far and the target; null otherwise
package/docs/api/post.md CHANGED
@@ -2,10 +2,11 @@
2
2
 
3
3
  - `post.object() → any` — (experimental) What the chain runs in, for reading, or null while no post work has run yet (built the first time an effect is on; it is not built here, so asking never costs a render target). WebGLRenderer: the three.js EffectComposer (pass list, sizes, its targets). WebGPURenderer: { pipeline, scenePass }, three's RenderPipeline and the scene's pass() node. Read-only by rule, not by lock: the engine owns it, rebuilds the chain whenever the list changes and disposes it with the engine. To add a pass use post.add, to own the whole chain post.own() (recipe 52). Why public: a game reading the chain had to dig into an internal field (review 2026-11-03)
4
4
  - `post.targets() → { renderTarget1, renderTarget2, readBuffer, writeBuffer } | null | …` — (experimental) The composer's render targets, for reading (sample the last frame's color or depth in a game pass, check formats / samples), or null while there is no composer, and always on WebGPURenderer (its pass nodes own their targets: post.object().scenePass). renderTarget1 / renderTarget2 are the ping-pong pair. During the chain readBuffer is a pass's input and writeBuffer its output; EffectComposer swaps them after every pass with needsSwap (most passes; the scene RenderPass does not). The last pass draws to the canvas and still swaps, so after the frame (engine.onRender(fn, { when: 'after' })) neither target holds the final picture: writeBuffer holds the input of that last pass (readBuffer when the last pass does not swap) and readBuffer is stale. For the final image, render into a target of your own.
5
- - `post.add(x: any, o?: { name?, slot?, order? }) → PostHandle` — The one way to add a post effect. x is a three.js Pass (WebGL), a TSL node function (input, ctx) => node (WebGPU), or an effect { name, create / node / fuse, slot, order, params, needsDepth, needsBuffers, backend, skipOnLowTier, facts } (both renderers when it gives create and node, or a fuse). A wrong shape throws with nothing added. needsDepth, needsBuffers ('normal' / 'diffuse' / 'velocity', WebGPU), backend ('webgpu': not on the WebGL2 backend), skipOnLowTier (held when engine.tier is 'low') and facts (shown by describe().render.post) are explained on PostEffect. A Pass that draws engine.scene takes the 'scene' slot, FXAA / SMAA / TAA 'final', any other 'hdr' after the effects already there, or 'ldr' once an OutputPass was added. A RenderPass of engine.scene and an OutputPass are the engine's own stages: skipped and said once (an OutputPass still marks where display color starts). Example: `const glow = engine.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); glow.enabled = false;`
6
- - `post.get(name: string) → PostHandle | undefined` — (experimental) An added effect's handle (as add() returns it), or undefined. Example: `engine.post.get('bloom').set({ strength: 0.6 });`
5
+ - `post.add(x: any, o?: { name?, slot?, order? }) → PostHandle` — The one way to add a post effect. x is a three.js Pass (WebGL), a TSL node function (input, ctx) => node (WebGPU), or an effect { name, create / node / fuse, slot, order, params, needsDepth, needsBuffers, backend, skipOnLowTier, cheaper, facts } (both renderers when it gives create and node, or a fuse). A wrong shape throws with nothing added. needsDepth, needsBuffers ('normal' / 'diffuse' / 'velocity' / 'metalRough', WebGPU), backend ('webgpu': not on the WebGL2 backend), skipOnLowTier (held when engine.tier is 'low') and facts (shown by describe().render.post) are explained on PostEffect. A Pass that draws engine.scene takes the 'scene' slot, FXAA / SMAA / TAA 'final', any other 'hdr' after the effects already there, or 'ldr' once an OutputPass was added. Example: `const glow = engine.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); glow.enabled = false;`
6
+ - `post.get(name: string) → PostHandle | undefined` — An added effect's handle (as add() returns it), or undefined. Example: `engine.post.get('bloom').set({ strength: 0.6 });`
7
+ - `post.byRole(role: string, name?: string) → PostHandle[]` — (experimental) The added effects that declare this role in about.acts ('glow', 'ao', 'exposure'): found by what they do, never by name; the settings rows and photo follow every one of them. Only when NO effect declares the role does the effect named `name` stand in (a game's own 'bloom' written before roles existed); with no `name` that case gives [].
7
8
  - `post.own(on?: boolean)` — (experimental) Hand the built chain to the game: the engine stops rebuilding it, so the composer's passes (post.object().passes) or the WebGPU pipeline's outputNode are the game's to edit. own(false) gives it back and rebuilds from the list. describe().owned shows who has it. Example: `engine.post.own(); engine.post.object().passes.reverse();`
8
- - `post.list() → { name, slot, order, enabled }[]` — (experimental) Effects in render order: [{ name, slot, order, enabled }]
9
+ - `post.list() → { name, slot, order, enabled }[]` — Effects in render order: [{ name, slot, order, enabled }]
9
10
  - `post.render(dt: number, target?: any)` — Draw the frame through the chain. target: a render target to draw the finished picture into instead of the canvas (engine.renderOnce(target)); it gets the canvas's pixels (tone mapped, output color space). Why a target argument and not "set the render target first": the WebGL chain's last pass always writes to the canvas (EffectComposer renderToScreen); the WebGPU pipeline draws into whatever target is set.
10
11
  - Properties:
11
12
  - `antialias: boolean` (experimental) MSAA on or off in the post chain's render targets, for what runs through the chain. It is a render setting, not a drawing part. With no effect on nothing runs through the chain: the canvas's own MSAA shows, fixed when the context was made (createEngine({ antialias })). Example: `engine.post.antialias = false;`
@@ -21,9 +22,11 @@
21
22
  - `order?: number`
22
23
  - `enabled?: boolean`
23
24
  - `needsDepth?: boolean`
24
- - `needsBuffers?: ("normal" | "diffuse" | "velocity")[]`
25
+ - `needsBuffers?: ("normal" | "diffuse" | "velocity" | "metalRough")[]`
25
26
  - `backend?: "webgpu"`
26
27
  - `skipOnLowTier?: boolean`
28
+ - `cheaper?: Record<string, any>`
27
29
  - `facts?: () => Record<string, any> | null`
30
+ - `about?: Record<string, any>`
28
31
  - `params?: Record<string, any>`
29
32
  - `update?: (impl: any, params: Record<string, any>) => void`
@@ -12,9 +12,9 @@ Quests (quests() module)
12
12
  - `quests.start(id: string)` — Start a quest
13
13
  - `quests.state(id: string) → { step, steps, done, failed, active, visited } | null` — One quest's progress (a copy): step index, step count, done, failed, active; null before it starts
14
14
  - `quests.advance(id: string) → boolean` — Finish the current step from code (its done() is not asked) and go on; the last step completes the quest. false when not active
15
- - `quests.isDone(id: string) → boolean` — (experimental)
15
+ - `quests.isDone(id: string) → boolean` — Finished (done, not failed)
16
16
  - `quests.isActive(id: string) → boolean` — Started, not done and not failed
17
- - `quests.isFailed(id: string) → boolean` — (experimental) Its fail condition held (start(id) begins it again)
17
+ - `quests.isFailed(id: string) → boolean` — Its fail condition held (start(id) begins it again)
18
18
  - `quests.check()` — Check completion conditions once immediately
19
19
  - `quests.list() → { id, title, desc?, done, failed, steps }[]` — Quest list (for custom UI)
20
20
  - Properties:
package/docs/api/rays.md CHANGED
@@ -1,7 +1,6 @@
1
1
  # engine.rays (Rays) — engine.rays is the ray registry (engine.raycast hits whatever is registered here)
2
2
 
3
- - `rays.addStatic(obj: THREE.Object3D | THREE.Object3D[], opts?: { occluder?: boolean }) → Handle` — Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Only visible objects are hit. Something that is merely not drawn is still hit: batched originals, far hlod originals and the full model of a far assets.lod sit on a reserved layer, with their visible true. Unregisters automatically on geometry dispose or engine.remove. Example: `engine.rays.addStatic(house, { occluder: true });`
4
- - `rays.forget(obj: THREE.Object3D)` — (experimental) Unregister every mesh under the object (engine.remove calls this automatically)
3
+ - `rays.addStatic(obj: THREE.Object3D | THREE.Object3D[], opts?: { occluder?: boolean }) → Handle` — Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Matrices are read once per tick and frame: a registered mesh moved between two rays of one step needs updateMatrixWorld() first. Only visible objects are hit. Something that is merely not drawn is still hit: batched originals, far hlod originals and the full model of a far assets.lod sit on a reserved layer, with their visible true. Unregisters automatically on geometry dispose or engine.remove. Example: `engine.rays.addStatic(house, { occluder: true });`
5
4
  - `rays.addProvider(fn: RayProvider) → Handle` — (experimental) A module merges its own hits (rigid adds rigid bodies; asked only when targets is 'all'). Returns a handle { remove() }
6
5
  - Properties:
7
6
  - `statics: Map<THREE.Object3D, { refs: number; occ: number }>` (experimental) Registered mesh -> { refs: registration count, occ: camera-blocker registration count }
package/docs/api/saves.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # engine.saves (Saves) — engine.saves handles saving
2
2
 
3
- - `saves.register(key: string, provider: SaveProvider) → { remove }` — Register "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); a load returning a Promise makes later parts wait. version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current shape. A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept). load(data, turn): turn is this replacement's identity. Pass it on, level.load(x, { turn }) or content.load(x, { turn }): those wait for a running load to end, except with its turn. A part registered after a save was loaded (a module installed later) is handed its data from that save: at once when idle, else right after the replacement under way. Example: `engine.saves.register('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) }); // later the format gains beds: version 2, and a step that upgrades version-1 data engine.saves.register('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });`
4
- - `saves.putAttachment(group: string, id: string, blob: Blob | (() => Promise<Blob>), meta?: any) → Promise<void>` — (experimental) Store a binary attachment outside the world save (a photo, a replay). It rides in the queue of save writes, so flush() waits for it, and exportFile() carries it. Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept. Rejects with save-stale, changing nothing, when another tab wrote this id since this tab last saw it; attachments(group) is how a tab looks. Example: `await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });`
3
+ - `saves.define(key: string, provider: SaveProvider) → { remove }` — Define "how to save and load"; key is this part's name in the save. Parts with first: true load first (the level); first may be a number, lower loads earlier, true counts as 0 (zones that need the level: 1); a load returning a Promise makes later parts wait. version (default 1): raise it by 1 whenever what save() returns changes shape, and add migrate[oldVersion] = data => newData; load sees only the current shape. A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept). load(data, turn): turn is this replacement's identity. Pass it on, level.load(x, { turn }) or content.load(x, { turn }): those wait for a running load to end, except with its turn. A part registered after a save was loaded (a module installed later) is handed its data from that save: at once when idle, else right after the replacement under way. Example: `engine.saves.define('garden', { save: () => garden.toJSON(), load: d => garden.fromJSON(d) }); // later the format gains beds: version 2, and a step that upgrades version-1 data engine.saves.define('garden', { version: 2, migrate: { 1: d => ({ ...d, beds: [] }) }, save: () => garden.toJSON(), load: d => garden.fromJSON(d) });`
4
+ - `saves.putAttachment(group: string, id: string, blob: Blob | (() => Promise<Blob>), meta?: any) → Promise<void>` — (experimental) Store a binary attachment outside the world save (a photo, a replay). It rides in the queue of save writes, so flush() waits for it, and exportFile() carries it. Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept: it rejects with save-write. Rejects with save-stale, changing nothing, when another tab wrote this id since this tab last saw it; attachments(group) is how a tab looks. Example: `await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });`
5
5
  - `saves.removeAttachment(group: string, id: string) → Promise<void>` — (experimental) Delete an attachment; no such id is fine. Rejects with save-stale as putAttachment does
6
6
  - `saves.attachments(group: string) → Promise<{ group: string; id: stri…` — (experimental) The attachments of a group, once storage is ready. Empty without IndexedDB.
7
7
  - `saves.storageKey(name: string) → string` — A localStorage key for what belongs to this game but is not a save (settings, a last-used tab): it shares the game's name, so two games on one site stay apart, and stays out of list(). Example: `localStorage.setItem(engine.saves.storageKey('lastTab'), 'map');`
@@ -10,7 +10,7 @@
10
10
  - `saves.check(slot?: string) → null | "missing" | "corrupt" | "tooNew" | "migrate"` — Can this slot be loaded? null when it can, else why not (checked without touching the game): 'missing' / 'corrupt' (unreadable) / 'tooNew' (a newer save format or part) / 'migrate' (an upgrade step is missing or throws). Example: `if (engine.saves.check('slot1') === 'tooNew') showUpdateHint();`
11
11
  - `saves.apply(data: any, slot?: string) → Promise<boolean>` — Apply a save's data (an object from collect(), or save text) onto the running game. Resolves true when every part loaded. Refused before anything changes (false, toast) when the data is corrupt, from a newer build or cannot be migrated. After every part loaded it runs the modules' afterLoad hooks (gameplay frozen until they resolve), for saves.load, session.newGame / quit and direct calls alike. If a part's load throws, a listener of an event it emits while loading (world:load) throws, or a module's afterLoad throws, the game is rolled back to how it was before (every part reloads its pre-load state) and it resolves false; the error goes through the error tiers. "While loading" lasts until the result settles, past every await of an async load(); a listener that throws in that window for any reason fails this load.
12
12
  - `saves.save(slot?: string) → Promise<boolean>` — Save into a slot (default 'auto'). Returns Promise<boolean> (resolves after the write to IndexedDB: true on success, false with a toast and console error on failure). The in-memory save updates immediately, so a following load / list / export sees it at once; the 'save:written' event fires only after the write succeeds. Asked for while a load, newGame or quit is under way, it waits for that to end and saves the result: a save never holds half of each state. If any part's save() throws, or its data holds NaN or Infinity at any depth (the message names the part and the path), nothing is written and the slot keeps its previous save (false). A failed write keeps the previous save too. Show "saved" only after the result is true. Example: `if (await engine.saves.save('slot1')) toast(engine, 'Saved'); // on false the engine already showed why`
13
- - `saves.load(slot?: string) → Promise<boolean>` — Load a slot onto the running playthrough (a quick load: what the game added during play stays) and resolve true on success; the 'save:loaded' event fires on success. A missing slot resolves false; a corrupt / too new / unmigratable save resolves false with a toast and changes nothing; a part whose load throws rolls the game back. To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot). Example: `if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');`
13
+ - `saves.load(slot?: string, { turn }?: { turn?: object }) → Promise<boolean>` — Load a slot onto the running playthrough (a quick load: what the game added during play stays) and resolve true on success; the 'save:loaded' event fires on success. A missing slot resolves false; a corrupt / too new / unmigratable save resolves false with a toast and changes nothing; a part whose load throws rolls the game back. To continue or retry with nothing of the current playthrough left over, use engine.session.load(slot). Example: `if (!(await engine.saves.load('quick'))) toast(engine, 'No quick save');`
14
14
  - `saves.list() → { slot: string; savedAt: number }[]` — All slots, newest first (synchronous, reads the in-memory index)
15
15
  - `saves.remove(slot: string) → Promise<void>` — Delete a slot. Returns a Promise (disk write done); awaiting is optional. A newer save another tab wrote meanwhile is kept: the slot lists again, with a toast (save-stale). A delete the store refused lists the slot again too, with a toast.
16
16
  - `saves.export(slot?: string) → string` — (experimental) Export as a piece of text (can be copied as a backup; synchronous, without binary attachments)
@@ -25,12 +25,12 @@
25
25
  - `versions: Record<string, number>` The save versions this build reads, per part: { world: 1, clock: 1, ... }. A save whose part is newer is refused; an older one is migrated.
26
26
 
27
27
  ## Data structures
28
- - **SaveProvider** Save provider: save() returns JSON-able data, load(data) reads it back (may return a Promise, e.g. for changing level; later parts wait for it to finish before loading). first: true providers load first (parts such as the level, where the rest only makes sense after it is loaded)
28
+ - **SaveProvider** Save provider: save() returns JSON-able data, load(data) reads it back (may return a Promise, e.g. for changing level; later parts wait for it to finish before loading). first: true providers load first (parts such as the level, where the rest only makes sense after it is loaded); first may be a number, lower loads earlier, true counts as 0
29
29
  - `save: () => any` This part's data now: plain data (structuredClone can copy it; no functions, DOM nodes or three objects). It may be the live object the part keeps: the engine copies it for its rollback point before a load, so a load() that writes into that same object can still be undone.
30
30
  - `load: (data: any, turn: SaveTurn) => void | Promise<void>` Read data back; may return a Promise (later parts wait). Listener errors of events it emits count as the load throwing, also after an await. turn: this replacement's identity. Pass it on as level.load(x, { turn }) / content.load(x, { turn }): awaited without it, those wait for this load, so for ever (dev warns after 3 s, save-nested)
31
- - `first?: boolean` Load before the other parts (such as the level)
32
- - `atomic?: boolean` Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback)
33
- - `notAtomic?: string` Why an atomic op leaves this part alone. Every engine part gives atomic: true or this (rule R66); a game's part may
31
+ - `first?: boolean | number` Load before the other parts (such as the level)
32
+ - `atomic?: boolean` Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback; load() must be synchronous: an async function is refused at define, a returned Promise at rollback as engine-misuse)
33
+ - `notAtomic?: string` Why an atomic op leaves this part alone. Every engine part gives atomic: true or this (rule R67); a game's part may
34
34
  - `checkNewGame?: (data: any) => void` Dev only: called once start() finished with this part's data in the new-game state, to warn about what should not be there yet (world: records placed by code)
35
35
  - `version?: number` This part's format version, default 1: raise it by 1 when what save() returns changes shape. A save with a newer version is refused
36
36
  - `migrate?: Record<number, (data: any, save: { parts: Record<string, an…` Upgrade steps: old version -> data => data in the next version's shape, e.g. { 1: d => ({ ...d, beds: [] }) }. The second argument is the whole save as read ({ parts, versions }, read only), for a step that depends on another part
@@ -13,7 +13,7 @@ Settings menu (settings() module)
13
13
  - `settings.get(key: string) → any` — Read a setting, e.g. get('vol.music')
14
14
  - `settings.set(key: string, value: any, opts?: { save?: boolean })` — Change a setting (takes effect immediately + saved)
15
15
  - `settings.preset(name: 'low' | 'medium' | 'high' | (string & {}))` — (experimental) Graphics preset: 'low' / 'medium' / 'high'
16
- - `settings.define(key: string, def: T, apply?: ((value, e) => void) | { apply?, limits? })` — Game-defined setting: default value + apply function (saved automatically), or { apply, limits }. limits names the shared value(s) the row restricts on the settings layer, like the built-in shadows row: off holds it off (the scene, weather or a cutscene cannot turn it back on), on allows what the scene chose; a number row from 0 to 1 is a factor on a number value. Define it after the effect exists
16
+ - `settings.define(key: string, def: T, apply?: ((value, e) => void) | { apply?, limits?, menu?, label?, options?, min?, … } | …)` — Game-defined setting: default value + apply function (saved automatically), or { apply, limits }. limits names the shared value(s) the row restricts on the settings layer, like the built-in shadows row: off holds it off (the scene, weather or a cutscene cannot turn it back on), on allows what the scene chose; a number row from 0 to 1 is a factor on a number value. Define it after the effect exists. The menu draws the row itself in the tab menu names (default 'options', shown while it has a row): a switch for true/false, a slider for a number (min/max; a limits row has 0..1), buttons for options. label: an i18n key or text, else the key. menu: false when your own tab draws it; a row the menu cannot draw, a missing tab or a row drawn twice warns once
17
17
  - `settings.addSection(id: string, section?: SettingsSection)` — Add a tab of your own, or a built-in / optional one by name: addSection('camera')
18
18
  - `settings.reset(key?: string)` — Put one setting (or all, with no key) back to its default: the engine's start value, or the default the game gave define(). Keys: resetBindings
19
19
  - `settings.resetBindings()` — (experimental) Restore all keys to defaults
@@ -25,7 +25,7 @@ Settings menu (settings() module)
25
25
  - `values: Record<string, any>` All current setting values, read only (set() changes one). pixelRatio is the renderer's real ratio
26
26
  - `presets: Record<string, QualityPreset>` Graphics presets
27
27
  - `sections: Map<string, any>` (experimental) Tabs
28
- - `isOpen: boolean` (experimental) Whether the menu is open
28
+ - `isOpen: boolean` Whether the menu is open
29
29
 
30
30
  ## Data structures
31
31
  - **SettingsSection** One settings tab
package/docs/api/tools.md CHANGED
@@ -65,7 +65,7 @@
65
65
  - `season(color: Node, kind: Node | 0 | 1) → Node` — (experimental) GLSL vec3 threedogSeason(vec3 color, int kind): kind 0 foliage, 1 ground; tints by uFoliageTint / uGroundTint (mix mode when uFoliageMix / uGroundMix > 0). A vec4 color is read as its rgb.
66
66
  - `objectOrigin() → Node` — (experimental) World position of the drawn object's origin (an InstancedMesh: of each instance), vec3. Works for any Mesh / InstancedMesh sharing the material; BatchedMesh throws [tsl-misuse].
67
67
  - `instanceOffset(offset: Node) → Node` — (experimental) An object-space offset carried through the drawn instance's rotation and scale (a plain Mesh: the offset as it is). A positionNode runs after the instance transform, so an offset meant for before it, like wind()'s, goes through this. BatchedMesh throws [tsl-misuse].
68
- - `hash(p: Node) → Node` — (experimental) GLSL float threedogHash(vec2 p): a repeatable random number 0-1 from a 2D position.
68
+ - `hash(p: Node) → Node` — (experimental) GLSL float threedogHash(vec2 p): a repeatable random number 0-1 from a 2D position (an integer hash of its bits: the same on WebGL and WebGPU).
69
69
  - `noise(p: Node) → Node` — (experimental) GLSL float threedogNoise(vec2 p): smooth value noise 0-1, the one behind the engine's clouds and cloud shadows. No uniforms.
70
70
  - `uniforms(engine: { uniforms: object }) → Record<string, Node>` — (experimental) engine.uniforms as TSL uniform nodes (uTime, uWind, uWeatherCloud, uFoliageTint, uSunDir, uDaylight ...), cached per engine. They read the same { value } objects, so engine.uniforms.uWind.value = 2 changes GLSL and TSL materials alike.
71
71
  - `detailNoise(p: Node, kind: Node | 0 | 1 | 2 | 3, octaves: Node | number) → Node` — (experimental) GLSL vec4 threedogDetailNoise(vec2 p, int kind, float octaves): kind 0 grain, 1 paper, 2 stroke, 3 dabs; returns (gray rgb, height 0-1). No uniforms: p is any 2D pattern position you choose (world xz times a scale, a uv...). octaves: up to 4 (dabs: 3).
@@ -74,7 +74,9 @@
74
74
  - `shadowTint(ambient: Node, tint: Node, strength: Node | number, soft: Node | number, nl: Node, shadow: Node | number) → Node` — (experimental) GLSL vec3 threedogShadowTint(vec3 ambient, vec3 tint, float strength, float soft, float nl, float shadow): the ambient with the shaded side's hue moved toward tint (brightness kept). shadow: 1 lit / 0 shadowed (the sun's lightNode.shadowNode); soft: terminator width in n.l.
75
75
  - `rim(normal: Node, viewDir: Node, color: Node, strength: Node | number, power: Node | number, shadowSide: Node | number, nl: Node) → Node` — (experimental) GLSL vec3 threedogRim(vec3 normal, vec3 viewDir, vec3 color, float strength, float power, float shadowSide, float nl): edge light to add (viewDir from the surface to the eye, e.g. normalView and positionViewDirection); shadowSide 1 = only on the side facing away from the sun.
76
76
  - `celLighting() → import('three/webgpu').LightingMo…` — (experimental) The lighting model for cel bands with colored ramps: assign it to a MeshToonNodeMaterial, whose gradientMap holds the ramp (rampTexture). A shadowed pixel reads the dark end of the ramp, so a cast shadow takes the same flat band and color as the side turned away. Without a gradientMap: two levels, as three's toon.
77
+ - `pcss(o?: { lightSize?, samples?, maxDistance? }) → any` — (experimental) A shadow filter for a DirectionalLight whose edge softens with the distance from caster to receiver (PCSS). The game assigns it before the first frame; it reaches the engine's cascades too. lightSize: edge width per world unit of that distance; samples: filter taps; maxDistance: where the edge stops growing. A spot or point light throws by name.
77
78
  - `waterWave(p: Node, t: Node | number) → Node` — (experimental) GLSL float threedogWaterWave(vec3 p, float t): the built-in wave sum (height before waveHeight). p = world position * waveScale, t = time * waveSpeed.
78
79
  - `waterSurface(spec?: { depth?, foam?, waveMax? }) → (base, wave, facing, worldPos, time) => Node` — (experimental) The built-in water surface as TSL: returns a function with the GLSL signature threedogWaterSurface(base, wave, facing, worldPos, time) -> vec4 (rgb, opacity). Only the parts given exist (depth: shallow / deep by viewing angle or wave height; foam on crests); values are numbers / colors or nodes. wave is waterWave's height, facing = 1 looking straight down.
79
80
  - `waterFresnel(color: Node, normal: Node, viewDir: Node, strength: Node | number, towards: Node) → Node` — (experimental) The water's fresnel blend: color mixed toward `towards` (the engine uses the fog color) by pow(1 - /viewDir . normal/, 3) * strength, view space
81
+ - `lightShaft(engine: { renderer, uniforms, tier }, opts?: LightShaftOptions) → LightShaft` — (experimental) A cheap visible light beam (ceiling hole, window, stage light): an additive open cone, top at the mesh origin pointing down -Y, sides softened by view angle, faded where it meets geometry and near the camera, dimmed (not tinted) by scene fog. Occluders do not cut it (for that: sunShafts / lightVolumes). WebGPURenderer only (both backends); WebGLRenderer throws by name. Add / move / remove it like any mesh; engine.remove frees it.
80
82
  - `serve(handler: (msg: any) => any)` — Start answering lane messages in a worker. handler is the same function the lane's local() returns on the main thread.
package/docs/api/vars.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # engine.vars (Vars) — engine.vars: story flags and counters (autosaved)
2
2
 
3
3
  - `vars.flag(key: string) → any` — Read a flag
4
- - `vars.setFlag(key: string, value?: any)` — (experimental) Set a flag (default true)
4
+ - `vars.setFlag(key: string, value?: any)` — Set a flag (default true)
5
5
  - `vars.counter(key: string) → number` — Read a counter (0 if none)
6
6
  - `vars.bump(key: string, n?: number) → number` — Counter +n (default 1), returns the new value
7
7
  - Properties:
@@ -16,10 +16,11 @@ Vegetation (vegetation() module; grows on terrain or on any ground provider)
16
16
  - `vegetation.rebuild()` — Place every chunk again: after changing the ground behind the same provider (a ground function reading game state). A new setGround or level is followed automatically
17
17
  - `vegetation.setShadowRing(name: string, ring: number)` — Change at runtime how far a vegetation kind casts shadows: within `ring` chunk rings of the player (0 = only the chunk you stand in, 1 = the default, larger = further and dearer). Takes effect at once; the define() option shadowRing is only the starting value. An unknown name warns with the known ones. Example: `engine.vegetation.setShadowRing('tree', 0); // graphics setting "shadows: low": trees shadow only the nearest chunk`
18
18
  - `vegetation.define(name: string, opts: VegetationOptions) → Species | Promise<Species>` — Define a kind of vegetation (a model name in model / lodGeometry: resolves first, so the result is a Promise of the species)
19
- - `vegetation.isRemoved(species: string, cx: number, cz: number, id: number) → boolean` — (experimental)
19
+ - `vegetation.isRemoved(species: string, cx: number, cz: number, id: number) → boolean` — Was this instance removed (removeInstance) and not restored
20
20
  - `vegetation.removeInstance(species: string, cx: number, cz: number, id: number, opts?: { regrowSeconds?: number }) → string` — Remove one (chop a tree). regrowSeconds: grows back after this many calendar seconds, 0 = permanent. The record is saved with the save (save key 'vegetation'). Returns the entry name
21
- - `vegetation.restoreInstance(species: string, cx: number, cz: number, id: number)` — (experimental) Restore one
21
+ - `vegetation.restoreInstance(species: string, cx: number, cz: number, id: number)` — Restore one removed instance
22
22
  - `vegetation.instanceAt(position: PositionLike, opts?: { radius?, species? }) → VegetationHit | null` — The one nearest to position within radius meters (default 2) (species restricts to one kind), null if none
23
+ - `vegetation.plantOf(hit: { object?, instanceId? } | null | undefined) → VegetationHit | null` — The plant a ray hit, read from the hit itself (no spatial guess): the same VegetationHit instanceAt returns (goes to removeInstance), null if not vegetation or a far impostor card
23
24
  - Also: `vegetation.get(name: string) → Species | undefined`, `vegetation.list() → Species[]`
24
25
  - Properties:
25
26
  - `material: Material | null` The shared default material: species with no material or model of their own draw it, as given, planted ones too; null gives the neutral default back. Until set, reading gives the neutral source of each species' own copy (only .color written there reaches them all). Throws when a game module drew the plants instead (replaces: 'vegetation-draw').
@@ -38,6 +39,7 @@ Vegetation (vegetation() module; grows on terrain or on any ground provider)
38
39
  - `maxRing?: number` No longer drawn beyond this many rings
39
40
  - `fade?: false | { start?: number; end?: number }` Distance fade of a near-only species (grass, flowers, pebbles, debris ...): instances shrink out over a band in metres from the player instead of popping per chunk at the ring edge. Default for nearOnly: end = maxRing x chunk size, start = 65% of it. `false` keeps the hard ring edge (also the default for species that are not nearOnly).
40
41
  - `lodRing?: number` Switch to the low-detail model beyond this many rings, default 1
42
+ - `impostor?: boolean | { views?: number; size?: number }` Beyond lodRing, draw camera-facing cards baked from this species' own model and materials: one draw for all far chunks, lit through baked normals, no shadow there. views around the plant (default 8), size in pixels per view (default 128). Not with lodGeometry. WebGPU only (WebGL draws the mesh and warns)
41
43
  - `castShadow?: boolean` Cast shadows
42
44
  - `shadowRing?: number` Cast shadows within this many rings
43
45
  - `receiveShadow?: boolean` Receive shadows, default true
package/docs/api/world.md CHANGED
@@ -13,7 +13,7 @@ World data (world() module): things that must be saved, survive level changes an
13
13
  - `world.remove(id: string)` — Remove a record (its model is torn down too) and emit the world:remove event. Does nothing if the id does not exist. Removing an initial record is saved, so it stays gone after loading
14
14
  - `world.query(opts?: { kind?, near?, radius?, where?, zone? }) → WorldRecord[]` — Query records; returns an array. With near only nearby cells are scanned and results are sorted nearest first (radius defaults to 30 m); where filters further. For neighbor queries every step use forEachNear. Example: `engine.world.query({ kind: 'zombie', near: engine.player, radius: 30, where: z => !z.dead })`
15
15
  - `world.forEachNear(center: any, radius: number, fn: (rec, d2) => void)` — Call fn(rec, d2) for each record within radius meters (horizontal distance) of center; d2 is the squared distance. Unsorted, no allocation: use it for per-step neighbor queries (hundreds of zombies avoiding each other). Don't add / remove / move in the callback (moving into a cell not yet visited visits it again): record the change and apply it after the loop. Example: `engine.world.forEachNear(rec.position, 5, (o, d2) => { if (o !== rec && o.kind === 'zombie') n++; })`
16
- - `world.present(kind: string, opts: { build, update?, dispose?, show?, radius?, positionFrom? }) → { remove(): void }` — Register how a kind of thing looks: models are built automatically within radius meters of any full-detail stream source (engine.stream: player, camera focus, teleport destination) and torn down when far from all of them (radius × 1.25); tearing down never touches the record. Callbacks: build(rec) → three.js object (may be async). world adds it to the scene and places it at rec.position; if it throws / fails / returns a non-object: reported once, does not block ready, retried when you leave and come back. update(rec, obj, dt): called every frame for records that have a model (change the picture from the data, e.g. an opened chest swaps texture). dispose(rec, obj): called on teardown (record first, model second); if omitted, engine.remove(obj). show(rec) → false: this record has no model right now (picked up, waiting to respawn); re-evaluated when world.set changes records of this kind. Example: `engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, new THREE.MeshStandardMaterial()), dispose: (rec, obj) => engine.remove(obj), show: rec => !rec.looted })`
16
+ - `world.present(kind: string, opts: { build, update?, dispose?, show?, radius?, positionFrom? }) → { remove(): void }` — Register how a kind of thing looks: models are built automatically within radius meters of any full-detail stream source (engine.stream: player, camera focus, teleport destination) and torn down when far from all of them (radius × 1.25); tearing down never touches the record. Callbacks: build(rec) → three.js object (may be async). world adds it to the scene and places it at rec.position; if it throws / fails / returns a non-object: reported once, does not block ready, retried when you leave and come back. Only the position is world's: rec.rot / rec.scale are the build's to apply (rotate the root or a child, in its own units) and update's to follow. update(rec, obj, dt): called every frame for records that have a model (change the picture from the data, e.g. an opened chest swaps texture). dispose(rec, obj): called on teardown (record first, model second); if omitted, engine.remove(obj). Example: `engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, new THREE.MeshStandardMaterial()), dispose: (rec, obj) => engine.remove(obj), show: rec => !rec.looted })`
17
17
  - `world.view(id: string) → any` — The current model of this record (only exists nearby; null if not built yet or far away)
18
18
  - `world.refresh()` — Build / tear down models for the stream sources right now (normally automatic every frame, with a per-frame limit). Use it right after add when you need the model: sync builds are available via view(id) after the call, for async ones also await world.whenReady. Example: `engine.world.add({ id: 'gate', kind: 'gate', position: p }); engine.world.refresh(); engine.world.view('gate')`
19
19
  - `world.simulate(kind: string, opts: { near?, far?, farEvery?, radius?, fullRadius?, nearEvery?, … }) → { remove(): void }` — Register how a kind of thing changes (gameplay logic goes here, runs in the fixed step); near / far is split by distance from world.anchor (default: the player): near(rec, dt, obj): within radius, once per fixed step (obj is the model, may be null if not built yet; gameplay must not depend on it); far(rec, dt): farther away, once every farEvery seconds; dt is the seconds accumulated since the last simulation (can catch up a long time at once); on the far → near step, far runs first to pay back the owed time. With only far (crops), near also advances via far; with only near, far records are not simulated and owed time is not made up. Both dt are accumulated real (fixed-step) seconds (not multiplied by clock.rate). For things measured in game clock (grows over days) store engine.clock.now and compare. Example: `engine.world.simulate('zombie', { near: (rec, dt) => chase(rec, dt), far: (rec, dt) => wander(rec, dt), farEvery: 2 })`