threedog 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -1,12 +1,13 @@
1
1
  # engine — createEngine and the Engine class (core)
2
2
 
3
- - `createEngine(opts: EngineOptions) → Engine` — Create an engine (core only). canvas is required; style is the game's style (see recipes/09-materials-lights-models.md)
3
+ - `createEngine(opts: EngineOptions) → Engine` — Create an engine (core only). canvas is required
4
4
  - Options `EngineOptions`:
5
5
  - `canvas?: HTMLCanvasElement | HTMLElement` Canvas element (required unless renderer is given), e.g. document.getElementById('view')
6
6
  - `renderer?: 'webgl' | 'webgpu' | EngineRenderer` 'webgl' (default): the engine builds a WebGLRenderer. 'webgpu': it builds three's WebGPURenderer (needs import 'threedog/tsl' first) and start() awaits its init(). Or a ready three.js renderer (WebGLRenderer or WebGPURenderer) used as is; canvas then defaults to renderer.domElement.
7
7
  - `fallback?: 'webgl2' | 'webgl' | 'error'` WebGPU route only: what start() does when the browser gives no WebGPU. 'webgl2' (default): the same WebGPURenderer on its WebGL2 backend, TSL keeps working; 'webgl': a WebGLRenderer instead (faster, but NodeMaterials cannot draw: start() fails if the scene has one); 'error': start() rejects.
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. The start value is the canvas's own MSAA (no post chain while no effect is on)
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
+ - `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 })`
10
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
12
  - `targetFps?: number` Target frame rate for automatic resolution lowering, default 55
12
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 } })`
@@ -19,84 +20,82 @@
19
20
  - `saveKey?: string` Save name prefix; must differ when several games share one site, default 'game'
20
21
  - `joystick?: 'auto' | boolean` On-screen joystick: 'auto' (only on touch devices) / true / false
21
22
  - `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
22
- - `validate?: boolean` 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
23
- - `decoders?: string` 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
23
+ - `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
+ - `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
24
25
  - `budget?: BudgetLimits` Performance budget limits, e.g. { drawCalls: 250, fps: 55 }; only the given categories are checked; off by default
25
- - `urlState?: boolean` Set up a scenario from URL parameters (?time=18:30&weather=rain&pos=40,-20), default on only in development
26
+ - `urlState?: boolean` (experimental) Set up a scenario from URL parameters (?time=18:30&weather=rain&pos=40,-20), default on only in development
26
27
  - `seed?: number` Seed for engine.random; default 1 in headless mode (reproducible), the current time for live runs (different every game)
27
28
  - `movement?: Partial<MovementProfile>` Shared "can walk there" parameters (meters / degrees): collision, the Rapier capsule, navigation and level steps all read them by default. Default { radius: 0.4, height: 1.8, maxSlope: 48, stepHeight: 0.45 }
28
29
  - `threads?: 'auto' | number | false` (experimental) Worker pool size for engine.threads: 'auto' (default: cores - 1, at most 4), a worker count, or false (all on the main thread, same results, no workers created)
29
30
  - `pauseOnBlur?: boolean` Gameplay waits while the window is in the background or the tab is hidden; default true (engine.page)
30
31
  - `lights?: boolean` false: no default lights in the scene at all (engine.lights.sun / hemi still exist, detached, so sky and describe never see undefined); the game adds its own. No light of the engine's reaches the picture. Default true
31
- - `batching?: false | BatchingOptions` Automatic instancing of repeated static models the engine places (engine.batching; your own meshes opt in with userData.batch = true): false turns it off; default { minCount: 8, cell: engine.stream.cellSize }
32
+ - `batching?: false | BatchingOptions` Automatic instancing of repeated static models the engine places (engine.batching; your own meshes opt in with userData.batch = true): false turns it off; default { minCount: 8, cell: 4 * engine.stream.cellSize }
32
33
 
33
34
  ## engine methods
34
35
  - `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()`
35
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']`
36
37
  - `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
37
- - `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`
38
- - `engine.wrap(target: T, method: string, fn: (next, args) => any, opts?: { owner?: string }) → Handle` — 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' })`
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.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' })`
39
40
  - `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'); });`
40
41
  - `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' })`
41
42
  - `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');`
42
- - `engine.has(name: string) → boolean` — Whether a module is installed
43
+ - `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
43
44
  - `engine.setGround(g: Partial<Ground>)` — Set the ground (called by the terrain and level modules); missing parts fall back to flat ground
44
45
  - `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)
45
- - `engine.slope(x: number, z: number) → number` / `slope(at: PositionLike) → number` — Slope at (x, z); a position or object also works
46
- - `engine.groundType(x: number, z: number) → string` / `groundType(at: PositionLike) → string` — Ground type at (x, z) (for footsteps, particles); a position or object also works. 'void' off the outline of terrain({ shape })
47
- - `engine.waterAt(x: number, z: number) → number` / `waterAt(at: PositionLike) → number` — Water surface height at (x, z): standalone water bodies first, otherwise the global water level; -Infinity when there is no water. A position or object also works
46
+ - `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
+ - `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 })
48
+ - `engine.waterAt(x: number, z: number, refY?: number) → number` / `waterAt(at: PositionLike, refY?: number) → number` — Water surface height at (x, z): standalone water bodies first, otherwise the global water level; -Infinity when there is no water. A position or object also works
48
49
  - `engine.snapToGround(obj: T, offset?: number) → T` — Put an object on the ground under it (y = ground height + offset) and return the object. With multi-layer ground the object's current y is the reference height
49
50
  - `engine.addWaterBody(opts: WaterBodyOptions) → Handle & { body: WaterBody }` — Add a water body (give radius for a circle, halfWidth / halfDepth for a rectangle) and return a handle { body, remove() }. The water module draws it
50
- - `engine.t(key: string, params?: Record<string, any>) → string` — Get UI text (i18n)
51
+ - `engine.t(key: string, params?: Record<string, any>) → string` — Get UI text (i18n): {name} in the text takes params.name, {key:action} the label of the key bound to that action; a key with no text comes back as itself. Example: `engine.t('shop.buy', { name: 'Fish' });`
51
52
  - `engine.add(obj: T, ...more: (Object3D | { id?, save? })[]) → T` — Add objects to the scene and register them (engine.thing), returns the first one. The last argument may be { id?, save? }: id makes thing.set / thing.remove changes saved (unique, no '#', one object per call); without it a unique obj.name is used, else a session id obj#n. save: true asks dev to warn when it cannot be saved. engine.scene.add adds without registering. Example: `engine.add(windmill, { id: 'windmill' });`
52
53
  - `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'`
53
54
  - `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)
54
- - `engine.detach(...objs: Object3D[])` — Only take it off its parent without releasing GPU memory (use when you will add it back later). Use remove for objects you no longer need
55
55
  - `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
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
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
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`
59
- - `engine.bakeProbes(opts: { bounds, spacing, resolution?, include?, owner? }) → Promise<ProbeSet>` — 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
- - `engine.loadProbes(json: ProbeData, opts?: { owner?: string }) → ProbeSet` — 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
- - `engine.loadLightmap(file: string | ArrayBuffer, opts?: { owner?: string }) → Promise<Lightmap>` — 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');`
62
- - `engine.setPixelRatio(p: number)` — Render resolution
59
+ - `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
+ - `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
+ - `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');`
62
+ - `engine.setPixelRatio(p: number)` — Render resolution, and the top adaptive resolution climbs back to. Throws while pixelSize is on
63
+ - `engine.setPixelSize(k: number | null)` — One art pixel becomes k real screen pixels (createEngine({ pixelSize }) at runtime). While on, adaptive resolution stops, engine.setPixelRatio throws and a photo keeps the art pixels. null turns it off and brings the ratio from before back. Example: `engine.setPixelSize(3);`
63
64
  - `engine.raycast(origin: Vec3Like, dir: Vec3Like, opts?: RaycastOptions) → RayHit | null` — Ray: shoot from origin along dir, returns the nearest hit or null (by default only registered static objects are hit)
64
- - `engine.pick(ndcX: number, ndcY: number, opts?: RaycastOptions) → RayHit | null` — Shoot a ray through the camera from screen coordinates (-1..1, e.g. input.pointer.ndcX/ndcY)
65
- - `engine.applyState(params: StateParams) → Promise<void>` — Set up a scenario: time of day, weather, player position, load a save, advance time, skip cutscenes; emits state:applied when done
65
+ - `engine.pick(ndcX: number, ndcY: number, opts?: RaycastOptions) → RayHit | null` — Shoot a ray through the camera from screen coordinates (-1..1, e.g. input.pointer.ndcX/ndcY). The ray comes from the camera as last drawn: a rig.yaw / rig.pitch write reaches it on the next drawn step, so several shots in one step with recoil between them cast from the rig's angles with engine.raycast (recipe 19)
66
+ - `engine.applyState(params: StateParams) → Promise<{ ok: boolean, refused: {…` — Set up a scenario: time of day, weather, player position, load a save, advance time, skip cutscenes; emits state:applied when done
66
67
  - `engine.defineState(name: string, params: StateParams, opts?: { owner?: string }) → { owner?: string; remove(): void }` — Name a group of scenario parameters, then use applyState({ state: name }) or URL ?state=name. Returns a handle: remove() forgets the name
67
68
  - `engine.start() → Promise<this>` — Start: initialize modules, preload assets, wait for the world to be ready
68
- - `engine.pause(owner?: string | { owner?, kind? }, opts?: { kind?: 'test' }) → 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
69
+ - `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
69
70
  - `engine.nextFixed(fn: () => T) → Promise<T>` — Run fn at the start of the next fixed step (via commits); a Promise of fn's value
70
- - `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) keeps moving while frozen; { ambient: true } stops it too
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)
71
72
  - `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
72
73
  - `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' })`
73
74
  - `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);`
74
75
  - `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);`
75
76
  - `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 })`
76
- - `engine.explain(q: { op, args?, actor? } | Record<string, any>) → { 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. 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)'`
77
+ - `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)'`
77
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
78
79
  - `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.
79
80
  - `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)
80
81
 
81
82
  ## engine properties (module properties are on each module page)
82
- - `THREE: typeof import('three')` three.js (a game can also import { THREE } from 'threedog' directly)
83
+ - `validate: boolean` False when createEngine({ validate: false }) turned the development checks off for this engine
83
84
  - `renderer: EngineRenderer` three.js renderer: WebGLRenderer, or WebGPURenderer on the WebGPU route (EngineRenderer)
84
- - `tier: 'low' | 'high'` Device tier: 'low' (phones, integrated graphics) / 'high'. A headless page takes it from ?threedog-tier=low/high (threedog shot / gallery / capture pass high, shot --tier low checks the low tier)
85
+ - `tier: 'low' | 'high'` The one quality value, what everything that scales by quality reads: the device's tier, 'low' (phones, integrated graphics) / 'high', unless the player's preset says otherwise (shared point 'tier'). A headless page takes the device's from ?threedog-tier=low/high (threedog shot / gallery / capture pass high, shot --tier low checks the low tier)
85
86
  - `scene: import('three').Scene` three.js scene
86
87
  - `lights: { sun, hemi }` Placeholder lights: neutral and still, nothing moves them (the sky only gives signals). createEngine({ lights: false }) leaves them out of the scene
87
- - `camera: import('three').PerspectiveCamera` three.js PerspectiveCamera (class EngineCamera, core/engineCamera.js): a camera rig with projection: 'orthographic' switches it to an orthographic matrix in place (orthoSize; describe().camera.projection says which)
88
+ - `camera: import('three').Perspec… | import('three').Orthogr…` The camera the engine draws with, a plain THREE.PerspectiveCamera to begin with. Assign a real THREE.PerspectiveCamera or THREE.OrthographicCamera to draw through it; any other class is refused [camera-option].
88
89
  - `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
89
90
  - `ground: Ground` Current ground
90
91
  - `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
91
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
92
93
  - `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
93
- - `phase: 'constructed' | 'loading' | 'ready' | 'running' | 'disposed'` Where the engine is in its life: 'constructed' (start() not called) -> 'loading' (start() running: 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'. engine.step() during loading runs frame hooks only
94
+ - `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'.
94
95
  - `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)
95
96
  - `disposed: boolean` phase is 'disposed'
96
- - `moduleOrder: string[]` Execution order of module hooks (module names, first -> last), for debugging "who runs before whom"
97
- - `moduleStates: Record<string, 'registered' | 'initializing' | 'running' | …` Where each module is: 'registered' (init not started), 'initializing', 'running', 'failed' (init threw: its hooks never run) or 'disposed'. A module installed after start() runs no fixed / frame hook until it is 'running'; `await engine.loading.settled()` waits for that
97
+ - `moduleOrder: string[]` (experimental) Execution order of module hooks (module names, first -> last), for debugging "who runs before whom"
98
98
  - `error: EngineError | null` Gameplay error in development / testing (module hooks, onFixed / onFrame / clock callbacks, event listeners): { where (location of the error), message }, gameplay is frozen; null when there is no error. A release build does not freeze, it reports once in the console
99
- - `disabledModules: Set<string>` Names of picture / ui modules disabled after an error (a module's type decides: picture and ui fail soft)
100
99
  - `signal: AbortSignal` The engine's cancel signal (AbortSignal): for DOM listeners write addEventListener(type, fn, { signal: engine.signal }), removed automatically on dispose()
101
100
  - `uiRoot: HTMLDivElement` UI root node: UI elements of the engine and modules hang under it (don't attach to document.body directly), the whole tree is removed on dispose()
102
101
  - `modules: Map<string, ModuleDef>` Installed modules: name -> module definition
@@ -109,30 +108,28 @@
109
108
  - `input: Input` Input
110
109
  - `audio: Audio` Audio
111
110
  - `assets: Assets` Assets
111
+ - `picture: any` The API of the module holding the 'picture' slot (recipe 62), undefined when no look is installed: engine.use(next(), { replaces: 'picture' }) changes it, so read it again after a switch
112
112
  - `loading: Loading` Observable loading: every asset load, module init / isReady and track() step as a task (phase, error, source manifest)
113
113
  - `post: PostFX` Post-processing: named effects in slots (add / get / enable / list)
114
114
  - `occlusion: Occlusion` Occlusion culling of the engine's big things (hlod cells, batched groups) on both renderers. Off by default; it pays only when heavy things hide behind others (recipe 34)
115
115
  - `ui: UIParts` UI parts: every piece of screen UI is replaceable or off (see recipes/26-ui-parts.md)
116
116
  - `adaptive: AdaptiveState` Automatic resolution state
117
- - `cpuMs: number` Main-thread CPU milliseconds of the last real-time frame: input, fixed steps, frame hooks, render submission and afterRender hooks (not GPU time, not the wait for the next frame). Only the real-time loop updates it; step() does not.
118
- - `cpuPhases: { fixed, frame, render, afterRender }` cpuMs split by phase (last frame): fixed = input + fixed steps, frame = frame hooks incl. stream / jobs, render = draw submission, afterRender = its hooks
117
+ - `stepBlend: number` How far the drawn frame is from the last fixed step to the next, 0-1 (real loop); 1 after step(). Holds still while frozen. For drawing fixed-step state smoothly
119
118
  - `cameraOverride: CameraOverride | null` The camera holder in charge (latest engine.takeCamera claim), null when nobody holds it. Read-only
120
119
  - `runState: RunState` Why the page is (not) advancing; the dev bridge and MCP tools copy it as-is
121
- - `decoders: string` Draco/KTX2 decoder directory
122
120
  - `clock: Clock` Calendar clock: calendar seconds now, after / every, the rate (clock-time / season timers are on engine.calendar)
123
- - `stacks: import('./gameplay').Stacks` Every shared quantity by name; define your own with engine.stacks.define(name, { base })
124
- - `control: Control` Who decides where each character goes: one holder in charge per character, layers base < script < cutscene < net; a higher one pauses the lower until it ends. engine.control.take(ch, { owner, layer, step }) / .of(ch). Recipe 57. Example: `const h = engine.control.take(npc, { owner: 'escort', layer: 'script', step: () => ({ x: 0, z: 1 }) }); ... h.remove();`
121
+ - `stacks: import('./gameplay').Stacks` (experimental) Every shared quantity by name; define your own with engine.stacks.define(name, { base })
122
+ - `control: Control` Who decides where each character goes: one holder in charge per character, layers base < script < cutscene < physics < net; a higher one pauses the lower until it ends. engine.control.take(ch, { owner, layer, step }) / .of(ch). Recipe 57. Example: `const h = engine.control.take(npc, { owner: 'escort', layer: 'script', step: () => ({ x: 0, z: 1 }) }); ... h.remove();`
125
123
  - `time: import('./gameplay').Time` Time channels: read seconds with time.now('real' / 'ambient' / 'calendar' / a channel such as 'world'), speeds with scale(ch, id?)
126
124
  - `vars: Vars` Story flags and counters (autosaved)
127
125
  - `budget: Budget` Performance budget (off by default)
128
- - `plugins: { add, off, on, list }` The plugins folder: files in the game's plugins/ plugged at start by what they export (core/plugins.js); describe().slots lists them (add() off() on() list())
126
+ - `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())
129
127
  - `rays: Rays` Ray registry (what engine.raycast hits)
130
128
  - `jobs: Jobs` Frame-spread job scheduler
131
- - `commits: Commits` Background results that affect gameplay take effect on a fixed tick (chunk collision, spread jobs with apply...), see Commits
129
+ - `commits: Commits` (experimental) Background results that affect gameplay take effect on a fixed tick (chunk collision, spread jobs with apply...), see Commits
132
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
133
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
134
132
  - `views: Views` Named fixed camera views for repeatable screenshots: define / show / release (recipes/46-blender-art-route.md)
135
- - `tick: number` Fixed-step count (= engine.time.tick, the one time counter: does not advance while frozen; commits due times, event history and the operation log use it). Seconds are views of it: engine.time.now('real' / 'ambient' / 'calendar' / channel)
136
133
  - `random: Random` Seeded random numbers, an object (not a function): engine.random.next() in [0, 1), .range(a, b), .int(a, b), .pick(list), .chance(p). Use it for gameplay randomness: reproducible and saved with the game
137
134
  - `stream: Stream` Spatial stream-in and the stream sources (where the world is loaded: terrain, colliders, models, stream entries; built-in player and camera sources, add one for a teleport destination)
138
135
  - `batching: Batching` Automatic batching: the same static model the engine placed (world records, stream builds, level files) many times in a cell is drawn as one InstancedMesh; your own meshes only with userData.batch = true (createEngine({ batching }))
@@ -141,41 +138,48 @@
141
138
  - `waterLevel: number` Global water level (meters); -Infinity when there is no water
142
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
143
140
  - `shadows: Shadows` Shadow engineering on lights you hand in: enabled, cascades, box, budget, include (recipes/45): core, always there
144
- - `view: View` The camera and drawing-buffer values the engine changes on its own: manual() takes one (recipes/52): core, always there
145
- - `terms: Terms` Your own cloud shadow or season tint in place of the engine's (recipes/52): core, always there
146
- - `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)
141
+ - `autoView: View` The camera and drawing-buffer values the engine changes on its own: manual() takes one (recipes/52): core, always there
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)
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
147
145
  - `headless: boolean` Whether in headless mode (createEngine({ headless: true }))
148
- - `paused: boolean` Whether paused (headless mode is paused by default, only step() advances)
146
+ - `halted: boolean` Whether the real-time loop is stopped: only step() advances the game (headless mode starts this way)
149
147
  - `fps: number` Smoothed frame rate
150
- - `openWindows: Set<string>` Ids of the open windows
151
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
152
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).
153
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' }] }`
154
152
 
155
153
  ## Module definition (engine.use(myModule()))
156
154
  - **ModuleDef** A module (the argument of engine.use). The name is the property name on the engine once installed. Per-frame hook order follows stage, then before / after within a stage, then install order.
157
155
  - `name: string` Module name; after install, access the object returned by install through engine[name]
158
- - `type: ModuleType` What the module may own (required; core/moduleTypes.js): 'world' state, records, ops (draws nothing) / 'picture' what is seen and heard (changes no game state: no ops, no world record writes) / 'actor' characters / 'rules' game logic / 'ui' panels and menus (binds no keys, no game save part) / 'net' multiplayer / 'tool' a one-shot job.
156
+ - `type?: ModuleType` What the module owns (default 'rules'; core/engine/moduleTypes.js): 'world' state, records, ops (draws nothing) / 'picture' what is seen and heard (changes no game state: no ops, no world record writes) / 'actor' characters / 'rules' game logic / 'ui' panels and menus (binds no keys, no game save part) / 'net' multiplayer / 'tool' a one-shot job.
159
157
  - `label?: string` Display name (used by the loading screen)
160
158
  - `requires?: string[]` Capabilities this depends on: slot names another module provides ('inventory', 'world', 'sky'), never a particular module. Missing throws with both fixes: install the engine's part of that name first, or your own module with provides: ['inventory']
161
159
  - `provides?: (PictureSlot | (string & {}))[]` Capabilities this module holds while installed ("only one may hold this": 'sky', 'inventory'); engine.<slot> is its API too, so dependents keep working when a game swaps it: engine.use(mine(), { replaces: 'inventory' }). A second provider throws shared-taken. describe().shared shows the holder.
162
160
  - `optional?: string[] | Record<string, string>` Optional dependencies (modules the code uses as e.xxx?. or guards with if (e.xxx); rule R16 requires listing them all). An array only registers them; written as { moduleName: 'what is lost when missing' }, start() prints a one-time development hint when one is missing; use this form when it changes gameplay results
163
161
  - `stage?: 'control' | 'ground' | 'environment' | 'gameplay' | 'effects' | 'late' | 'audio'` Hook stages, only the run order (first -> last): 'control' timeline, camera -> 'ground' terrain, level -> 'environment' weather, sky, water -> 'gameplay' interactions, dialogue, triggers -> 'effects' particles, settings, objective markers -> 'late' (default) -> 'audio' music. Within a stage use before / after, then install order.
164
- - `before?: string[]` Hooks run before these modules, inside one stage (ignored if not installed; use() throws on a cycle, or when the other module's stage already runs earlier)
165
- - `after?: string[]` Hooks run after these modules, inside one stage (ignored if not installed; use() throws on a cycle, or when the other module's stage already runs later)
162
+ - `before?: string[]` Hooks run before these modules or capabilities, inside one stage (ignored if not installed; a capability means whichever module provides it now; use() throws on a cycle, or when the other module's stage already runs earlier; reached through a capability that is a dev warning and the stage order stays)
163
+ - `after?: string[]` Hooks run after these modules or capabilities, inside one stage (ignored if not installed; a capability means whichever module provides it now; use() throws on a cycle, or when the other module's stage already runs later; reached through a capability that is a dev warning and the stage order stays)
166
164
  - `critical?: boolean` The game cannot run without this module (default false): when its init() fails, engine.start() rejects with the module name and reason instead of starting a broken game. Without it a failed init is reported by severity (type picture / ui: disabled and the game carries on; other types: error tiers) and start() goes on. Example: `engine.use({ name: 'saveSlots', type: 'rules', critical: true, async init(e) { await loadSlots(); } })`
165
+ - `content?: Record<string, ContentSection>` Content sections this module owns: their format, checks and how the data becomes live state (validate, prepare, commit). See core/base/sections.js
166
+ - `noSkip?: string` Why a module with a fixed hook has no skip hook
167
+ - `skipKind?: 'exact' | 'approx' | 'step' | 'none'` How engine.skip advances it. exact: the same state as stepping, from the clock or a hook. approx: a hook catches up with an estimate. step: a hook replays the steps. none: a jump moves nothing here. A module with a fixed or skip hook declares it (engine.catalog reports one that does not); engine modules always do
168
+ - `params?: any` The option schema (core/base/params.js): engine.catalog shows it, and dev checks the module's options against it
169
+ - `docs?: string` Where its docs live, shown by engine.catalog
167
170
  - `explain?: Record<string, (e: Engine, value: any, query: Record<string…` Optional: answer engine.explain({ key: value }) for your own keys, e.g. explain: { quest: (e, id) => ({ ok: false, text: 'waits on step 2: ...' }) }
171
+ - `stateKeys?: string[]` Optional: the applyState keys this module handles; a key no module handles is reported in applyState's refused list. Leave out to count for every key
168
172
  - `install(e: Engine, ctx: ModuleCtx) → Api` — Install: create and return the object the game uses (engine.name). Register listeners / timers through ctx.track so they leave with the module (a use() batch that rolls back, a failed init, engine.dispose). Example: `install(e, ctx) { ctx.track(e.events.on('item:add', onAdd)); return api; }`
169
173
  - `init(e: Engine, ctx: ModuleCtx) → void | Promise<void>` — Called at startup (download things, wait for assets); may be async. ctx is the same as install's
170
174
  - `isReady(e: Engine) → boolean` — The loading screen waits until this returns true before disappearing (the hook is called isReady; in the engine ready is always a boolean property)
171
- - `afterLoad(e: Engine) → void | Promise<void>` — After a save loaded: rebuild what the loaded state needs nearby; gameplay waits frozen until the returned Promise resolves
175
+ - `afterLoad(e: Engine, turn: SaveTurn) → void | Promise<void>` — After a save loaded: rebuild what the loaded state needs nearby; gameplay waits frozen until the returned Promise resolves. turn: as SaveProvider.load
172
176
  - `fixed(dt: number, e: Engine)` — Fixed step (60 times per second); dt is in seconds
173
177
  - `frame(dt: number, e: Engine)` — Once per frame; dt is in seconds
174
178
  - `afterRender(dt: number, e: Engine)` — After rendering
175
179
  - `skip(dt: number, e: Engine, done: boolean)` — engine.skip moved time without stepping: advance your own time by dt fixed seconds (calendar seconds = dt x clock.speed), no per-step work. Called once per skip segment (segments end at timers and calendar clock marks); done is true on the last one: do expensive catch-up only then. Only for modules that keep time themselves (calendar, world); modules that compare against clock.now need nothing
176
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"
177
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)
178
- - `applyState(e: Engine, params: StateParams) → void | PositionLike | 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
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
179
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
180
184
 
181
185
  ## createEngine({ ui })
@@ -219,11 +223,11 @@
219
223
  - `play?: string | boolean` Present (?play, any value): leave the title screen the way its Start does (engine.session.newGame(), the title part closes; flow leaves its start state) before wait; nothing when no title is up
220
224
  - `fresh?: string | boolean` Delete every save of this page first (no Continue on the title); on a running page also end the run and go back to the title. ?fresh in the URL
221
225
  - **StartupReport** Startup timing (milliseconds): totalMs page open to playable, startMs start() to playable, preloadMs preloading, streamMs the nearby builds required by stream registrations finished, compileMs shader compilation before the first frame, modules is the init / ready time of each module. With a budget on and startupMs (open to playable) / moduleMs (a single module) given, the slowest module is reported in the console when exceeded. firstFrameMs: page open to the end of the first frame drawn after the loading screen (null until that frame, and headless); phases add up to it: script (page open until createEngine), construct (createEngine), setup (game code until start()), init (saves, renderer, module init), preload, world (scenario parameters, nearby builds), compile (shaders + hidden warm-up frame), draw (ready until the first frame's draw calls were submitted)
222
- - `totalMs: number`
223
- - `startMs: number`
224
- - `preloadMs: number`
225
- - `streamMs: number | null`
226
+ - `totalMs: number` (experimental)
227
+ - `startMs: number` (experimental)
228
+ - `preloadMs: number` (experimental)
229
+ - `streamMs: number | null` (experimental)
226
230
  - `compileMs: number`
227
231
  - `modules: Record<string, { init?: number; ready?: number }>`
228
- - `firstFrameMs: number | null`
229
- - `phases: { script, construct, setup, init, preload, world, … }`
232
+ - `firstFrameMs: number | null` (experimental)
233
+ - `phases: { script, construct, setup, init, preload, world, … }` (experimental)
@@ -29,15 +29,18 @@
29
29
  - `day:start` [day: number] A new day (the argument is the day number, starting at 1; needs the calendar module)
30
30
  - `season:change` [season: string] Season changed (the argument is the season name, e.g. 'autumn')
31
31
  - `mod:end` [{ target: string; owner: string; id: string | null }] A mod with `for` ran out (engine.mod(target, { owner, for })): target is the quantity's name, id the record for per-record ones
32
- - `time:skip` [{ seconds: number }] engine.skip jumped game time forward (seconds = game seconds skipped); timers and world catch-up already ran
32
+ - `time:skip` [{ seconds: number }] engine.skip jumped game time forward (seconds = calendar seconds skipped); timers and world catch-up already ran
33
33
  - `weather:lightning` [] Lightning strike (weather module)
34
34
  - `weather:change` [change: { from: string; to: string }] engine.weather.set switched to another weather name (once, when the blend starts; setting the same name again does not fire)
35
35
  - `camera:shot` [CameraShotEvent] The fixed-shot camera switched shots
36
36
  - `camera:change` [{ kind: string; previous: string }] engine.setCamera switched the camera kind; settings that belong to the camera (sensitivity, invert Y, field of view) are re-applied on it
37
37
  - `character:jump` [{ character: Character; air: boolean; index: number }] A character jumped
38
38
  - `character:launch` [{ character: Character; speed: number; owner: string }]
39
- - `character:fall` [{ character: Character; safe: Vector3 | null; preventDefault(): void…
39
+ - `link:enter` [{ id: string; character: Character; crossing: LinkCrossing }] (experimental) A walker reached a nav link. Set crossing.seconds here to say how long it takes
40
+ - `link:exit` [{ id: string; character: Character | null; crossing: LinkCrossing }] (experimental) A crossing ended: landed, or cut short (npc.placeAt, walk.remove()). character is null for an NPC that went out of range mid-crossing
41
+ - `character:fall` [{ character: Character; safe: Vector3 | null }]
40
42
  - `character:model` [{ character: Character; model: Object3D }] A character's model named by asset finished loading and replaced the placeholder body (same root; anim is now set)
43
+ - `character:step` [{ character: Character }] A foot of a walking character came down; character.groundType() is what it stepped on
41
44
  - `character:land` [{ character: Character; impact: number }] A character landed; impact is the landing speed (m/s), the larger the harder the fall
42
45
  - `character:water` [{ character: Character; in: boolean; mode: string; depth: number }] A character went into or out of deep water (water option): in true on entering, mode what the water option did there ('swim' / 'block' / 'wade', or what the function returned)
43
46
  - `dialogue:start` [speaker: string] Dialogue started; the argument is the dialogue script name
@@ -55,13 +58,19 @@
55
58
  - `quest:done` [{ id: string }] A quest completed
56
59
  - `quest:part` [{ id: string; step: number; part: number }] A part of a parallel quest step was met; step and part are indexes (starting at 0)
57
60
  - `quest:fail` [{ id: string }] A quest failed (its fail condition held); quests.start(id) may begin it again
61
+ - `quest:unpaid` [{ id: string; code: string; failed: { word: string; code: string; fa… A finished quest's reward was not given. failed: each word that failed; owed: the items the quest still owes, null when none or when onUnpaid took it
62
+ - `content:failed` [{ code: string; failed: { word: string; code: string; facts: any }[]… A content effect word failed ({ give } in a full bag, { op } refused), wherever it ran: a dialogue do, a trigger, a reward, content.run. actor: whose effect it was
58
63
  - `photo:taken` [PhotoShot] A photo was taken
59
64
  - `photo:denied` [{ reason: string }] The photo key was pressed but the op photo.take was refused (reason from photo.canTake(), 'denied' when it returned false)
60
65
  - `trigger:enter` [TriggerEvent] Entered a trigger zone
61
66
  - `trigger:exit` [TriggerEvent] Left a trigger zone
62
- - `level:loaded` [LevelLoadedEvent] Level finished loading
67
+ - `level:loading` [LevelLoadingEvent] Level finished loading
68
+ - `level:loaded` [LevelLoadedEvent]
69
+ - `level:unloaded` [LevelUnloadedEvent]
70
+ - `level:playable` [LevelPlayableEvent]
71
+ - `level:failed` [LevelFailedEvent]
63
72
  - `timeline:start` [{ id: number }] A cutscene started
64
- - `timeline:end` [{ id: number; skipped: boolean }] A cutscene ended; skipped tells whether it was skipped
73
+ - `timeline:end` [{ id: number; ending: 'finished' | 'skipped' | 'dropped' | 'failed';… A cutscene ended; ending says how, error why it failed
65
74
  - `template:stage` [TemplateStageEvent] A content template instance entered a new stage by growing (templates with stages)
66
75
  - `ground:change` [{ x0: number; z0: number; x1: number; z1: number }] The ground's shape or type changed in this world-space box (engine.terrain.edit): cached ground samples (path rasters) inside it are stale
67
76
  - `rigid:rebuilt` [{ world: any; player: any; bodies: Record<string, any> }] rigid: newGame / a load rebuilt the physics world (a fresh page for physics) and the engine's bodies are back (entry.body is the rebuilt Rapier body; bodies maps the ids given to addBox / addBall / addHull / addWheeled). The old world's joints were freed with it: re-create the game's joints here (recipes/11-vehicles.md, Joints). Not emitted while a vehicle exists (the world is kept then, joints included)
@@ -70,7 +79,7 @@
70
79
  - `vegetation:remove` [VegetationRemoveEvent] A vegetation instance was chopped / removed
71
80
  - `vegetation:restore` [VegetationRemoveEvent] A vegetation instance was restored
72
81
  - `music:change` [MusicChangeEvent] Background music changed track (null means silence)
73
- - `music:stinger` [{ name: string }] A stinger was played
82
+ - `music:stinger` [{ name: string; played: boolean }] A stinger was played
74
83
  - `state:applied` [StateParams] Scenario parameters were applied (URL parameters or engine.applyState)
75
84
  - `state:placed` [{ x: number; z: number }] A scenario (at, pos) moved the player: a camera or view that eases jumps there
76
85
  - `anim:end` [{ root: Object3D; state: string }] A one-shot action of the animation state machine finished
@@ -86,13 +95,15 @@
86
95
  - `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
87
96
  - `engine:error` [EngineError] A gameplay error in development / testing; gameplay is frozen (error severity levels, see engine.error)
88
97
  - `module:disabled` [{ name: string; message: string }] A picture or ui module errored and was disabled (the game continues)
98
+ - `module:restored` [{ modules: any[] }]
99
+ - `state:replaced` [{ undone: boolean }]
89
100
  - `vehicle:enter` [{ character: Character; vehicle: Rideable }] A character boarded a vehicle
90
101
  - `vehicle:exit` [{ character: Character; vehicle: Rideable }] A character exited a vehicle
91
102
  - `flow:change` [{ from: string; to: string }] Game flow state changed
92
103
  - `flow:transition` [{ phase: 'start' | 'end' }] Scene transition: phase 'start' begins fading to black, 'end' finishes fading back in
93
104
  - `session:end` [] A playthrough ends (engine.session.newGame / load / quit), before the reset
94
105
  - `session:start` [{ kind: 'new' | 'load'; slot?: string }] A playthrough started from a clean slate: kind 'new' (newGame) or 'load' (session.load, with the slot)
95
- - `session:failed` [{ kind: 'new' | 'load'; slot?: string }] newGame / session.load failed (a save part's load() threw) and the game was rolled back: the old playthrough goes on, no session:start
106
+ - `session:failed` [{ kind: 'new' | 'load' | 'quit'; slot?: string }] newGame / session.load failed (a save part's load() threw) and the game was rolled back: the old playthrough goes on, no session:start
96
107
  - `page:blur` [{ focused: boolean; visible: boolean }] The page went away: the window lost focus or the tab was hidden (engine.page)
97
108
  - `page:focus` [{ focused: boolean; visible: boolean }] The page came back: focused and visible again
98
109
  - `page:pointerlock` [{ locked: boolean }] The mouse lock on the canvas started or ended (Esc, alt-tab); cameras with pointerLock lock again on the next click
package/docs/api/flow.md CHANGED
@@ -11,7 +11,7 @@ Game flow and scene transitions (flow() module)
11
11
  - `flow.transition(fn: () => any, opts?: FlowTransitionOptions) → Promise<void>` — Scene transition: lock input -> fade to black -> fade out music -> autosave -> fn() -> wait for modules to be ready -> fade in -> unlock; multiple calls queue up
12
12
  - Properties:
13
13
  - `state: string` Current state name
14
- - `transitioning: boolean` A scene transition is in progress
14
+ - `transitioning: boolean` (experimental) A scene transition is in progress
15
15
 
16
16
  ## Data structures
17
17
  - **FlowStateDef** A flow state (title, playing, paused, game over...)
package/docs/api/grids.md CHANGED
@@ -5,7 +5,7 @@
5
5
 
6
6
  ## Methods and properties
7
7
  - `grids.add(name: string, opts?: { cell?, origin?, size?, zone?, flat?, y?, … }) → Grid` — Create a grid. cell: edge length (m, default 1); origin: world [x, z] of the min corner of cell [0, 0]; size: [cells wide, cells deep] (omit = unbounded); zone: level name (tiles only show there); flat: max height difference under a footprint (m, default 0.5); y: height of level 0 (m; default the ground under each cell), levelHeight: meters per level (default 3; level n is at y + n * levelHeight); mapping: { toCell(x, z) => [i, j], center([i, j]) => [x, z] } replaces the square cell <-> world math (one place: toCell, toWorld, tiles, flatness); layers: authored cells { zone: [[i, j, { buildable: true }], ...] } (content/grids.js): the baseline a save diffs against, so a save keeps only changed cells. Example: `const room = engine.grids.add('room', { cell: 0.5, origin: [-3, -3], size: [12, 12], zone: 'house' })`
8
- - `grids.get(name: string) → Grid | null` — A grid by name, or null when there is none
8
+ - `grids.get(name: string) → Grid | undefined` — A grid by name, or undefined when there is none
9
9
  - `grids.list() → Grid[]` — All grids (a new array)
10
10
  - `grids.define(name: string, rule: import("./Grid.js").GridRule)` — Register what can be placed and its rules. size [w, d] in cells (default [1, 1]); kind of the world record (default the item name); occupy: the occupancy layer it takes (default 'main'): things in different layers share a cell ('floor' tile, 'main' table, 'wall' lamp), two in one layer do not; ground: allowed engine.groundType values; layer: { layerName: field } that must be truthy on every cell (reason 'not' + Field, e.g. notBuildable); flat: max height difference (overrides the grid's); fields: copied into the record; can(e, { grid, cell, rotation, cells, level }): your own rule. Example: `engine.grids.define('tower', { size: [2, 2], layer: { zone: 'buildable' }, fields: { range: 6 } }) // tower defense`
11
11
  - `grids.preview(opts: { grid, item, from?, rotate?, rotation?, draw? }) → { cell, rotation, ok, code, rotate, place, … }` — Show where an item would go: the target cell under the pointer ('pointer', default), in front of the player ('front') or from your function, turned by the input action rotate (default name 'rotate'; the game binds it, e.g. presets.bindings.gridRotate; the engine binds no key itself), light when can() passes, dark otherwise (neutral tool colors; grids({ ok, bad }) override them). draw: false = no visual; (engine) => ({ update(view), hide(), dispose() }) = your own; pv.material is the default box's three.js material. place() runs grid.place with what is shown. Example: `engine.input.bind({ place: ['Mouse0'], ...presets.bindings.gridRotate }); // the game's own bindings const pv = engine.grids.preview({ grid: 'field', item: 'tower' }); engine.onFrame(() => { if (engine.input.pressed('place')) { const r = pv.place(); if (!r.ok) toast(engine, engine.t('grid.' + r.code)); } });`
@@ -1,16 +1,15 @@
1
1
  # engine.ground (Ground) — Ground: whoever provides the ground height is the "terrain" (terrain module, level module, or the default flat y=0)
2
2
 
3
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) → number` — Slope at (x, z) (height difference / horizontal distance)
5
- - `ground.type(x: number, z: number) → string` — Ground type at (x, z) (landform name, e.g. 'meadow')
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')
6
6
  - `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
7
  - `ground.voidY() → number` — Height below which something has fallen out of the world (terrain:void): engine.terrain.voidY with terrain({ shape }), else -Infinity
8
8
  - `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)
9
- - `ground.viewRange() → number` — Optional: how far (meters) the ground is shown around a stream source now; stream entries build within it by default (else engine.uniforms.uViewDistance)
10
- - `ground.chunkCollision(cx: number, cz: number) → any` — Optional: collision data of a chunk (used by the physics module)
11
- - `ground.staticTrimeshes() → { positions, indices }[]` — Optional: static triangle mesh (the level module provides it for physics)
12
- - `ground.staticVersion() → number` — Optional: version number of the static mesh; rebuild when it changes
13
- - `ground.navGeometry() → { positions, indices }` — Optional: triangle mesh for building the navmesh (walkable surfaces + obstacle volumes), used by the nav module
9
+ - `ground.viewRange() → number` — (experimental) Optional: how far (meters) the ground is shown around a stream source now; stream entries build within it by default (else engine.uniforms.uViewDistance)
10
+ - `ground.chunkCollision(cx: number, cz: number) → any` — (experimental) Optional: collision data of a chunk (used by the physics module)
11
+ - `ground.staticTrimeshes() → { positions, indices }[]` — (experimental) Optional: static triangle mesh (the level module provides it for physics)
12
+ - `ground.staticVersion() → number` — (experimental) Optional: version number of the static mesh; rebuild when it changes
14
13
  - Properties:
15
14
  - `waterLevel: number` Global water level (meters); -Infinity when there is no water
16
15
  - `chunkSize?: number` Optional: chunk edge length (meters)
package/docs/api/hud.md CHANGED
@@ -7,8 +7,8 @@ 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
11
- - `hud.add(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
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)
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
14
  - `hud.remove(id: string)` — Delete a counter or progress bar
package/docs/api/i18n.md CHANGED
@@ -1,10 +1,10 @@
1
- # engine.i18n (I18n) — engine.i18n: string tables; t(key, params) fetches text and replaces {name} with params
1
+ # engine.i18n (I18n) — engine.i18n: string tables; engine.t(key, params) fetches text and replaces {name} with params
2
2
 
3
+ - `engine.t(key: string, params?: Record<string, any>) → string` — Get UI text (i18n): {name} in the text takes params.name, {key:action} the label of the key bound to that action; a key with no text comes back as itself. Example: `engine.t('shop.buy', { name: 'Fish' });`
3
4
  - `i18n.add(tables: StringTables)` — Register string tables (never overrides text the game gave). Example: `engine.i18n.add({ 'zh-CN': { 'shop.buy': '购买 {name}' }, en: { 'shop.buy': 'Buy {name}' } });`
4
- - `i18n.setLocale(l: string)` — Switch language ('auto' picks from the browser like createEngine)
5
+ - `i18n.setLocale(l: string)` — (experimental) Switch language ('auto' picks from the browser like createEngine)
5
6
  - `i18n.has(key: string) → boolean` — Whether the key exists
6
- - `i18n.t(key: string, params?: Record<string, any>) → string` — Fetch text; params replace {name}, {key:action} shows the key label. Example: `engine.i18n.t('shop.buy', { name: '鱼' });`
7
7
  - Properties:
8
- - `fallback: string` Language used when a key is missing in the current one (default 'en')
9
- - `locale: any` Current language, e.g. 'zh-CN' ('zh' and 'zh-Hans' resolve to it, 'en-US' to 'en')
10
- - `languages: string[]` All available languages
8
+ - `fallback: string` (experimental) Language used when a key is missing in the current one (default 'en')
9
+ - `locale: string` (experimental) Current language, e.g. 'zh-CN' ('zh' and 'zh-Hans' resolve to it, 'en-US' to 'en'). Read-only: setLocale changes it, and tells i18n:change
10
+ - `languages: string[]` (experimental) All available languages
package/docs/api/input.md CHANGED
@@ -2,16 +2,17 @@
2
2
 
3
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`
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
- - `input.touchButton(action: string, labelKey: string)` — 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)
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
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`
8
9
  - `input.rebound() → Record<string, string[]>` — The player's rebindings now in effect: { action: keys } (what the settings menu saves)
9
- - `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
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
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);`
11
12
  - `input.label(action: string) → string` — Key name shown in the UI, e.g. "E"
12
13
  - `input.down(action: string) → boolean` — Held (a snapshot of this step in fixed, the latest state in frame)
13
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(); });`
14
- - `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);`
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
16
  - `input.pressedRaw(action: string) → boolean` — Just pressed, ignoring input contexts (for menus and dialogue themselves, which run while a context blocks the game)
16
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
18
  - `input.describe() → { stack, unbound, rebound }` — describe().input: the context stack, declared actions nobody bound (unbound: isUnbound) and the player's rebindings
@@ -19,12 +20,12 @@
19
20
  - Properties:
20
21
  - `look: { dx: number; dy: number; zoom: number }` This frame's look-drag amount (pixels) and wheel notches
21
22
  - `pointer: Pointer` Mouse/touch pointer
22
- - `stick: { x: number; y: number }` On-screen stick (touch)
23
+ - `stick: { x: number; y: number }` (experimental) On-screen stick (touch)
23
24
  - `autopilot: Autopilot | null` Auto movement (stress tests, test scripts)
24
25
  - `actions: Map<string, { labelKey: string; context: string; optional: …` action name -> its declaration: labelKey (string-table key), context, optional, by (who declared it; null = only bound so far). Keys are not here: keysOf(action) reads the shared point 'input.keys'
25
- - `lastDevice: "keyboard" | "pad" | "touch"` Most recently used device: UI key hints follow it
26
- - `touch: boolean` Is this a touch device?
27
- - `contexts: string[]` Names of the active contexts, bottom to top (pending switches apply at the next fixed step)
28
- - `holders: { context: string; owner: string; pass: boolean }[]` Who holds input, bottom to top above the base context: [{ context, owner, pass }] (pass: unrelated gameplay actions still read)
26
+ - `lastDevice: "keyboard" | "pad" | "touch"` (experimental) Most recently used device: UI key hints follow it
27
+ - `touch: boolean` (experimental) Is this a touch device?
28
+ - `contexts: string[]` (experimental) Names of the active contexts, bottom to top (pending switches apply at the next fixed step)
29
+ - `holders: { context: string; owner: string; pass: boolean }[]` (experimental) Who holds input, bottom to top above the base context: [{ context, owner, pass }] (pass: unrelated gameplay actions still read). Pushes and removes count at once, before the next fixed step applies them: on a halted page a closed window is not a holder any more
29
30
  - `enabled: boolean` False while an opaque context (menu, dialogue, cutscene...) covers gameplay: no game action can be read, and cameras ignore picture/zoom
30
31
  - `axis: { x: number; y: number }` Movement direction: x positive right, y positive forward, length <= 1 (a snapshot of this step in fixed, the latest state in frame)
@@ -1,6 +1,6 @@
1
1
  # engine.interactions — interactions(opts?: InteractionsOptions)
2
2
 
3
- Interaction prompts (interactions() module)
3
+ Interaction prompts (interactions() module). Press a key near a thing. Install: engine.use(interactions()); undefined until installed. onUse returning { ok: false, code } fails the use and spends nothing
4
4
 
5
5
  - Options `InteractionsOptions`:
6
6
  - `action?: string` Default action name, default 'interact'
@@ -10,10 +10,10 @@ Interaction prompts (interactions() module)
10
10
 
11
11
  ## Methods and properties
12
12
  - `interactions.add(target: Object3D | PositionLike, opts?: InteractionOptions) → Handle` — Add an interaction: passing an object makes it follow the object, passing a position (Vector3 / [x, y, z] / { x, y, z }) makes a fixed point. Returns a handle { remove() }
13
- - `interactions.get(id: string) → any` — The interaction with this id, or null. Using one is the op: engine.ops.run('interaction.use', { id }) (no id = the one the actor would pick)
13
+ - `interactions.get(id: string) → Interaction | undefined` — The interaction with this id, or undefined. Using one is the op: engine.ops.run('interaction.use', { id }) (no id = the one the actor would pick)
14
14
  - Properties:
15
- - `promptHeight: number` How high the prompt floats (meters)
16
- - `items: any[]` All interactions in the order added (a fresh array each read; get(id) finds one without it)
15
+ - `promptHeight: number` (experimental) How high the prompt floats (meters)
16
+ - `items: Interaction[]` All interactions in the order added (a fresh array each read; get(id) finds one without it)
17
17
  - `radius: number` Default reach of add() in meters (2.5)
18
18
  - `pickMode: InteractionPick` How the one in front of the actor is chosen; can be changed at runtime
19
19
  - `current: any` The interaction the prompt shows right now (null if none)
@@ -32,4 +32,4 @@ Interaction prompts (interactions() module)
32
32
  - `hold?: number` Seconds the key must stay down before onUse runs (0 = a press). The engine counts it and interrupts it on release, leaving reach, enabled() false or locked input (interaction:hold / interaction:interrupt); the prompt gets progress 0-1. The op interaction.use itself is the completed use
33
33
  - `approach?: boolean` Walk the player there first (walkTo, stops 1.2 m away), then use it; with radius: Infinity it can be used from anywhere (point-and-click)
34
34
  - `once?: boolean` Hide the object after a use and allow no second one (onUse returning { ok: false } leaves it). Saved under id, else the object's name; development throws when it has neither
35
- - `counter?: string` Name of a HUD counter each use adds 1 to (hud.add; nothing without hud()). Saved; read the total with hud.value(name)
35
+ - `counter?: string` Name of a HUD counter each use adds 1 to (hud.bump; nothing without hud()). Saved; read the total with hud.value(name)