threedog 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
@@ -0,0 +1,199 @@
1
+ # engine — createEngine and the Engine class (core)
2
+
3
+ - `createEngine(opts: EngineOptions) → Engine` — Create an engine (core only). canvas is required; style is the style pack
4
+ - Options `EngineOptions`:
5
+ - `canvas?: HTMLCanvasElement | HTMLElement` Canvas element (required unless renderer is given), e.g. document.getElementById('view')
6
+ - `renderer?: any` A ready three.js renderer (WebGLRenderer or compatible) to use instead of creating one; canvas then defaults to renderer.domElement. The engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself. WebGL is the fully supported path; WebGPU-style renderers may not run shader patches or post effects (recipe 48)
7
+ - `style?: StyleInput` Style pack (looks only: materials, sky, lighting, post, UI look), e.g. import lowpoly from '@threedog/style-lowpoly', or a list of parts deep-merged left to right: [lowpoly, { sky: { sunSize: 600 } }]. Without one: neutral gray placeholders
8
+ - `shadows?: boolean` Real-time shadows, default true
9
+ - `shadowType?: 'basic' | 'pcf' | 'vsm'` Shadow filter: 'basic' (hard edge) / 'pcf' / 'vsm' (softest, costliest), default 'pcf'. Change later with engine.look.shadow.set({ type })
10
+ - `antialias?: boolean` MSAA anti-aliasing (kept with post effects on), default style.antialias, else on for desktop and off for low-tier devices
11
+ - `post?: Record<string, boolean>` Turn style post effects on or off by name at startup, e.g. { bloom: false }; default: each effect's own setting (costly ones off on low-tier devices)
12
+ - `pixelRatio?: number` Render resolution, default min(device pixel ratio, 1.5)
13
+ - `adaptiveResolution?: boolean` Automatically lower resolution when the frame rate is too low, default true
14
+ - `targetFps?: number` Target frame rate for automatic resolution lowering, default 55
15
+ - `ui?: Record<string, UIPartValue>` UI parts: replace or turn off any piece of screen UI (loading, toast, title, hud.marker, hud.counter, hud.bar). Default title screen is off. Example: `createEngine({ canvas, ui: { loading: { title: 'My Game' }, title: { title: 'My Game' }, toast: false } })`
16
+ - `audio?: AudioConfig` Volume of each channel, 0–1
17
+ - `fov?: number` Camera field of view (degrees), default 55
18
+ - `near?: number` Camera near clipping plane (meters), default 0.3
19
+ - `fogFar?: number` Default fog distance (meters), default 600
20
+ - `locale?: string` UI language: 'auto' (default) follows the browser (a language starting with zh gives 'zh-CN', anything else 'en'); or force 'zh-CN' / 'en' / your own
21
+ - `strings?: StringTables` Override / add UI strings: { 'zh-CN': { key: text } }
22
+ - `bindings?: Record<string, string[]>` Keys per action: changes the neutral defaults (move / confirm / cancel) and binds gameplay actions, e.g. { interact: ['KeyE'], run: ['ShiftLeft'] }; a module's define() keeps these keys
23
+ - `padBindings?: Record<string, string>` Default gamepad buttons: { jump: 'PadA' }
24
+ - `saveKey?: string` Save name prefix; must differ when several games share one site, default 'game'
25
+ - `joystick?: 'auto' | boolean` On-screen joystick: 'auto' (only on touch devices) / true / false
26
+ - `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
27
+ - `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
28
+ - `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
29
+ - `budget?: BudgetLimits` Performance budget limits, e.g. { drawCalls: 250, fps: 55 }; only the given categories are checked; off by default
30
+ - `urlState?: boolean` Set up a scenario from URL parameters (?time=18:30&weather=rain&pos=40,-20), default on only in development
31
+ - `seed?: number` Seed for engine.random; default 1 in headless mode (reproducible), the current time for live runs (different every game)
32
+ - `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 }
33
+ - `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)
34
+ - `pauseOnBlur?: boolean` Gameplay waits while the window is in the background or the tab is hidden; default true (engine.page)
35
+ - `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. Default true
36
+ - `batching?: false | BatchingOptions` Automatic instancing of repeated static models (engine.batching): false turns it off; default { minCount: 8, cell: engine.stream.cellSize }
37
+
38
+ ## engine methods
39
+ - `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()`
40
+ - `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: short list; a module id / op name: that entry expanded (null if unknown); { find }: the short list filtered. recipes/51-capability-catalog.md. Example: `engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']`
41
+ - `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
42
+ - `engine.setCamera(kind: CameraKind, opts?: object) → CameraRig` — Switch the camera at runtime (only exists with a camera module installed): 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'); });`
43
+ - `engine.use(...mods: ModuleInput[])` — Install one or more modules (in order; dependencies must be installed first)
44
+ - `engine.has(name: string) → boolean` — Whether a module is installed
45
+ - `engine.makeMaterial(purpose?: string, params?: { color?, … }) → Material` — Material by role from this engine's style pack: engine.makeMaterial('prop', { color: 0x8a5a36 })
46
+ - `engine.setGround(g: Partial<Ground>)` — Set the ground (called by the terrain and level modules); missing parts fall back to flat ground
47
+ - `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)
48
+ - `engine.slope(x: number, z: number) → number` / `slope(at: PositionLike) → number` — Slope at (x, z); a position or object also works
49
+ - `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 })
50
+ - `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
51
+ - `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
52
+ - `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
53
+ - `engine.t(key: string, params?: Record<string, any>) → string` — Get UI text (i18n)
54
+ - `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' });`
55
+ - `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'`
56
+ - `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)
57
+ - `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
58
+ - `engine.onFixed(fn: (dt: number) => void) → 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). Returns a handle { remove() }
59
+ - `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() }
60
+ - `engine.setPixelRatio(p: number)` — Render resolution
61
+ - `engine.setShadows(on: boolean)` — Shadow toggle
62
+ - `engine.setFogFar(d: number)` — Fog distance (meters), also adjusts the camera far plane
63
+ - `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.spawn(name: string, at: any, fields?: { id?, rot?, scale?, y?, items?, … }) → import('./generated/modules/world…` — New runtime instance of a content template (inside an op or fixed step), saved whole; returns the world record (kind = template name). Needs content(). e.g. engine.spawn('chest', { x: 10, z: 4 }, { opened: true })
66
+ - `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
67
+ - `engine.defineState(name: string, params: StateParams)` — Name a group of scenario parameters, then use applyState({ state: name }) or URL ?state=name
68
+ - `engine.start() → Promise<this>` — Start: initialize modules, preload assets, wait for the world to be ready
69
+ - `engine.pause(owner?: string | { owner?, kind? }, opts?: { kind?: 'test' }) → ChainedHandle` — Pause the real-time loop: the picture stops and even rendering stops, only step() advances (for tests and screenshots). Use freeze() for a game menu pause
70
+ - `engine.resume(owner?: string | { owner?: string })` — Resume the real-time loop (only this owner's pause)
71
+ - `engine.nextFixed(fn: () => T) → Promise<T>` — Run fn at the start of the next fixed step (via commits); a Promise of fn's value
72
+ - `engine.freeze(owner?: string | { owner?, kind? }, opts?: { kind?: 'title' }) → ChainedHandle` — Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, the game clock and engine.elapsed all 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'
73
+ - `engine.unfreeze(owner?: string | { owner?: string })` — Release the freeze of owner (gameplay resumes only when all freezers are released)
74
+ - `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; when timeScale is not 1, game seconds clock.now and sky time of day run faster or slower than it; 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
75
+ - `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; engine.elapsed does not move. 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' })`
76
+ - `engine.checkSkip(seconds: number, opts?: { ignore?: string[] }) → Promise<{ ok: boolean; diffs: { p…` — 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);`
77
+ - `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);`
78
+ - `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, one line per module with its key counts), 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 })`
79
+ - `engine.explain(q: { op, args?, actor? } | Record<string, any>) → { ok, reason?, 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)'`
80
+ - `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
81
+ - `engine.dispose()` — 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)
82
+ - `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)
83
+
84
+ ## engine properties (module properties are on each module page)
85
+ - `THREE: typeof import('three')` three.js (a game can also import { THREE } from 'threedog' directly)
86
+ - `style: Style` Style pack
87
+ - `renderer: import('three').WebGLRenderer` three.js renderer
88
+ - `tier: 'low' | 'high'` Device tier: 'low' (phones, integrated graphics) / 'high'
89
+ - `scene: import('three').Scene` three.js scene
90
+ - `lights: { sun, hemi }` Default lights (neutral without sky; the sky module drives these same two). Hide or retune them for your own lighting: `engine.lights.sun.visible = false`
91
+ - `camera: import('three').PerspectiveCamera` three.js perspective camera
92
+ - `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
93
+ - `shadows: boolean` Whether shadows are on
94
+ - `shadowType: 'basic' | 'pcf' | 'vsm'` Shadow filter in use; change it with look.shadow.set({ type })
95
+ - `ground: Ground` Current ground
96
+ - `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
97
+ - `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
98
+ - `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
99
+ - `ready: boolean` True once start() completes and the loading screen is gone (every "is it ready" in the engine is such a boolean property)
100
+ - `disposed: boolean` True after dispose()
101
+ - `moduleOrder: string[]` Execution order of module hooks (module names, first -> last), for debugging "who runs before whom"
102
+ - `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
103
+ - `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
104
+ - `disabledModules: Set<string>` Names of presentation modules disabled after an error (modules with presentation: true)
105
+ - `signal: AbortSignal` The engine's cancel signal (AbortSignal): for DOM listeners write addEventListener(type, fn, { signal: engine.signal }), removed automatically on dispose()
106
+ - `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()
107
+ - `fogFar: number` Base fog distance (meters)
108
+ - `modules: Map<string, ModuleDef>` Installed modules: name -> module definition
109
+ - `waterBodies: WaterBody[]` Standalone water bodies (lakes, ponds)
110
+ - `events: Events` Event bus
111
+ - `i18n: I18n` i18n
112
+ - `saves: Saves` Saves
113
+ - `session: Session` New game / continue / back to title, each from a clean slate (engine.session.newGame(), load(slot), quit())
114
+ - `page: Page` Window focus, tab visibility, mouse lock, WebGL context: the one place that listens to them
115
+ - `input: Input` Input
116
+ - `audio: Audio` Audio
117
+ - `assets: Assets` Assets
118
+ - `loading: Loading` Observable loading: every asset load, module init / isReady and track() step as a task (phase, error, source manifest)
119
+ - `post: PostFX` Post-processing: named effects in slots (add / get / enable / list)
120
+ - `look: Look` Every look in one place: engine.look.<part>.set / patch / replace (recipes/52-look.md)
121
+ - `ui: UIParts` UI parts: every piece of screen UI is replaceable or off (see recipes/26-ui-parts.md)
122
+ - `adaptive: AdaptiveState` Automatic resolution state
123
+ - `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.
124
+ - `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
125
+ - `cameraOverride: CameraOverride | null` The camera holder in charge (latest engine.takeCamera claim), null when nobody holds it. Assigning { owner } / null is the old alias of takeCamera
126
+ - `runState: RunState` Why the page is (not) advancing; the dev bridge and MCP tools copy it as-is
127
+ - `decoders: string` Draco/KTX2 decoder directory
128
+ - `clock: Clock` Game clock: game seconds now, after / every (clock-time / season timers are on engine.sky)
129
+ - `vars: Vars` Story flags and counters (autosaved)
130
+ - `budget: Budget` Performance budget (off by default)
131
+ - `rays: Rays` Ray registry (what engine.raycast hits)
132
+ - `jobs: Jobs` Frame-spread job scheduler
133
+ - `commits: Commits` Background results that affect gameplay take effect on a fixed tick (chunk collision, spread jobs with apply...), see Commits
134
+ - `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
135
+ - `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
136
+ - `views: Views` Named fixed camera views for repeatable screenshots: define / show / release (recipes/46-blender-art-route.md)
137
+ - `tick: number` Fixed-step count (the gameplay timeline: does not advance while frozen; commits due times, event history and the operation log use it)
138
+ - `random: Random` Seeded random numbers (use for gameplay randomness: reproducible and saved with the game)
139
+ - `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)
140
+ - `batching: Batching` Automatic batching: the same static model placed many times in a cell is drawn as one InstancedMesh (createEngine({ batching }))
141
+ - `startup: StartupReport | null` Startup timing report (null until start() completes)
142
+ - `elapsed: number` Run seconds: unaffected by the sky time scale, does not advance while frozen or paused; for presentation animation (swaying, floating). The other two "times": game seconds engine.clock.now (= fixed-step seconds x clock.timeScale, saved); sky time of day engine.sky.timeOfDay (0–1, one day = dayLength game seconds)
143
+ - `uniforms: EngineUniforms` This engine's shader uniforms, read by the built-in effects (wind, clouds, season, water, sky, rain). Share these objects in your own ShaderMaterial or patch instead of making your own uTime. Weather and sky write them; uTime follows engine.elapsed. Example: `new THREE.ShaderMaterial({ uniforms: { uTime: engine.uniforms.uTime }, vertexShader, fragmentShader });`
144
+ - `waterLevel: number` Global water level (meters); -Infinity when there is no water
145
+ - `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
146
+ - `exposureDriver: ((sky: any) => number) | null` Exposure per frame from style.exposure / look.tone keyframes or function, null for a plain number; the sky module calls it with engine.sky
147
+ - `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)
148
+ - `headless: boolean` Whether in headless mode (createEngine({ headless: true }))
149
+ - `paused: boolean` Whether paused (headless mode is paused by default, only step() advances)
150
+ - `fps: number` Smoothed frame rate
151
+ - `openWindows: Set<string>` Ids of the open windows
152
+ - `frozen: boolean` Is anyone freezing gameplay?
153
+ - `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).
154
+ - `inspect: { scene }` 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 reason 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, reason: 'noMoney', why: 'Not enough gold' }] }`
155
+
156
+ ## Module definition (engine.use(myModule()))
157
+ - **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.
158
+ - `name: string` Module name; after install, access the object returned by install through engine[name]
159
+ - `label?: string` Display name (used by the loading screen)
160
+ - `requires?: string[]` Names of other modules this depends on; they must be installed first (an error is thrown if not)
161
+ - `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
162
+ - `stage?: 'control' | 'world' | 'environment' | …` Hook stages (first -> last): 'control' timeline, camera -> 'world' terrain, level -> 'environment' weather, sky, water -> 'gameplay' interactions, dialogue, triggers, entities -> 'presentation' particles, settings, objective markers -> 'late' (default) -> 'audio' music. Within a stage use before / after, then install order
163
+ - `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)
164
+ - `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)
165
+ - `presentation?: boolean` Presentation modules (particles, sound effects, HLOD; gameplay is unaffected without them): when a hook errors only this module is disabled and the game continues. Without it the module counts as gameplay: during development / testing an error freezes gameplay and is recorded in engine.error (error severity levels)
166
+ - `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 (presentation: disabled and the game carries on; gameplay: error tiers) and start() goes on. Example: `engine.use({ name: 'saveSlots', critical: true, async init(e) { await loadSlots(); } })`
167
+ - `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: ...' }) }
168
+ - `install(e: Engine) → Api` — Install: create and return the object the game uses (engine.name)
169
+ - `init(e: Engine) → void | Promise<void>` — Called at startup (download things, wait for assets); may be async
170
+ - `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
172
+ - `fixed(dt: number, e: Engine)` — Fixed step (60 times per second); dt is in seconds
173
+ - `frame(dt: number, e: Engine)` — Once per frame; dt is in seconds
174
+ - `afterRender(dt: number, e: Engine)` — After rendering
175
+ - `skip(dt: number, e: Engine, done: boolean)` — engine.skip moved time without stepping: advance your own time by dt fixed seconds (game seconds = dt x clock.timeScale), no per-step work. Called once per skip segment (segments end at timers and sky clock marks); done is true on the last one: do expensive catch-up only then. Only for modules that keep time themselves (sky, world); modules that compare against clock.now need nothing
176
+ - `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
+ - `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 | Promise<void>` — Optional: handle the keys of engine.applyState that this module owns (e.g. sky handles time)
179
+ - `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
+
181
+ ## Data structures
182
+ - **Handle** Handle: returned by every "add / register / listen / attach" API (events.on, onFrame, clock.after, collision.addBox, interactions.add, rays.addStatic…), call remove() to undo that registration (removes the listener, collider, timer…; safe to call repeatedly). Some handles carry extra fields (such as setTarget on hud.marker)
183
+ - `remove()`
184
+ - **StateParams** Scenario parameters (can also go in the URL: ?time=18:30&weather=rain&pos=40,-20&cutscene=skip&state=name)
185
+ - `state?: string` A group of parameters named with defineState
186
+ - `time?: string | number` Time of day: 'HH:MM' or 0–1
187
+ - `season?: string` Season name from sky({ seasons }): jumps sky.day to that season's first day (time of day kept)
188
+ - `weather?: string` Weather name
189
+ - `pos?: string | PositionLike` Player position: 'x,z' or a position (sets the focus when there is no player)
190
+ - `save?: string` Which save slot to load
191
+ - `wait?: number` How many seconds to advance (fixed-step seconds, not multiplied by clock.timeScale)
192
+ - `cutscene?: 'skip' | 'keep'` Opening cutscene: 'skip' skips it / 'keep' plays it as usual
193
+ - **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
194
+ - `totalMs: number`
195
+ - `startMs: number`
196
+ - `preloadMs: number`
197
+ - `streamMs: number | null`
198
+ - `compileMs: number`
199
+ - `modules: Record<string, { init?: number; ready?: number }>`
@@ -0,0 +1,61 @@
1
+ # engine.entities — entities()
2
+
3
+ Entities: single stateful, saved objects such as saplings, campfires and chests; the data is a record of engine.world, the model is built only when nearby (entities() module)
4
+
5
+
6
+ ## Methods and properties
7
+ - `entities.define(type: string, def: EntityDef<S>)` — Define an entity type
8
+ - `entities.spawn(type: string, data?: EntitySpawnData) → Entity | null` — Spawn an entity (returns null if the type is not defined)
9
+ - `entities.nearest(position: PositionLike, opts?: { radius?, type? }) → Entity | null` — The entity nearest to position within radius meters (default 3) (type restricts to one type)
10
+ - `entities.clear()` — Delete all entities
11
+ - `entities.setStage(ent: Entity, i: number)` — Jump straight to a growth stage
12
+ - Also: `entities.get(id: string) → Entity | null`, `entities.byType(type: string) → Entity[]`, `entities.list() → Entity[]`, `entities.remove(id: string) → boolean`
13
+ - Properties:
14
+ - `types: Map<string, EntityDef>` Type definitions
15
+ - `now: number` Game seconds (= engine.clock.now)
16
+
17
+ ## Data structures
18
+ - **EntityDef** Entity type definition: engine.entities.define('sapling', {...})
19
+ - `create: (engine: Engine, ent: Entity<S>) => Object3D` Create the model (required), returns a THREE.Object3D
20
+ - `state?: S` Default state (merged with the state given at spawn)
21
+ - `stages?: EntityStage[]` Growth stages
22
+ - `canGrow?: (ent: Entity<S>, engine: Engine) => boolean` Growth stops when this returns false
23
+ - `update?: (dt: number, ent: Entity<S>, engine: Engine) => void` Called every fixed step (dt in seconds); runs only near the player, far away only growth is caught up
24
+ - `interact?: EntityInteract` Interaction
25
+ - `collider?: number` Circular collision radius (meters, needs the collision module; follows the model, exists only near the player)
26
+ - `colliderHeight?: number` Collision height (meters), default 3
27
+ - `dispose?: (ent: Entity<S>, engine: Engine) => void` Cleanup when the model is torn down (called both when walking away and on deletion; don't clear data while the data still exists)
28
+ - `save?: boolean` false = not saved (temporary things, cleared on load), default true
29
+ - **EntityStage** Growth stage
30
+ - `name: string` Stage name, e.g. 'seed'
31
+ - `duration?: number` How many game seconds to stay in this stage (leave out on the last one = stay here forever)
32
+ - `scale?: number` Model size multiplier
33
+ - `model?: (engine: Engine, ent: Entity) => Object3D` Swap the model
34
+ - **EntityInteract** Entity interaction settings (needs the interactions module)
35
+ - `label?: string | ((ent: Entity, engine: Engine) => string)` Prompt text: an i18n key, plain text, or a function ent => text
36
+ - `action?: string` Interaction action name, default 'interact'
37
+ - `radius?: number` How close you must be to interact (meters), default 2.5
38
+ - `height?: number` How high the prompt floats (meters)
39
+ - `enabled?: (ent: Entity, engine: Engine) => boolean` Whether it can be interacted with
40
+ - `onUse?: (ent: Entity, engine: Engine) => void` When the interact key is pressed
41
+ - **EntitySpawnData** Parameters of spawn()
42
+ - `id?: string` Specify the id (generated automatically if omitted)
43
+ - `position?: PositionLike` Position: Vector3 / object / [x, y, z] / { x, z } ({ x, z } without y snaps to the ground), default origin
44
+ - `rotation?: number` Heading (radians)
45
+ - `state?: Record<string, any>` Initial state (merged onto the default state)
46
+ - `extra?: Record<string, any>` Extra data (ent.data, saved)
47
+ - **Entity** An entity: x / y / z / rotation / state / data read engine.world data directly (kind is 'entity:<type>'); object / visual exist only near the player
48
+ - `id: string`
49
+ - `type: string`
50
+ - `def: EntityDef<S>`
51
+ - `x: number` Position (meters)
52
+ - `z: number`
53
+ - `y: number`
54
+ - `rotation: number`
55
+ - `state: S & { stage?: number; stageAt?: number }` State (stage is the current stage index, stageAt the time it was entered); change values with ent.set() so that events fire
56
+ - `object: Object3D | null` Root node (heading and interactions hang on it); null when there is no model far away, built the frame after spawn
57
+ - `visual: Object3D | null` Model (a child of the root node)
58
+ - `data: Record<string, any>` Extra data
59
+ - `stageName: string | null` Current stage name
60
+ - `set(key: string, value: any)` — Change one state value (emits the entity:state event)
61
+ - `remove() → boolean` — Delete this entity
@@ -0,0 +1,95 @@
1
+ # engine.events (Events) — engine.events: the event bus; modules "shout" and whoever cares listens
2
+
3
+ - `events.traceFocus(id: string | null)` — Verbose trace for one object (needs traceSize > 0): perception queries and state checks that name `obj` === id are recorded in full (misses too), the rest of the world only records what changed. null clears. For "why did this guard not see me": traceFocus('guard-1'), play, then read trace('sight'). Example: `engine.events.traceSize = 300; engine.events.traceFocus('guard-1');`
4
+ - `events.note(name: string, info?: { code?, obj?, data?, verbose?, parent? }) → string | null` — Add one entry to the cause trace (no-op while traceSize is 0; check `events.traceSize > 0` first to skip building info). Returns its parent id (`ev:<n>`) to pass as info.parent of follow-ups, or null. info: code (failure code), obj (world record id it is about), data (small plain values), verbose (true = only recorded while traceFocus(obj)), parent (default: the event or op running now). The engine notes failed ops (`op:<name>`), collision.lineClear (`sight`) and NPC state changes (`npc:state`); a game's behaviors can note their own, e.g. 'npc:mode' patrol -> investigate. Example: `if (e.events.traceSize > 0) e.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } });`
5
+ - `events.trace(name?: string) → { id, tick, name, parent, chain, code?, … }[]` — Cause chains (needs traceSize > 0): each emitted event is recorded with parent = the event (`ev:<id>`) or op (`op:<name>#<seq>`) whose handler emitted it, null when it came from outside any. chain lists the causes from the nearest to the root (as far as the ring still holds). For "why did this fire". Example: `engine.events.traceSize = 200; engine.ops.run('shop.buy', { item: 'bread' }); engine.events.trace('item:add').at(-1).chain; // ['op:shop.buy#12']`
6
+ - `events.recent(name?: string) → { tick, name, data }[]` — Recent events (old -> new); with name, only that kind: { tick = which fixed step, name, data = summary (simple values only; objects become '…') }. For "why did it not fire", first check whether it happened at all. Example: `engine.events.recent('item:add');`
7
+ - `events.on(name: K, fn: (args) => void) → Handle` — Listen to an event; returns a handle { remove() }. Example: `const h = engine.events.on('item:add', ({ id, count }) => console.log(id, count)); h.remove();`
8
+ - `events.once(name: K, fn: (args) => void) → Handle` — Listen once; returns a handle { remove() } (can be removed before it fires)
9
+ - `events.emit(name: K, ...args: EventArgs<K & string>)` — Emit an event. Example: `engine.events.emit('item:add', { id: 'fish', count: 1 });`
10
+ - Properties:
11
+ - `historySize: number` How many history entries to keep, default 200; 0 records nothing
12
+ - `traceSize: number` Cause trace ring size, default 0 = off (no cost). Set e.g. 200 in dev to record which event or op caused which follow-up event; read with trace()
13
+
14
+ ## Event table (engine.events.on(name, (args…) => …), the [] lists the callback arguments)
15
+ - `engine:ready` [] Loading finished; the world is playable
16
+ - `audio:ready` [] Audio can play (after the player's first click / key press)
17
+ - `i18n:change` [locale: string] UI language changed; the argument is the new language
18
+ - `input:rebind` [{ action: string | null; keys: string[] | null }] Key bindings changed; action null means everything was reset to defaults
19
+ - `input:context` [{ stack: string[] }]
20
+ - `save:written` [slot: string] Save written to disk; the argument is the slot name (not emitted when the write fails, a toast is shown instead)
21
+ - `save:imported` [slot: string] Restore from a save file (saves.importFile) finished; the argument is the slot name. Attachments in the file (such as photos) are written to storage too
22
+ - `save:loaded` [slot: string] A save was loaded onto the running playthrough (saves.load / session.load); the argument is the slot name
23
+ - `ui:open` [id: string] A window was opened (the argument is the window id, e.g. 'inventory')
24
+ - `ui:close` [id: string] A window was closed
25
+ - `settings:shadows` [on: boolean] Shadows were toggled
26
+ - `settings:change` [values: Record<string, any>] A value in the settings menu changed (the argument is all setting values)
27
+ - `water:add` [body: WaterBody] A water body was added
28
+ - `water:remove` [body: WaterBody] A water body was removed
29
+ - `day:start` [day: number] A new day (the argument is the day number, starting at 1; needs the sky module)
30
+ - `season:change` [season: string] Season changed (the argument is the season name, e.g. 'autumn')
31
+ - `time:skip` [{ seconds: number }] engine.skip jumped game time forward (seconds = game seconds skipped); timers and world catch-up already ran
32
+ - `weather:lightning` [] Lightning strike (weather module)
33
+ - `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)
34
+ - `camera:shot` [CameraShotEvent] The fixed-shot camera switched shots
35
+ - `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
36
+ - `character:jump` [{ character: Character }] A character jumped
37
+ - `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)
38
+ - `character:land` [{ character: Character; impact: number }] A character landed; impact is the landing speed (m/s), the larger the harder the fall
39
+ - `dialogue:start` [speaker: string] Dialogue started; the argument is the dialogue script name
40
+ - `dialogue:line` [{ script: string; node: string; speaker: string; text: string; data:… A dialogue line started (after its do ran): data is the node's own fields (portrait, voice...), {} when none. Use it for voice, portraits, camera shots without replacing the UI part
41
+ - `dialogue:end` [speaker: string] Dialogue ended; the argument is the dialogue script name
42
+ - `item:add` [ItemEvent] An item was added to the inventory
43
+ - `item:remove` [ItemEvent] An item was removed from the inventory
44
+ - `container:add` [ContainerEvent] An item was added to a non-player container (chest, corpse...); container is the container id
45
+ - `container:remove` [ContainerEvent] An item was removed from a non-player container
46
+ - `item:pickup` [PickupEvent] An item on the ground was picked up
47
+ - `item:use` [ItemUseEvent] An item was used through the inventory.use op (after use ran)
48
+ - `quest:start` [{ id: string }] A quest started
49
+ - `quest:step` [{ id: string; step: number }] A quest moved to the next step; step is the new step index (starting at 0)
50
+ - `quest:done` [{ id: string }] A quest completed
51
+ - `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)
52
+ - `quest:fail` [{ id: string }] A quest failed (its fail condition held); quests.start(id) may begin it again
53
+ - `photo:taken` [PhotoShot] A photo was taken
54
+ - `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)
55
+ - `trigger:enter` [TriggerEvent] Entered a trigger zone
56
+ - `trigger:exit` [TriggerEvent] Left a trigger zone
57
+ - `level:loaded` [LevelLoadedEvent] Level finished loading
58
+ - `timeline:start` [{ id: number }] A cutscene started
59
+ - `timeline:end` [{ id: number; skipped: boolean }] A cutscene ended; skipped tells whether it was skipped
60
+ - `entity:spawn` [Entity] An entity was spawned
61
+ - `entity:remove` [Entity] An entity was removed
62
+ - `entity:state` [EntityStateEvent] A state value of an entity changed
63
+ - `entity:stage` [EntityStageEvent] An entity entered a new growth stage
64
+ - `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
65
+ - `terrain:void` [{ who: any; position: { x: number; y: number; z: number } }] terrain({ shape }): the player or a moving rigid body dropped below engine.terrain.voidY (once per fall). The engine does not respawn: the game decides
66
+ - `vegetation:remove` [VegetationRemoveEvent] A vegetation instance was chopped / removed
67
+ - `vegetation:restore` [VegetationRemoveEvent] A vegetation instance was restored
68
+ - `music:change` [MusicChangeEvent] Background music changed track (null means silence)
69
+ - `music:stinger` [{ name: string }] A stinger was played
70
+ - `state:applied` [StateParams] Scenario parameters were applied (URL parameters or engine.applyState)
71
+ - `anim:end` [{ root: Object3D; state: string }] A one-shot action of the animation state machine finished
72
+ - `world:add` [{ id: string; kind: string }] A record was added to world
73
+ - `world:change` [{ id: string; kind: string; keys: string[] }] world.set changed fields (keys lists which)
74
+ - `world:remove` [{ id: string; kind: string }] A record was removed from world
75
+ - `world:load` [{ count: number }] world finished loading a save (the data is now the save's; caches holding a rec object should refresh on this, count is the record count after loading)
76
+ - `net:join` [{ peer: number; actor: string }] Host (net): a peer connected; actor is its world record / container id
77
+ - `net:leave` [{ peer: number; actor: string }] Host (net): a peer disconnected (its bag stays; a reconnect with its key gets the same actor)
78
+ - `net:open` [{}] Client (net): connected to the host (the first snapshot follows)
79
+ - `net:close` [{}] Client (net): connection lost
80
+ - `net:sync` [{ tick: number; full: boolean }] Client (net): host state applied (full: a whole snapshot, else a diff); redraw UI from state here
81
+ - `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
82
+ - `engine:error` [EngineError] A gameplay error in development / testing; gameplay is frozen (error severity levels, see engine.error)
83
+ - `module:disabled` [{ name: string; message: string }] A presentation module errored and was disabled (the game continues)
84
+ - `vehicle:enter` [{ character: Character; vehicle: Vehicle }] A character boarded a vehicle
85
+ - `vehicle:exit` [{ character: Character; vehicle: Vehicle }] A character exited a vehicle
86
+ - `flow:change` [{ from: string; to: string }] Game flow state changed
87
+ - `flow:transition` [{ phase: 'start' | 'end' }] Scene transition: phase 'start' begins fading to black, 'end' finishes fading back in
88
+ - `session:end` [] A playthrough ends (engine.session.newGame / load / quit), before the reset
89
+ - `session:start` [{ kind: 'new' | 'load'; slot?: string }] A playthrough started from a clean slate: kind 'new' (newGame) or 'load' (session.load, with the slot)
90
+ - `page:blur` [{ focused: boolean; visible: boolean }] The page went away: the window lost focus or the tab was hidden (engine.page)
91
+ - `page:focus` [{ focused: boolean; visible: boolean }] The page came back: focused and visible again
92
+ - `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
93
+ - `page:contextlost` [] The WebGL context was lost: gameplay waits and the player sees a message
94
+ - `page:contextrestored` [] The WebGL context is back: gameplay resumes
95
+ - Other names work too (the game's own events, such as 'door:open'), their arguments are just not checked
@@ -0,0 +1,27 @@
1
+ # engine.flow — flow(opts?: FlowOptions)
2
+
3
+ Game flow and scene transitions (flow() module)
4
+
5
+ - Options `FlowOptions`:
6
+ - `start?: string` Starting state, default 'playing'; other states are entered on engine:ready (so you can define after use())
7
+
8
+ ## Methods and properties
9
+ - `flow.define(name: string, def: FlowStateDef)` — Define a state (built-in 'playing', 'paused')
10
+ - `flow.go(name: string)` — Switch state
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
+ - Properties:
13
+ - `state: string` Current state name
14
+ - `transitioning: boolean` A scene transition is in progress
15
+
16
+ ## Data structures
17
+ - **FlowStateDef** A flow state (title, playing, paused, game over...)
18
+ - `enter?: (e: Engine, from: string) => void` Called on entering
19
+ - `exit?: (e: Engine, to: string) => void` Called on leaving
20
+ - `freeze?: boolean` Freeze gameplay (engine.freeze, the picture keeps running), default false
21
+ - `lockInput?: boolean` Lock game input, default false
22
+ - `music?: string | null` Music played on entering (track name, null for silence)
23
+ - **FlowTransitionOptions** Parameters of flow.transition()
24
+ - `fade?: number` Fade-to-black / fade-in seconds, default 0.5
25
+ - `lockInput?: boolean` Lock input during the switch, default true
26
+ - `music?: 'fade' | 'keep'` Music: 'fade' fades out (default) / 'keep' leaves it alone
27
+ - `autosave?: 'auto' | false` Save to slot 'auto' before the switch: 'auto' / false (default: a game with its own save points keeps its slots)
@@ -0,0 +1,11 @@
1
+ # engine.grids — grids()
2
+
3
+ (experimental) Placement grids: world <-> cell, occupancy derived from world records, per-cell layers, placement preview (grids() module)
4
+
5
+
6
+ ## Methods and properties
7
+ - `grids.add(name: string, opts?: { cell?, origin?, size?, zone?, flat?, layers? }) → 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); layers: authored cells { soil: [[i, j, { tilled: 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
9
+ - `grids.list() → Grid[]` — All grids (a new array)
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); ground: allowed engine.groundType values; layer: { layerName: field } that must be truthy on every cell (reason 'not' + Field, e.g. notTilled); flat: max height difference (overrides the grid's); fields: copied into the record; can(e, { grid, cell, rotation, cells }): your own rule. Example: `engine.grids.define('crop', { size: [1, 1], layer: { soil: 'tilled' }, fields: { plantedAt: 0 } })`
11
+ - `grids.preview(opts: { grid, item, from?, rotate?, rotateKeys?, rotation?, … }) → { cell, rotation, ok, reason, 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, or pass rotateKeys / ...presets.keys.gridRotate, the engine binds no key itself), light when can() passes, dark otherwise (neutral tool colors; style.grid.ok / bad override them). look: false = no visual; (engine) => ({ update(view), hide(), dispose() }) = your own. place() runs grid.place with what is shown. Example: `engine.input.define('place', ['Mouse0']); // the game's own binding const pv = engine.grids.preview({ grid: 'farm', item: 'crop', ...presets.keys.gridRotate }); engine.onFrame(() => { if (engine.input.pressed('place')) { const r = pv.place(); if (!r.ok) toast(engine, engine.t('grid.' + r.reason)); } });`
@@ -0,0 +1,16 @@
1
+ # engine.ground (Ground) — Ground: whoever provides the ground height is the "terrain" (terrain module, level module, or the default flat y=0)
2
+
3
+ - `ground.height(x: number, z: number, refY?: number) → number` — Ground height (meters) at (x, z). For multi-layer ground (bridges, caves) pass refY: takes the highest layer not above refY + one step (0.45 m); without it the highest layer is used. Single-layer ground ignores refY
4
+ - `ground.slope(x: number, z: number) → 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')
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
+ - `ground.voidY() → number` — Height below which something has fallen out of the world (terrain:void): engine.terrain.voidY with terrain({ shape }), else -Infinity
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 fogFar)
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
14
+ - Properties:
15
+ - `waterLevel: number` Global water level (meters); -Infinity when there is no water
16
+ - `chunkSize?: number` Optional: chunk edge length (meters)
@@ -0,0 +1,34 @@
1
+ # engine.hlod — hlod(opts?: HlodOptions)
2
+
3
+ (experimental) HLOD, merged distant geometry (hlod() module)
4
+
5
+ - Options `HlodOptions`:
6
+ - `level?: boolean` Handle levels automatically (adds the level on level:loaded), default true
7
+ - `cell?: number` Merge cell edge length (meters), default 64
8
+ - `near?: number` Beyond this distance (meters) the merged proxy is shown, default 160
9
+ - `castShadow?: boolean` Proxy casts shadows, default false
10
+ - `include?: (mesh: Object3D) => boolean` Which meshes to merge (return false to skip)
11
+
12
+ ## Methods and properties
13
+ - `hlod.add(target: Object3D | Object3D[], opts?: HlodAddOptions) → HlodHandle` — Register a group of objects (a root or an array), merged into proxies by cell
14
+ - Properties:
15
+ - `cells: HlodCell[]` All merged cells
16
+
17
+ ## Data structures
18
+ - **HlodAddOptions** Parameters of hlod.add()
19
+ - `cell?: number`
20
+ - `near?: number`
21
+ - `castShadow?: boolean`
22
+ - `include?: (mesh: Object3D) => boolean` Which meshes to merge (return false to skip)
23
+ - **HlodCell** One merged cell: proxy is the merged proxy meshes, originals the original objects
24
+ - `key: string` Cell key 'x,z'
25
+ - `proxy: Object3D[]` Merged proxy meshes (one per material)
26
+ - `originals: Object3D[]` Originals
27
+ - `center: Vector3` Average center of the originals (for distance)
28
+ - `far: boolean` The proxy is currently shown
29
+ - **HlodHandle** Handle returned by hlod.add()
30
+ - `cells: HlodCell[]`
31
+ - `near: number` Beyond this distance (meters) the proxy is shown
32
+ - `ready: boolean` Are all proxies merged (done over several frames)
33
+ - `whenReady: Promise<HlodHandle>` Promise that resolves when merging is done: await h.whenReady
34
+ - `remove()` — Cancel: restore the originals, free the proxies
@@ -0,0 +1,31 @@
1
+ # engine.hud — hud(opts?: HudOptions)
2
+
3
+ Objective markers, counters, progress bars (hud() module)
4
+
5
+ - Options `HudOptions`:
6
+ - `questMarkers?: boolean` Show a marker automatically when the current quest step has a target, default true
7
+
8
+ ## Methods and properties
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? })` — Counter (calling again with the same id = update; calling every frame is fine), e.g. counter('fish', { label: '鱼', value: 2, max: 5 })
11
+ - `hud.bar(id: string, opts: { value, max?, label? })` — 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
12
+ - `hud.remove(id: string)` — Delete a counter or progress bar
13
+ - Properties:
14
+ - `markers: HudMarker[]` All markers
15
+
16
+ ## Data structures
17
+ - **HudMarkerOptions** Objective marker parameters
18
+ - `label?: string | (() => string)` Text
19
+ - `icon?: string` Icon (text or image URL)
20
+ - `offscreen?: 'arrow' | 'hide'` When the target is off screen: 'arrow' an arrow at the screen edge (default) / 'hide' not shown
21
+ - `distance?: boolean` Show the distance, default true
22
+ - `height?: number` How high the marker floats above the target (meters)
23
+ - **HudMarker** Marker returned by hud.marker()
24
+ - `target: HudTarget`
25
+ - `dist: number | null` Distance in meters from the player (from the focus when there is no player)
26
+ - `visible: boolean` Shown this frame (false when the target is missing, off screen with offscreen 'hide', or before the first frame)
27
+ - `part: import('./core').UIPart | null` The UI part drawing it (null when hud.marker is turned off); the default part has .el
28
+ - `onScreen: boolean` On screen (otherwise an edge arrow is shown or it is hidden)
29
+ - `set(opts: HudMarkerOptions)` — Change parameters
30
+ - `setTarget(target: HudTarget)` — Change the target (the marker itself is not rebuilt)
31
+ - `remove()` — Delete
@@ -0,0 +1,10 @@
1
+ # engine.i18n (I18n) — engine.i18n: string tables; t(key, params) fetches text and replaces {name} with params
2
+
3
+ - `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.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
+ - Properties:
8
+ - `locale: any` Current language, e.g. 'zh-CN'
9
+ - `fallback: string` Language used when a key is missing in the current one (default 'en')
10
+ - `languages: string[]` All available languages
@@ -0,0 +1,24 @@
1
+ # engine.input (Input) — Input: read by "action", not by "key"
2
+
3
+ - `input.define(action: string, keys: string | string[], labelKey?: string, opts?: { pad?, context? })` — Register an action. keys is a key name or array (gamepad keys such as 'PadY' can go in directly); labelKey is the display name (a string-table key or text). opts.pad: the default gamepad key for this action (gameplay-specific actions get it from the registering module; createEngine({ padBindings }) takes precedence). If the action exists, the later definition overrides (warns once in dev when the keys differ); keys the player rebound in settings are kept. Example: `engine.input.define('openMap', 'KeyM', 'input.openMap', { pad: 'PadY' });`
4
+ - `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.simulate(action: any, 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. Example: `engine.input.simulate('jump'); engine.step(1 / 60); engine.input.simulate('jump', false)`
6
+ - `input.rebind(action: string, keys: string | string[])` — Rebind a key
7
+ - `input.keysOf(action: string) → string[]` — All keys bound to an action
8
+ - `input.label(action: string) → string` — Key name shown in the UI, e.g. "E"
9
+ - `input.down(action: string) → boolean` — Held (a snapshot of this step in fixed, the latest state in frame)
10
+ - `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(); });`
11
+ - `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);`
12
+ - `input.pressedRaw(action: string) → boolean` — Just pressed, ignoring input contexts (for menus and dialogue themselves, which run while a context blocks the game)
13
+ - `input.push(name: string, opts?: { pass?: boolean }) → { 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 define(..., { 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();`
14
+ - Properties:
15
+ - `look: { dx: number; dy: number; zoom: number }` This frame's look-drag amount (pixels) and wheel notches
16
+ - `pointer: Pointer` Mouse/touch pointer
17
+ - `stick: { x: number; y: number }` On-screen stick (touch)
18
+ - `autopilot: Autopilot | null` Auto movement (stress tests, test scripts)
19
+ - `actions: Map<string, { keys: string[]; labelKey: string }>` action name -> { keys = key list, labelKey = string-table key }
20
+ - `lastDevice: "keyboard" | "pad" | "touch"` Most recently used device: UI key hints follow it
21
+ - `touch: boolean` Is this a touch device?
22
+ - `contexts: string[]` Names of the active contexts, bottom to top (pending switches apply at the next fixed step)
23
+ - `enabled: boolean` False while an opaque context (menu, dialogue, cutscene...) covers gameplay: no game action can be read, and cameras ignore look/zoom
24
+ - `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)
@@ -0,0 +1,31 @@
1
+ # engine.interactions — interactions(opts?: InteractionsOptions)
2
+
3
+ Interaction prompts (interactions() module)
4
+
5
+ - Options `InteractionsOptions`:
6
+ - `action?: string` Default action name, default 'interact'
7
+ - `promptHeight?: number` How high the prompt floats (meters)
8
+ - `radius?: number` Default reach of add() in meters, default 2.5
9
+ - `pick: InteractionPick` Required, no default: how the interaction in front of the actor is chosen. presets.interactions.* fill it. Example: `interactions({ pick: 'aim', keys: ['KeyE'], radius: 2 }) // first person`
10
+ - `keys?: string[]` Keys of the action; required unless the game bound the action already (createEngine({ bindings: { interact: [...] } }) or input.define)
11
+
12
+ ## Methods and properties
13
+ - `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() }
14
+ - `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)
15
+ - Properties:
16
+ - `promptHeight: number` How high the prompt floats (meters)
17
+ - `items: any[]` All interactions
18
+ - `radius: number` Default reach of add() in meters (2.5)
19
+ - `pickMode: InteractionPick` How the one in front of the actor is chosen; can be changed at runtime
20
+ - `current: any` The interaction the prompt shows right now (null if none)
21
+ - `options: { action: string; id: string; label: string }[]` One best interaction per key action this frame, for a prompt that lists several keys
22
+
23
+ ## Data structures
24
+ - **InteractionOptions**
25
+ - `id?: string` Stable id for the op interaction.use { id } (default: the world record id it was built for, else a running number)
26
+ - `label?: string | (() => string)` Prompt text, or a function returning text
27
+ - `radius?: number` How close the actor must be (meters), default interactions({ radius }) = 2.5
28
+ - `action?: string` Key action name, default 'interact' (E key). Give one object a second verb by adding another interaction with another action
29
+ - `onUse?: (object: Object3D) => void` Called when pressed
30
+ - `enabled?: () => boolean` When this returns false the whole prompt disappears (to show a state such as "growing", don't use enabled: have the label function return different text by state and decide in onUse whether it can be used)
31
+ - `height?: number` How high the prompt floats above the object (meters)