threedog 0.2.0 → 0.5.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 (596) hide show
  1. package/CHANGELOG.md +290 -0
  2. package/README.md +9 -8
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +83 -16
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +32 -8
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +39 -18
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +45 -10
  11. package/core/Describe.js +104 -43
  12. package/core/Engine.js +190 -57
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +168 -79
  16. package/core/Inspect.js +2 -2
  17. package/core/InspectMaterials.js +85 -0
  18. package/core/InspectPerf.js +61 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/Ops.js +50 -9
  22. package/core/Random.js +9 -2
  23. package/core/Rays.js +5 -5
  24. package/core/SaveStore.js +41 -9
  25. package/core/Saves.js +71 -15
  26. package/core/Stream.js +14 -10
  27. package/core/Threads.js +26 -7
  28. package/core/UrlState.js +25 -9
  29. package/core/Views.js +9 -6
  30. package/core/actor.js +1 -1
  31. package/core/adaptive.js +93 -0
  32. package/core/assetEntry.js +22 -5
  33. package/core/assetHot.js +176 -0
  34. package/core/assetLoad.js +38 -11
  35. package/core/assetManifest.js +48 -9
  36. package/core/assetReport.js +1 -1
  37. package/core/audioRules.js +13 -11
  38. package/core/audioVoice.js +69 -42
  39. package/core/canvasBox.js +1 -2
  40. package/core/catalog.js +5 -2
  41. package/core/cells.js +62 -0
  42. package/core/checks.js +10 -8
  43. package/core/chunkStream.js +87 -0
  44. package/core/control.js +149 -0
  45. package/core/copies.js +32 -0
  46. package/core/dayTime.js +12 -6
  47. package/core/debugView.js +82 -15
  48. package/core/describeRender.js +43 -17
  49. package/core/describeText.js +41 -21
  50. package/core/engineCamera.js +32 -0
  51. package/core/errorCodes.js +438 -19
  52. package/core/errorHints.js +37 -141
  53. package/core/errors.js +31 -8
  54. package/core/events.generated.js +12 -7
  55. package/core/gameLights.js +62 -0
  56. package/core/grayMap.js +20 -0
  57. package/core/grid.js +128 -0
  58. package/core/gridLoad.js +20 -0
  59. package/core/ground.js +6 -4
  60. package/core/headlessLoad.js +55 -0
  61. package/core/holds.js +78 -50
  62. package/core/inputContext.js +11 -7
  63. package/core/inputDefaults.js +24 -21
  64. package/core/inputPad.js +1 -1
  65. package/core/inputPointer.js +1 -1
  66. package/core/inputTouch.js +2 -2
  67. package/core/lifecycle.js +48 -12
  68. package/core/lightWatch.js +6 -4
  69. package/core/look/coreParts.js +137 -30
  70. package/core/look/part.js +175 -95
  71. package/core/look/points.js +255 -0
  72. package/core/look/report.js +34 -17
  73. package/core/look/shadowPart.js +63 -0
  74. package/core/look/state.js +45 -0
  75. package/core/look/write.js +12 -28
  76. package/core/loop.js +101 -37
  77. package/core/math.js +11 -3
  78. package/core/moduleSlots.js +75 -0
  79. package/core/moduleTypes.js +73 -0
  80. package/core/modules.js +145 -27
  81. package/core/movement.js +2 -2
  82. package/core/namedModel.js +70 -0
  83. package/core/opsCheck.js +3 -3
  84. package/core/opsFail.js +15 -6
  85. package/core/opsGuard.js +4 -4
  86. package/core/opsRun.js +4 -3
  87. package/core/owned.js +168 -0
  88. package/core/page.js +2 -1
  89. package/core/params.js +30 -8
  90. package/core/plugins.js +277 -0
  91. package/core/saveApply.js +99 -17
  92. package/core/saveFiles.js +8 -6
  93. package/core/saveValues.js +46 -0
  94. package/core/saveVersions.js +20 -3
  95. package/core/scatter.js +48 -19
  96. package/core/sceneDelta.js +203 -0
  97. package/core/sceneMethods.js +35 -30
  98. package/core/screenToGround.js +1 -1
  99. package/core/services.js +27 -11
  100. package/core/session.js +28 -25
  101. package/core/shaderCost.js +78 -0
  102. package/core/shadowTypes.js +2 -1
  103. package/core/sharedPoint.js +317 -0
  104. package/core/skip.js +36 -28
  105. package/core/stackFrames.js +34 -0
  106. package/core/stacks.js +166 -0
  107. package/core/startup.js +153 -11
  108. package/core/streamSources.js +0 -11
  109. package/core/styleParts.js +65 -47
  110. package/core/targeting.js +1 -1
  111. package/core/textureBytes.js +20 -0
  112. package/core/thingExplain.js +2 -2
  113. package/core/thingOps.js +29 -6
  114. package/core/things.js +21 -11
  115. package/core/threadPure.js +7 -3
  116. package/core/threePatches.js +47 -0
  117. package/core/tier.js +21 -10
  118. package/core/time.js +236 -0
  119. package/core/uiClock.js +25 -0
  120. package/core/util.js +7 -1
  121. package/core/validate.js +65 -86
  122. package/core/wrap.js +106 -0
  123. package/docs/AI.md +89 -97
  124. package/docs/API.md +32 -28
  125. package/docs/CODEMAP.md +224 -149
  126. package/docs/COMMANDS.md +57 -34
  127. package/docs/CONVENTIONS.md +92 -30
  128. package/docs/MIGRATING-0.3.md +248 -0
  129. package/docs/MIGRATING-0.4.md +228 -0
  130. package/docs/MIGRATING-0.5.md +68 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +79 -27
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +12 -9
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/calendar.md +41 -0
  137. package/docs/api/cameraRig.md +16 -5
  138. package/docs/api/characters.md +41 -25
  139. package/docs/api/clock.md +6 -5
  140. package/docs/api/collision.md +9 -6
  141. package/docs/api/content.md +6 -4
  142. package/docs/api/dialogue.md +9 -9
  143. package/docs/api/engine.md +65 -62
  144. package/docs/api/events.md +19 -14
  145. package/docs/api/grids.md +3 -3
  146. package/docs/api/ground.md +1 -1
  147. package/docs/api/hud.md +2 -2
  148. package/docs/api/i18n.md +1 -1
  149. package/docs/api/input.md +11 -6
  150. package/docs/api/interactions.md +7 -5
  151. package/docs/api/inventory.md +17 -16
  152. package/docs/api/level.md +0 -1
  153. package/docs/api/lightPool.md +3 -1
  154. package/docs/api/music.md +1 -1
  155. package/docs/api/nav.md +3 -0
  156. package/docs/api/openWorld.md +2 -1
  157. package/docs/api/particles.md +2 -2
  158. package/docs/api/photo.md +0 -2
  159. package/docs/api/pickups.md +15 -0
  160. package/docs/api/post.md +5 -4
  161. package/docs/api/quests.md +2 -3
  162. package/docs/api/rigid.md +16 -14
  163. package/docs/api/saves.md +6 -4
  164. package/docs/api/settings.md +2 -3
  165. package/docs/api/sky.md +11 -44
  166. package/docs/api/stream.md +1 -1
  167. package/docs/api/style.md +31 -29
  168. package/docs/api/terrain.md +9 -6
  169. package/docs/api/terrainLook.md +10 -0
  170. package/docs/api/timeline.md +3 -4
  171. package/docs/api/tools.md +30 -13
  172. package/docs/api/triggers.md +5 -10
  173. package/docs/api/vegetation.md +12 -8
  174. package/docs/api/vegetationLook.md +10 -0
  175. package/docs/api/water.md +4 -20
  176. package/docs/api/weather.md +5 -15
  177. package/docs/api/weatherLook.md +10 -0
  178. package/docs/api/world.md +2 -1
  179. package/docs/recipes/01-new-game.md +71 -59
  180. package/docs/recipes/02-npc.md +46 -29
  181. package/docs/recipes/03-items-pickups.md +38 -24
  182. package/docs/recipes/04-quests.md +34 -27
  183. package/docs/recipes/05-props-bake.md +154 -18
  184. package/docs/recipes/06-clock-events.md +100 -52
  185. package/docs/recipes/07-flow-scenes-pause.md +41 -10
  186. package/docs/recipes/08-weather-sky.md +146 -37
  187. package/docs/recipes/09-style.md +218 -0
  188. package/docs/recipes/10-blender-level.md +14 -2
  189. package/docs/recipes/11-vehicles.md +64 -7
  190. package/docs/recipes/13-animation.md +34 -10
  191. package/docs/recipes/14-custom-module.md +65 -34
  192. package/docs/recipes/15-perf.md +35 -6
  193. package/docs/recipes/16-dev-bridge.md +65 -41
  194. package/docs/recipes/18-world.md +21 -8
  195. package/docs/recipes/19-shooting-picking.md +12 -11
  196. package/docs/recipes/20-content-actions-save.md +63 -25
  197. package/docs/recipes/21-camera.md +49 -16
  198. package/docs/recipes/22-shop-gold.md +18 -18
  199. package/docs/recipes/23-ops.md +17 -11
  200. package/docs/recipes/26-ui-parts.md +61 -12
  201. package/docs/recipes/27-net.md +12 -6
  202. package/docs/recipes/28-terrain.md +35 -2
  203. package/docs/recipes/29-grid.md +71 -33
  204. package/docs/recipes/30-templates.md +64 -12
  205. package/docs/recipes/31-audio.md +20 -12
  206. package/docs/recipes/32-action-game.md +35 -2
  207. package/docs/recipes/34-environment-lighting.md +27 -4
  208. package/docs/recipes/35-style-from-reference.md +115 -51
  209. package/docs/recipes/36-sky-ground-plant-looks.md +37 -35
  210. package/docs/recipes/37-terrain-look-hooks.md +37 -15
  211. package/docs/recipes/38-environment-look-hooks.md +64 -48
  212. package/docs/recipes/40-scene.md +16 -13
  213. package/docs/recipes/41-thing-registry.md +11 -7
  214. package/docs/recipes/42-terrain-shape.md +3 -3
  215. package/docs/recipes/43-shader-patches-surface-looks.md +171 -74
  216. package/docs/recipes/44-water-weather-look-hooks.md +30 -21
  217. package/docs/recipes/45-cascaded-shadows.md +17 -8
  218. package/docs/recipes/46-blender-art-route.md +4 -4
  219. package/docs/recipes/47-island-snow-backdrop.md +11 -10
  220. package/docs/recipes/48-make-material.md +11 -6
  221. package/docs/recipes/49-game-module-contract.md +46 -33
  222. package/docs/recipes/50-own-renderer.md +2 -2
  223. package/docs/recipes/51-capability-catalog.md +4 -4
  224. package/docs/recipes/52-look.md +228 -54
  225. package/docs/recipes/53-ground-up-close.md +58 -0
  226. package/docs/recipes/54-three-idioms.md +88 -0
  227. package/docs/recipes/55-mods-time-wrap.md +112 -0
  228. package/docs/recipes/56-webgpu-tsl.md +260 -0
  229. package/docs/recipes/57-control.md +65 -0
  230. package/docs/recipes/58-input.md +57 -0
  231. package/docs/recipes/59-depth-post-effects.md +83 -0
  232. package/docs/recipes/60-judge-the-picture.md +55 -0
  233. package/examples/action/.threedog/content-index.json +1 -0
  234. package/examples/action/GAMEMAP.md +17 -13
  235. package/examples/action/assets.js +8 -0
  236. package/examples/action/content/actions.js +1 -1
  237. package/examples/action/content/audio.js +5 -5
  238. package/examples/action/look.js +1 -1
  239. package/examples/action/main.js +10 -13
  240. package/examples/action/models.js +24 -23
  241. package/examples/pullable.json +111 -0
  242. package/examples/rc2d/.threedog/content-index.json +1 -0
  243. package/examples/rc2d/GAMEMAP.md +83 -0
  244. package/examples/rc2d/README.md +52 -0
  245. package/examples/rc2d/main.js +63 -0
  246. package/examples/rc2d/rc2d.js +197 -0
  247. package/examples/rc2d/shaders.js +144 -0
  248. package/examples/sheepisland/.threedog/content-index.json +1 -0
  249. package/examples/sheepisland/GAMEMAP.md +13 -11
  250. package/examples/sheepisland/assets.js +5 -0
  251. package/examples/sheepisland/main.js +17 -12
  252. package/examples/sheepisland/style/index.js +6 -6
  253. package/examples/styletest/.threedog/content-index.json +1 -0
  254. package/examples/styletest/GAMEMAP.md +15 -16
  255. package/examples/styletest/assets.js +6 -0
  256. package/examples/styletest/content/npcs.js +1 -1
  257. package/examples/styletest/content/templates.js +1 -1
  258. package/examples/styletest/content/vegetation.js +1 -1
  259. package/examples/styletest/look.js +1 -1
  260. package/examples/styletest/main.js +18 -17
  261. package/examples/styletest/models.js +1 -1
  262. package/examples/styletest/params.js +3 -3
  263. package/examples/techniques/contact-shadows/README.md +92 -0
  264. package/examples/techniques/contact-shadows/contactShadows.js +51 -0
  265. package/examples/techniques/contact-shadows/main.js +53 -0
  266. package/examples/techniques/day-night-grade/README.md +86 -0
  267. package/examples/techniques/day-night-grade/dayNightGrade.js +76 -0
  268. package/examples/techniques/day-night-grade/main.js +51 -0
  269. package/examples/techniques/interior-light/README.md +103 -0
  270. package/examples/techniques/interior-light/interiorLight.js +45 -0
  271. package/examples/techniques/interior-light/main.js +124 -0
  272. package/examples/techniques/modular-building/README.md +125 -0
  273. package/examples/techniques/modular-building/kit.js +426 -0
  274. package/examples/techniques/modular-building/main.js +47 -0
  275. package/examples/techniques/night-lights/README.md +94 -0
  276. package/examples/techniques/night-lights/main.js +70 -0
  277. package/examples/techniques/night-lights/nightLights.js +91 -0
  278. package/examples/techniques/outlines-and-rim/README.md +59 -0
  279. package/examples/techniques/outlines-and-rim/main.js +84 -0
  280. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  281. package/examples/techniques/procedural-animation/README.md +77 -0
  282. package/examples/techniques/procedural-animation/creature.js +44 -0
  283. package/examples/techniques/procedural-animation/main.js +45 -0
  284. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  285. package/examples/techniques/procedural-surface/README.md +67 -0
  286. package/examples/techniques/procedural-surface/main.js +103 -0
  287. package/examples/techniques/procedural-surface/surface.js +120 -0
  288. package/examples/techniques/stylized-shading/README.md +75 -0
  289. package/examples/techniques/stylized-shading/main.js +93 -0
  290. package/examples/techniques/stylized-shading/shading.js +131 -0
  291. package/examples/techniques/sun-and-key-light/README.md +135 -0
  292. package/examples/techniques/sun-and-key-light/keyLight.js +53 -0
  293. package/examples/techniques/sun-and-key-light/main.js +95 -0
  294. package/examples/techniques/wet-road/README.md +99 -0
  295. package/examples/techniques/wet-road/main.js +68 -0
  296. package/examples/techniques/wet-road/wetRoad.js +209 -0
  297. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  298. package/examples/webgpu-tsl/GAMEMAP.md +84 -0
  299. package/examples/webgpu-tsl/README.md +42 -0
  300. package/examples/webgpu-tsl/main.js +21 -0
  301. package/examples/webgpu-tsl/tslScene.js +75 -0
  302. package/examples/world/.threedog/content-index.json +1 -0
  303. package/examples/world/GAMEMAP.md +22 -15
  304. package/examples/world/art/humanoid.js +42 -0
  305. package/examples/world/art/index.js +11 -0
  306. package/examples/world/art/models.js +58 -0
  307. package/examples/world/art/shapes.js +9 -0
  308. package/examples/world/assets.js +6 -0
  309. package/examples/world/content/audio.js +5 -5
  310. package/examples/world/content/npcs.js +2 -2
  311. package/examples/world/content/props.js +1 -1
  312. package/examples/world/content/rules.js +1 -1
  313. package/examples/world/content/templates.js +1 -1
  314. package/examples/world/content/vegetation.js +1 -1
  315. package/examples/world/main.js +17 -13
  316. package/examples/world/style/index.js +61 -0
  317. package/examples/world/style/plugins/10-bloom.js +5 -0
  318. package/index.d.ts +50 -45
  319. package/index.js +27 -22
  320. package/llms.txt +20 -12
  321. package/modules/ambience/Ambience.js +34 -23
  322. package/modules/calendar/Calendar.js +163 -0
  323. package/modules/calendar/contract.js +21 -0
  324. package/modules/calendar/index.js +81 -0
  325. package/modules/{sky → calendar}/schedule.js +17 -16
  326. package/modules/calendar/seasons.js +55 -0
  327. package/modules/camera/FirstPersonCamera.js +6 -15
  328. package/modules/camera/FixedCamera.js +33 -15
  329. package/modules/camera/FollowCamera.js +90 -16
  330. package/modules/camera/RtsCamera.js +18 -17
  331. package/modules/camera/common.js +70 -19
  332. package/modules/camera/contract.js +17 -0
  333. package/modules/camera/projection.js +11 -24
  334. package/modules/characters/Character.js +196 -59
  335. package/modules/characters/NPC.js +87 -36
  336. package/modules/characters/assetModel.js +27 -8
  337. package/modules/characters/behaviors.js +2 -1
  338. package/modules/characters/contract.js +13 -0
  339. package/modules/characters/footsteps.js +1 -1
  340. package/modules/characters/index.js +87 -49
  341. package/modules/characters/moveHelpers.js +4 -5
  342. package/modules/characters/movers/common.js +97 -19
  343. package/modules/characters/movers/manual.js +20 -0
  344. package/modules/characters/movers/rapier.js +19 -16
  345. package/modules/characters/movers/simple.js +14 -11
  346. package/modules/characters/movers/support.js +172 -0
  347. package/modules/characters/npcAvoid.js +47 -42
  348. package/modules/characters/npcSim.js +12 -8
  349. package/modules/characters/npcView.js +44 -16
  350. package/modules/characters/pathAsync.js +7 -3
  351. package/modules/characters/playerStrings.js +4 -3
  352. package/modules/characters/proceduralRig.js +46 -10
  353. package/modules/characters/useModel.js +1 -1
  354. package/modules/characters/vehicle.contract.js +21 -0
  355. package/modules/characters/walkTo.js +21 -7
  356. package/modules/collision/Collision.js +65 -25
  357. package/modules/collision/grid.js +8 -6
  358. package/modules/content/explain.js +2 -2
  359. package/modules/content/fields.js +102 -0
  360. package/modules/content/ids.js +8 -6
  361. package/modules/content/index.js +97 -28
  362. package/modules/content/loader.js +45 -33
  363. package/modules/content/models.js +11 -40
  364. package/modules/content/packs.js +6 -5
  365. package/modules/content/parts.js +41 -0
  366. package/modules/content/props.js +16 -9
  367. package/modules/content/rules.js +58 -0
  368. package/modules/content/stages.js +80 -0
  369. package/modules/content/templates.js +121 -30
  370. package/modules/debug/DebugPanel.js +24 -17
  371. package/modules/flow/contract.js +16 -0
  372. package/modules/flow/index.js +21 -15
  373. package/modules/gameplay/Container.js +41 -32
  374. package/modules/gameplay/Containers.js +30 -15
  375. package/modules/gameplay/Dialogue.js +113 -55
  376. package/modules/gameplay/Interactions.js +193 -67
  377. package/modules/gameplay/Inventory.js +69 -73
  378. package/modules/gameplay/Quests.js +75 -39
  379. package/modules/gameplay/boxOps.js +3 -3
  380. package/modules/gameplay/dialogue.contract.js +21 -0
  381. package/modules/gameplay/dialogueBox.js +4 -2
  382. package/modules/gameplay/dialogueBubbles.js +116 -0
  383. package/modules/gameplay/interactionPrompt.js +4 -1
  384. package/modules/gameplay/interactions.contract.js +16 -0
  385. package/modules/gameplay/inventory.contract.js +23 -0
  386. package/modules/gameplay/inventoryOps.js +18 -16
  387. package/modules/gameplay/pickups.js +268 -85
  388. package/modules/gameplay/questLog.js +4 -4
  389. package/modules/gameplay/quests.contract.js +17 -0
  390. package/modules/grid/Grid.js +92 -50
  391. package/modules/grid/Layer.js +14 -13
  392. package/modules/grid/index.js +60 -36
  393. package/modules/grid/ops.js +20 -18
  394. package/modules/grid/preview.js +15 -16
  395. package/modules/grid/strings.js +12 -0
  396. package/modules/grid/tiles.js +6 -5
  397. package/modules/hlod/index.js +51 -19
  398. package/modules/hud/index.js +35 -20
  399. package/modules/hud/parts.js +20 -7
  400. package/modules/level/heightfield.js +3 -1
  401. package/modules/level/index.js +45 -20
  402. package/modules/level/nodes.js +4 -3
  403. package/modules/lights/index.js +42 -18
  404. package/modules/music/Music.js +38 -21
  405. package/modules/music/rules.js +1 -1
  406. package/modules/nav/index.js +48 -42
  407. package/modules/net/Client.js +13 -6
  408. package/modules/net/Host.js +19 -5
  409. package/modules/net/Net.js +2 -1
  410. package/modules/net/index.js +13 -8
  411. package/modules/net/sync.js +9 -8
  412. package/modules/net/transports.js +77 -27
  413. package/modules/particles/Particles.js +23 -14
  414. package/modules/particles/contract.js +17 -0
  415. package/modules/particles/effect.js +39 -11
  416. package/modules/photo/Photo.js +53 -36
  417. package/modules/rigid/RigidBodies.js +194 -32
  418. package/modules/rigid/Vehicles.js +18 -15
  419. package/modules/rigid/sync.js +62 -17
  420. package/modules/settings/Settings.js +57 -52
  421. package/modules/settings/apply.js +38 -3
  422. package/modules/settings/sections.js +5 -3
  423. package/modules/settings/strings.js +3 -2
  424. package/modules/settings/view.js +5 -3
  425. package/modules/sky/Sky.js +88 -176
  426. package/modules/sky/cascades.js +86 -25
  427. package/modules/sky/cascades.tsl.js +82 -0
  428. package/modules/sky/clouds.js +34 -19
  429. package/modules/sky/domeLayers.js +30 -15
  430. package/modules/sky/environment.js +83 -13
  431. package/modules/sky/fog.js +140 -95
  432. package/modules/sky/frame.js +112 -44
  433. package/modules/sky/look.js +22 -19
  434. package/modules/sky/lookFog.js +48 -52
  435. package/modules/sky/lookShadow.js +53 -41
  436. package/modules/sky/lookSky.js +82 -21
  437. package/modules/sky/season.js +21 -0
  438. package/modules/sky/shader.js +41 -19
  439. package/modules/sky/shadow.js +44 -20
  440. package/modules/sky/skyModule.js +45 -33
  441. package/modules/sky/tint.js +61 -0
  442. package/modules/terrain/ChunkManager.js +175 -108
  443. package/modules/terrain/chunkJob.js +1 -1
  444. package/modules/terrain/chunkQueries.js +6 -4
  445. package/modules/terrain/index.js +105 -50
  446. package/modules/terrain/look.js +83 -0
  447. package/modules/terrain/lookGround.js +21 -16
  448. package/modules/terrain/terrainDefaults.js +1 -1
  449. package/modules/terrain/terrainEdit.js +18 -20
  450. package/modules/terrain/terrainGen.js +5 -3
  451. package/modules/terrain/terrainIsland.js +5 -4
  452. package/modules/terrain/terrainShape.js +12 -12
  453. package/modules/terrain/terrainShapeMain.js +8 -7
  454. package/modules/terrain/terrainTexture.js +21 -19
  455. package/modules/timeline/Timeline.js +95 -43
  456. package/modules/timeline/Tween.js +18 -10
  457. package/modules/timeline/letterbox.js +2 -2
  458. package/modules/timeline/shots.js +5 -1
  459. package/modules/triggers/index.js +107 -76
  460. package/modules/vegetation/Vegetation.js +190 -102
  461. package/modules/vegetation/densityMap.js +62 -0
  462. package/modules/vegetation/groundChunks.js +52 -58
  463. package/modules/vegetation/index.js +31 -10
  464. package/modules/vegetation/look.js +119 -0
  465. package/modules/vegetation/lookWind.js +71 -10
  466. package/modules/vegetation/modelGeometry.js +3 -2
  467. package/modules/vegetation/nearFade.js +45 -0
  468. package/modules/water/Water.js +65 -27
  469. package/modules/water/look.js +29 -18
  470. package/modules/water/surface.js +64 -25
  471. package/modules/water/surfaceDefaults.js +3 -0
  472. package/modules/weather/Weather.js +62 -104
  473. package/modules/weather/look.js +1 -2
  474. package/modules/weather/particles.js +24 -9
  475. package/modules/weather/strings.js +2 -2
  476. package/modules/weather/weatherLook.js +135 -0
  477. package/modules/world/World.js +24 -7
  478. package/modules/world/explain.js +1 -1
  479. package/modules/world/index.js +18 -4
  480. package/modules/world/persist.js +62 -2
  481. package/modules/world/pos.js +3 -2
  482. package/modules/world/records.js +8 -6
  483. package/modules/world/sim.js +60 -20
  484. package/modules/world/simFar.js +4 -3
  485. package/modules/world/state.js +3 -2
  486. package/modules/world/thingSource.js +1 -1
  487. package/modules/world/views.js +7 -5
  488. package/package.json +8 -3
  489. package/presets.js +41 -27
  490. package/render/PostFX.js +145 -120
  491. package/render/backend.js +440 -0
  492. package/render/detail.js +150 -45
  493. package/render/effects.js +130 -38
  494. package/render/engineUniforms.js +10 -1
  495. package/render/fuse.js +5 -4
  496. package/render/fx/cloudShadow.tsl.js +16 -0
  497. package/render/fx/detail.tsl.js +66 -0
  498. package/render/fx/index.js +26 -0
  499. package/render/fx/lighting.tsl.js +28 -0
  500. package/render/fx/nodeErrors.tsl.js +68 -0
  501. package/render/fx/noise.tsl.js +12 -0
  502. package/render/fx/objectOrigin.tsl.js +42 -0
  503. package/render/fx/particles.tsl.js +139 -0
  504. package/render/fx/patchNodes.tsl.js +403 -0
  505. package/render/fx/postWebGPU.tsl.js +158 -0
  506. package/render/fx/season.tsl.js +13 -0
  507. package/render/fx/sky.tsl.js +260 -0
  508. package/render/fx/uniforms.tsl.js +67 -0
  509. package/render/fx/water.tsl.js +53 -0
  510. package/render/fx/wind.tsl.js +22 -0
  511. package/render/fxNumbers.js +36 -0
  512. package/render/hotGlsl.js +24 -0
  513. package/render/lighting.js +66 -14
  514. package/render/lights.js +223 -4
  515. package/render/lookGlow.js +139 -0
  516. package/render/lookSurface.js +99 -36
  517. package/render/materials.js +71 -52
  518. package/render/modeling.js +73 -0
  519. package/render/ownFrame.js +76 -0
  520. package/render/patches.js +311 -34
  521. package/render/postLook.js +124 -46
  522. package/render/postWebGL.js +197 -0
  523. package/render/probes.js +231 -0
  524. package/render/shaderErrors.js +154 -0
  525. package/render/slots.js +165 -0
  526. package/render/surface.js +53 -17
  527. package/render/terms.js +211 -0
  528. package/render/uniformDecl.js +3 -2
  529. package/types/common.d.ts +2 -2
  530. package/types/core.d.ts +620 -244
  531. package/types/gameplay.d.ts +494 -318
  532. package/types/generated/core/Audio.d.ts +26 -42
  533. package/types/generated/core/Batching.d.ts +6 -2
  534. package/types/generated/core/Budget.d.ts +2 -8
  535. package/types/generated/core/DebugOverrides.d.ts +44 -3
  536. package/types/generated/core/I18n.d.ts +2 -2
  537. package/types/generated/core/Input.d.ts +102 -31
  538. package/types/generated/core/Ops.d.ts +31 -0
  539. package/types/generated/core/Random.d.ts +2 -2
  540. package/types/generated/core/Saves.d.ts +10 -2
  541. package/types/generated/core/Stream.d.ts +1 -1
  542. package/types/generated/core/Threads.d.ts +4 -1
  543. package/types/generated/core/Views.d.ts +0 -1
  544. package/types/generated/core/audioVoice.d.ts +17 -9
  545. package/types/generated/core/control.d.ts +55 -0
  546. package/types/generated/core/session.d.ts +2 -1
  547. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  548. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  549. package/types/generated/modules/calendar/index.d.ts +10 -0
  550. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  551. package/types/generated/modules/grid/Grid.d.ts +61 -25
  552. package/types/generated/modules/grid/Layer.d.ts +5 -5
  553. package/types/generated/modules/grid/index.d.ts +29 -17
  554. package/types/generated/modules/music/Music.d.ts +5 -3
  555. package/types/generated/modules/net/index.d.ts +3 -3
  556. package/types/generated/modules/net/transports.d.ts +12 -3
  557. package/types/generated/modules/particles/Particles.d.ts +1 -1
  558. package/types/generated/modules/sky/Sky.d.ts +12 -104
  559. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  560. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  561. package/types/generated/modules/weather/Weather.d.ts +17 -18
  562. package/types/generated/modules/weather/weatherLook.d.ts +12 -0
  563. package/types/generated/modules/world/World.d.ts +18 -3
  564. package/types/generated/render/PostFX.d.ts +67 -30
  565. package/types/generated/render/materials.d.ts +26 -20
  566. package/types/generated/render/modeling.d.ts +30 -0
  567. package/types/generated/render/patches.d.ts +16 -2
  568. package/types/generated/ui/UI.d.ts +6 -3
  569. package/types/nav.d.ts +6 -0
  570. package/types/physics.d.ts +137 -44
  571. package/types/style.d.ts +125 -92
  572. package/types/tsl.d.ts +86 -0
  573. package/types/world.d.ts +164 -110
  574. package/ui/Focus.js +25 -14
  575. package/ui/LoadingScreen.js +1 -1
  576. package/ui/Parts.js +27 -11
  577. package/ui/UI.js +20 -10
  578. package/ui/cursor.js +115 -0
  579. package/ui/defaults.js +15 -11
  580. package/ui/theme.js +9 -6
  581. package/ui/touchPart.js +1 -1
  582. package/core/claims.js +0 -51
  583. package/core/look/layers.js +0 -136
  584. package/core/renamed.js +0 -21
  585. package/docs/api/entities.md +0 -61
  586. package/docs/recipes/09-style-pack.md +0 -234
  587. package/examples/styletest/overrides.js +0 -33
  588. package/examples/styletest/panel.js +0 -135
  589. package/modules/entities/Entities.js +0 -243
  590. package/modules/entities/build.js +0 -25
  591. package/modules/entities/index.js +0 -4
  592. package/modules/sky/calendar.js +0 -80
  593. package/modules/sky/layers.js +0 -69
  594. package/modules/terrain/chunkLevels.js +0 -40
  595. package/modules/terrain/mountTerrain.js +0 -32
  596. package/modules/world/cells.js +0 -42
package/docs/PERF.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Performance comparison (PERF)
2
2
 
3
- > Numbers come from a cloud environment without a GPU (Chromium + SwiftShader software rendering, 1280x720, pixel ratio 1). Use them only for
3
+ > Sections 1-5 come from a cloud environment without a GPU (Chromium + SwiftShader software rendering, 1280x720, pixel ratio 1; section 6 is a real GPU). Use them only for
4
4
  **relative comparison**; they do not represent real-device frame rates.
5
5
  > Reproduce: `node packages/tools/perf.mjs [frames]` (default 60 frames; it builds first, then opens
6
6
  > `packages/engine/tests/perf/index.html` in a headless browser; both are in the engine repository, not the npm package).
@@ -28,7 +28,7 @@ The average is capped by the display refresh rate, so this shows headroom exists
28
28
  a hemisphere light, `renderer.render` every frame.
29
29
  - `engine`: the same scene inside `createEngine()` (**no modules installed**), running the same sequence as the real-time loop each frame: fixed
30
30
  step -> frame hooks (including stream/jobs) -> render -> budget sampling -> afterRender.
31
- - `world`: `openWorld()` plus the gameplay modules it used to bundle (interactions, dialogue, inventory, quests, timeline, triggers, entities,
31
+ - `world`: `openWorld()` plus the gameplay modules (interactions, dialogue, inventory, quests, timeline, triggers,
32
32
  particles, hud; debug panel, music and ambience off), with the same seed, the same flat ground and the same vegetation as the open-world example,
33
33
  without NPCs/quests or other content; `engine.profile()` times `fixed/frame/afterRender` for each module.
34
34
  - `props`: `n` repeated props over 4 models placed through `world.present`, with a directional shadow; `batch=0` turns `engine.batching` off (section 3c).
@@ -67,9 +67,8 @@ Whole frame 3.99 ms, of which rendering (submitting draw commands) 2.97 ms; 74 d
67
67
  | terrain (chunk streaming, LOD, frustum) | 0.04 | 0.06 |
68
68
  | weather | 0.02 | < 0.01 |
69
69
  | characters / interactions / particles | 0.01 each | < 0.01-0.01 |
70
- | triggers, entities, quests, timeline, water, dialogue, settings, hud, inventory | 0 | < 0.01 |
70
+ | triggers, quests, timeline, water, dialogue, settings, hud, inventory | 0 | < 0.01 |
71
71
 
72
- (photo is no longer installed by openWorld by default, so it is not in the table.)
73
72
  Conclusion: module logic totals about 0.9 ms/frame (a quarter of the frame), and the biggest part is still Rapier; every item rose together with the
74
73
  slower whole frame (slower machine), and no single module became slower.
75
74
  particles: group X once measured 0.21 ms/frame, and this run alone it is 0.01. The world scene has no particle effects (no emit/attach); particles per
@@ -104,8 +103,8 @@ back restores 93.
104
103
  `npm run perf -- --only=props`: 3000 repeated props over 4 models (a lamp of 2 meshes, a fence, a crate, an AC unit; 3750 meshes), each a world record
105
104
  presented as a clone of its model, spread over about 143 x 143 m (16 cells of 64 m), one directional light with shadows, 60 frames, headless Chromium
106
105
  with ANGLE SwiftShader
107
- on the user's Windows machine (perf.mjs now launches with `--use-angle=swiftshader`: plain `--use-gl=swiftshader` no longer starts WebGL there, which
108
- is why section 5 shows 0 draw calls).
106
+ on the user's Windows machine (plain `--use-gl=swiftshader` does not start WebGL there, which is why section 5 shows 0 draw calls; perf.mjs has since
107
+ moved to the hardware GPU when headless reaches one, so later runs of this table are GPU numbers: the first output line names the renderer).
109
108
 
110
109
  | | CPU ms/frame | Render ms/frame | Draw calls (incl. shadow) | Shadow draw calls | Batches | Instances |
111
110
  |---|---|---|---|---|---|---|
@@ -120,6 +119,10 @@ The batching bookkeeping itself costs about 0.46 ms/frame with 3000 batched obje
120
119
 
121
120
  ## 4. Open to playable (engine.startup)
122
121
 
122
+ > Dated: the tables below predate the 2026-11-02 cold-start change (no scene render before ready, `compileAsync` for the real render target, the
123
+ > room environment built only when a material reads it, Rapier / Recast loading from install). After it a test game measured 2.9 s cold start with
124
+ > 2.46 s of long tasks before ready (Radeon 780M, headless); the open-world rows have not been remeasured.
125
+
123
126
  | Example | Open to playable ms | start() to playable ms | Asset preload ms | First-screen chunks (terrain ready) ms | Slowest module |
124
127
  |---|---|---|---|---|---|
125
128
  | Open world (`/`), before optimization | 7036 | 6778 | 0 | 4319 | terrain 4319 |
@@ -200,11 +203,36 @@ sampling the ground raster (water / slope, cached 5 s) and the batches that came
200
203
  fewer are late.
201
204
  threads 0 costs a little more than the sync loop (batch building plus the raster), so `findPath` stays the call for one-off paths.
202
205
 
206
+ ## 6. Load budget (`threedog stress`), 2026-11-02
207
+
208
+ **Machine: `ANGLE (AMD, AMD Radeon 780M Graphics (0x00001900) Direct3D11 vs_5_0 ps_5_0, D3D11)`** (AMD Ryzen 7 integrated GPU, headless Chromium on
209
+ the hardware GPU), 1280x720, pixel ratio 1, 30 frames per step, medians. Other headless browsers were running on the machine at the same time: expect
210
+ 10-20% noise. The same machine's discrete GPU (RTX 5060) is measured separately by the user (key B on the WebGPU compare page); add its row here.
211
+
212
+ Each axis alone on the neutral page `tests/stress/` (gray ground, the engine's default lights, 400 boxes under the light / shadow / post axes). frame =
213
+ CPU + waiting for the GPU to finish, no overlap: an upper bound of the real frame. "≈" is log-interpolated between the two steps around the crossing.
214
+
215
+ | Axis (unit) | Fits 16.7 ms | Fits 33 ms | CPU / GPU / frame ms at the 16.7 ms load | Stopped by |
216
+ |---|---|---|---|---|
217
+ | triangles (1M-triangle tiles, few draws) | ≈ 45M | ≈ 100M | 0.6 / 10.1 / 11.9 | 33 ms |
218
+ | draw calls (separate meshes, one material) | ≈ 2400 | ≈ 4800 | 8.6 / 4.5 / 13.1 | 33 ms |
219
+ | instances (one InstancedMesh of boxes) | ≈ 3.2M | ≈ 7.3M | 0.3 / 15.0 / 16.6 | 33 ms |
220
+ | point + spot lights (no shadow) | ≥ 128 | ≥ 128 | 2.3 / 10.3 / 13.6 | shader compile fails at 256 (uniform limit) |
221
+ | shadow-casting spot lights (1024²) | ≥ 8 | ≥ 8 | 2.7 / 2.8 / 6.6 | shader compile fails at 16 (texture units) |
222
+ | sun shadow map size | ≈ 9700² (8192² fits) | ≈ 13000² | 2.7 / 2.8 / 6.3 at 8192² | 33 ms (16384²: 45 ms GPU) |
223
+ | overlapping full-view transparent quads | ≈ 58 | ≈ 113 | 0.4 / 8.2 / 9.3 | 33 ms |
224
+ | point particles (4 px, additive) | ≈ 1.7M | ≈ 3.8M | 0.3 / 14.6 / 15.8 | 33 ms |
225
+ | post effects, cumulative: bloom, vignette, grain, lut, chromatic, outline, ao, dof | 7 (all but dof) | all 8 (17.1 ms) | 4.1 / 9.7 / 15.0 | ladder end |
226
+ | skinned characters (24 bones, 2352 triangles, own mixer) | ≈ 230 | ≈ 440 | 4.9 / 2.7 / 9.2 | 33 ms |
227
+
228
+ Reading it: on this iGPU draw calls and skinned characters are CPU-bound (main thread), everything else is GPU-bound; ao (GTAO) is the costliest
229
+ single post effect (+5 ms GPU, it redraws the scene for normals). Real scenes combine axes, so take a game's limit well below one axis' crossing.
230
+
203
231
  ## Limitations
204
232
 
205
233
  - SwiftShader does the GPU's work on the CPU, but WebGL commands are submitted asynchronously: "render ms" in the tables is mostly the time three.js
206
234
  spends traversing the scene + submitting commands, and **does not include** the time to actually draw pixels. Fragment-heavy things (shadow map
207
- resolution, bloom, ambient occlusion, transparent overdraw) show no difference here; check them on a real device with the F3 panel.
235
+ resolution, bloom, ambient occlusion, transparent overdraw) show no difference here; measure them with `threedog stress` on the GPU (section 6).
208
236
  - Noise: the same configuration run repeatedly can differ by 10-30%; draw no conclusion from smaller differences.
209
237
  - The `world` mode has no NPCs, pickups or other content, so it has fewer draw calls than the open-world example; to see the example itself, open
210
238
  `npm run dev` and run the stress test with F3.
package/docs/THREE.md CHANGED
@@ -1,7 +1,44 @@
1
- # When the engine lacks a feature: use three.js directly
1
+ # Write three.js; the engine adopts it
2
+
3
+ The scene, camera, lights, characters and models in the engine are **plain three.js objects** (three 0.187). Write the three.js you already
4
+ know: what the engine can see, it plugs in with no extra call. Only where it cannot know your intent do you write one line.
5
+ Looks (materials, shaders, textures, lights, post passes) always take this route first; engine look features are optional conveniences on top.
6
+ This is the one place that order is stated: a material is `new THREE.*Material` / `ShaderMaterial` before a slot patch or a style role, a post
7
+ pass is a three.js Pass (`engine.look.post.add(pass)`) before a ready-made effect.
8
+
9
+ | You write (plain three.js) | The engine does | The one line, only when you mean it |
10
+ |---|---|---|
11
+ | `engine.scene.add(obj)` / `group.add(obj)` | registers each root under the scene like `engine.add`: `engine.thing`, `describe().scene`, `thing.set` / `thing.remove` | a stable id so a save finds it: `engine.add(obj, { id: 'mill' })` |
12
+ | `new THREE.PointLight(...)` / `SpotLight` added to the scene | a real light, adopted as a thing; counted by `engine.budget` `lights` / `shadowLights`, listed in `describe().render.lights`; a casting light at intensity 0 stops redrawing its shadow map; weather and day-night leave its values alone | many sources, few real lights: `lightPool` (recipe 52) |
13
+ | `new THREE.MeshStandardMaterial(...)` | scene fog (height fog too), cascaded shadows | wind sway: `applyEffects(mat, { wind: 0.03 })` |
14
+ | `engine.look.post.add(pass)`, the one way into the chain (the other renderer's form: recipe 56) | slots it after the scene render and before tone mapping (FXAA / SMAA last), or after tone mapping when you added it after an OutputPass; a pass that renders `engine.scene` itself (RenderPixelatedPass, SSAA, TAA) replaces the scene render, so the scene is drawn once; skips a RenderPass / OutputPass it already has; listed in `post.list()`; `remove()` leaves it undisposed | a settings name and position: `add(pass, { name: 'glow', order })`, then `look.post.set({ glow: false })` |
15
+ | your own `EffectComposer` / `renderer.render` of the whole canvas, every frame | yields the frame (stops drawing its own, warns once `[own-frame]`); delete your render call to hand it back. A minimap / HUD layer on top (scissor, smaller viewport, or `autoClear = false` with another scene) is not a takeover | - |
16
+ | `renderer.setSize` / `setPixelRatio` yourself | the post chain follows on its next draw | - |
17
+ | `scene.fog.far = 80`, `sun.intensity = 3`, `renderer.toneMappingExposure = 1.4` | yields that value (recipe 52 "Who writes it") | dim on top of weather instead of taking it: `engine.mod('look.fog.far', { owner: 'storm', mul: 0.6 })` |
18
+ | one file per piece in `plugins/` next to index.html (`export default mesh`, a Pass, a post effect such as `grain()`, a Material, a ShaderPatch `{ slot, glsl, roles }`, a module; never a bare function) | plugs each at `engine.start()` by what it exports, through the same calls as above (`scene.add`, `look.post.add`, `look.materials.replace` / `patch`, `engine.use`); order by file name or a `plugins.json` beside them; anything else is a `[plugin-shape]` error naming the file, what it found and the fix (a factory: `export default makeIt({ ... })`; a module with no `type`: add one) | switch one off: `plugins.json` `"off": ["20-bloom"]` or `engine.plugins.off('20-bloom')` |
19
+ | a static mesh you want `engine.pick` to hit | - | `engine.rays.addStatic(obj)` (a BVH only pays off for things that do not move) |
20
+
21
+ `describe().slots` is the one table of what is plugged in where: each row is `{ slot, plugged, file, on, affects }`, for the plugins folder,
22
+ `scene.add` roots (with the file:line that added them), `look.post.add` effects, modules and plain lights. Without the vite preset, hand the folder over
23
+ yourself: `engine.plugins.add(import.meta.glob('./plugins/*.js', { eager: true }))` before `engine.start()`.
24
+
25
+ ## What the engine changes in three.js (Global changes)
26
+ Everything else in three is untouched. Every change below is listed in `describe().threePatches` (`{ id, what, scope, on, offable, lost }`);
27
+ an offable one is undone page-wide with `threePatches.off(id)` (`import { threePatches } from 'threedog'`), call it before creating the objects
28
+ that should not see it. `lost` says what stops working; a change that cannot be undone says why and `off` throws.
29
+
30
+ | id | Change | Effect on your code | Off |
31
+ |---|---|---|---|
32
+ | `shadow-accessors` | `Mesh.prototype.customDepthMaterial / customDistanceMaterial` become accessors | Unassigned, they return a shadow material only for a mesh whose material carries a vertex-moving engine patch (wind), so its shadow sways too; otherwise `undefined` as in three. An assignment always wins | yes |
33
+ | `node-setup-position` | `NodeMaterial.prototype.setupPosition` wrapped | WebGPU only: runs the engine's vertex-moving patches (wind) first; other node materials unchanged | yes |
34
+ | `scene-add-hook` | `Object3D.prototype.add / remove` wrapped (page-wide) | None to the call itself; the engine sees what enters and leaves its scene at any depth (adopting `scene.add`, fog, cascades, cloud shadow, light counts). Another library wrapping the same methods stacks with it | yes (`scene.add` no longer adopted) |
35
+ | `mesh-material-accessor` | `material` on each object entering the engine's scene: an own get / set on that object (a class accessor, e.g. troika text, still runs) | In devtools `mesh.material` shows as an accessor; `mesh.material = other` works as in three and is seen | yes (new objects) |
36
+ | `material-compile-accessor` | `onBeforeCompile` / `customProgramCacheKey` on each material the engine patches (cloud shadow on plain lit materials, wind, fog) | Your own hook, assigned before or after, runs first, then the engine's | yes (new materials) |
37
+ | `renderer-render` | `engine.renderer.render` (that instance only) wrapped | Counts your full-canvas draws so the engine yields the frame; a scissored / smaller-viewport / `autoClear = false` layer (minimap, HUD) does not count | yes |
38
+ | `shader-chunks` | `THREE.ShaderChunk.threedog_*` added (new names, nothing replaced) | None until you `#include` one | no (the engine's patches include them) |
39
+ | `light-idle-shadow` | `shadow.autoUpdate` of your shadow-casting point / spot lights: off while intensity is 0, back on when lit | Only lights whose autoUpdate was on; writing autoUpdate yourself hands the light back; `light.userData.idleShadow = false` opts one out; `describe().render.lights` shows `shadowIdled` | yes |
40
+ | `hlod-visible` | `visible` on meshes registered with `engine.hlod.add` (and their `xxx_LOD1` nodes): an own get / set | Reads "your value and not hidden far"; your writes keep your value | per handle: `remove()` |
2
41
 
3
- The scene, camera, lights, characters and models in the engine are **plain three.js objects** (three 0.187). For anything the engine does not provide,
4
- write it the three.js way you already know, as long as you follow the conventions below.
5
42
 
6
43
  ## Getting three.js objects from the engine
7
44
 
@@ -10,39 +47,45 @@ write it the three.js way you already know, as long as you follow the convention
10
47
  | THREE itself | `import { THREE } from 'threedog'` or `engine.THREE` (the same copy the engine uses) |
11
48
  | Scene / camera / renderer | `engine.scene`, `engine.camera` (PerspectiveCamera), `engine.renderer` (WebGLRenderer) |
12
49
  | Player, NPCs | `engine.player.object`, `engine.npcs.get('name').object` (Group); position `.position` (Vector3) |
13
- | Pickups, entities | `inventory.spawnPickup(...)` returns a handle with `.object` (Mesh); entity `ent.object` (root Group), `ent.visual` (model) |
50
+ | Pickups, template instances | `pickups.spawn(...)` returns a handle with `.object` (Mesh); a template instance's model is `engine.world.view(id)` (exists only near) |
14
51
  | Level | `engine.level.root`; markers `engine.level.marker('spawn').object / .position` |
15
- | Sun, ambient light, sky dome, fog | `engine.sky.sun` (DirectionalLight), `sky.hemi` (HemisphereLight), `sky.dome`, `engine.scene.fog` |
52
+ | Sun, ambient light, sky dome, fog | `engine.lights.sun` (DirectionalLight), `engine.lights.hemi` (HemisphereLight), `engine.sky.dome`, `engine.scene.fog` |
16
53
  | Water | `engine.water.sea` (Mesh; null when the game sets no water level), `water.material`, `water.bodies.get(body)` |
17
- | Particles, rain/snow | `.points` (THREE.Points) of the value returned by `particles.define(...)`; rain / snow look in the style pack (`style.weather.rain / snow`) |
54
+ | Particles, weather particles | `.points` (THREE.Points) of the value returned by `particles.define(...)`; the weather's look in the style (`style.weather`) |
18
55
  | Rigid bodies | `engine.rigid.addBox(mesh)` returns a handle `{ object, body, remove() }`, or null before Rapier is ready (object is your mesh; `castShadow` / `receiveShadow` keep the values you set, the engine does not change them) |
19
- | Terrain chunks | `engine.terrain.chunks` (Map; each chunk has `.group` and a `.terrain` mesh) |
56
+ | Terrain chunks | `engine.terrain.chunks` (Map of chunk data); a chunk's three.js objects: `engine.terrainLook.meshes.get(chunk)` (`{ group, mesh }`) |
20
57
  | Models, textures, animation | `await engine.assets.model('name or path')` (an Object3D copy), `assets.texture(...)`, `assets.animate(model).mixer` |
21
- | Vehicles, navigation, character controller | `engine.rigid.addVehicle(mesh, ...)` returns `{ body, controller }`; `engine.nav.navMesh / query / tileCache / crowd` (they are destroyed and replaced on rebuild; code that caches them compares `engine.nav.version`); `engine.player.mover.controller` (mover: 'rapier') |
58
+ | Vehicles, navigation, character controller | `engine.rigid.addWheeled(mesh, ...)` returns `{ body, controller }`; `engine.nav.navMesh / query / tileCache / crowd` (they are destroyed and replaced on rebuild; code that caches them compares `engine.nav.version`); `engine.player.mover.controller` (mover: 'rapier') |
22
59
  | glTF / compression decoders | `engine.assets.gltf` (GLTFLoader, Meshopt installed), `assets.draco` (DRACOLoader), `assets.ktx2` (KTX2Loader); the last two are created the first time compressed data is met and are null before that |
23
60
  | Rays | `engine.raycast(origin, direction)` / `engine.pick(ndcX, ndcY)` return three hits (`object` is the mesh, `face` and `point` unchanged); `{ targets: 'all' }` hits rigid bodies too (the hit carries `entry` and `kind: 'rigid'`); the underlying `engine.rays.ray` (THREE.Raycaster, `firstHitOnly` on) |
24
- | Ray acceleration (BVH) | three-mesh-bvh: on import (`import 'threedog'`) the engine replaces `Mesh.prototype.raycast` page-wide, the way three-mesh-bvh recommends, so your own `new THREE.Raycaster()` uses it too (meshes without a `boundsTree` take three's normal path); a registered mesh has `mesh.geometry.boundsTree` (MeshBVH, built only from 256 triangles up) |
61
+ | Ray acceleration (BVH) | three-mesh-bvh, without touching three's prototypes: a static mesh the engine registers (from 256 triangles up) gets `mesh.geometry.boundsTree` and its own `mesh.raycast`, so `engine.raycast / pick` are fast and your own `new THREE.Raycaster()` is plain three. Page-wide BVH for your rays: three-mesh-bvh's documented setup (`Mesh.prototype.raycast = acceleratedRaycast`, ...) |
25
62
  | Streamed-in objects | `.object` of the handle returned by `engine.stream.add({ position, build })` (the Object3D that build returned; null before it is built) |
26
- | Post-processing | `engine.look.post.replace([{ name, slot, create: ctx => pass }, ...])` takes any three.js Pass as a named effect in a slot (`scene` / `hdr` / `ldr` / `final`); `look.post.set({ 'name.enabled': false })` |
63
+ | Post-processing | `engine.look.post.add(pass)`, the one way in (a Pass, or an effect `{ name, slot, create: ctx => pass }` plus its twin for the other renderer, recipe 56; slots `scene` / `hdr` / `tone` / `ldr` / `final`; on / off with `look.post.set`); `replace([...])` swaps the whole chain |
27
64
  | Where the mouse points | Ground: `screenToGround(engine, input.pointer.ndcX, ndcY)` -> Vector3; objects: `engine.pick(input.pointer.ndcX, ndcY)` (registered static objects; for any object pass `{ targets: [object] }`) |
28
65
 
29
66
  Returned positions are all `THREE.Vector3` (the camera's `forward()/right()` are planar directions `{x, z}`; positions in photo records are saveable `{x, z}`).
30
67
  Anywhere a position is accepted it is **one argument**: Vector3 / Object3D / `[x, y, z]` / `{ x, z }` all work, and sizes go in an options object (see
31
68
  "Interface conventions" in `CONVENTIONS.md`):
32
69
  `collision.addCircle(mesh, { radius: 1 })`, `collision.addBox(mesh.position, { halfWidth: 2, halfDepth: 1 })`, `particles.emit('dust', mesh, { count: 20 })`,
33
- `triggers.add({ position: mesh })`, `entities.spawn(t, { position: v })`, `npcs.add({ position: v })`, `spawnPickup(id, v)`, `interactions.add(v or mesh, ...)`,
70
+ `triggers.add({ position: mesh })`, `content.spawn(name, v)`, `npcs.add({ position: v })`, `pickups.spawn(v, { give })`, `interactions.add(v or mesh, ...)`,
34
71
  `rigid.impulse(entry, [0, 3, 5])`, `player.placeAt(v)`. Ground sampling `engine.surface(x, z)` also accepts `engine.surface(mesh.position)`.
35
72
 
36
73
  ## Engine conventions when using three.js
37
74
 
38
- 1. **Materials use `makeMaterial('role', { color, ... })`**, not `new MeshLambertMaterial` directly. It returns a real three material (the type is
39
- decided by the style pack); afterwards change `.map`, `.transparent` as usual.
40
- 2. **Adding to the scene**: `engine.add(obj)` returns obj so it fits on one line. `engine.scene.add(obj)` is plain three.js that the engine does not
41
- track, and is just as legal. Plain three.js and templates (`engine.spawn`, content props) are two doors into one scene (`recipes/40-scene.md`).
42
- `engine.add(obj, { id })` registers the object under a stable id so `engine.thing(id)` can say what it is and what a save keeps. To
43
- attach to a character use `player.object.add(hat)`.
75
+ 1. **Materials**: `new THREE.MeshStandardMaterial(...)` is fine. Use `makeMaterial('role', { color, ... })` when you want the style's material
76
+ for a role (it returns a real three material; the type is decided by the style); afterwards change `.map`, `.transparent` as usual.
77
+ Your own shader code works as in three.js: `ShaderMaterial`, `onBeforeCompile` (also on an engine material: yours runs first, the engine's
78
+ wind / clouds / season patches after it). The engine adds effects only to materials it made; yours opt in with `applyEffects(mat, { wind: 0.03 })`.
79
+ One exception, named: with cascaded shadows on (`look.shadow.set({ cascades: 3 })`) every built-in lit material gets the `csm` patch, or it would
80
+ be lit N times; a lit `ShaderMaterial` of yours joins with `engine.look.shadow.include(mat)` (recipe 45).
81
+ 2. **Adding to the scene**: `engine.scene.add(obj)` is all it takes: every root under the scene is registered (`engine.thing(obj)` says what it
82
+ is and what a save keeps). `engine.add(obj, { id })` is only for a stable id, so `thing.set` changes to it are saved. Plain three.js and
83
+ templates (`engine.content.spawn`, content props) are two doors into one scene (`recipes/40-scene.md`). To attach to a character use `player.object.add(hat)`.
44
84
  3. **Per-frame logic goes in `engine.onFrame(dt => ...)`** (movement and timing use `engine.onFixed`); it returns a handle, cancel with `h.remove()`.
45
- Never call `requestAnimationFrame` or `renderer.render` yourself: the engine owns pausing, fast-forward in tests, post-processing and ordering.
85
+ Don't start your own `requestAnimationFrame` loop: the engine owns pausing, fast-forward in tests and ordering. Rendering the canvas
86
+ yourself (own `EffectComposer`) takes the frame over: the engine stops drawing it and its post chain, adaptive resolution and photo mode stop applying. Rendering into your own render target is fine (mirror, minimap, portal, picking): do it in
87
+ `engine.onRender(({ renderer, scene, camera, dt }) => ...)`, which runs after the camera update and batching, just before the frame
88
+ (`{ when: 'after' }` runs right after it). Plain three.js idioms and where each goes: `recipes/54-three-idioms.md`.
46
89
  4. **Snap to ground**: get ground height with `engine.surface(x, z)`, or `engine.snapToGround(obj, heightAboveGround)`. Don't raycast the terrain.
47
90
  **Rays** always go through `engine.raycast / pick`: level meshes are registered automatically; register your own static objects with
48
91
  `engine.rays.addStatic(obj)` or `assets.model(name, { static: true })`.
@@ -51,10 +94,12 @@ Anywhere a position is accepted it is **one argument**: Vector3 / Object3D / `[x
51
94
  and materials (`obj.removeFromParent()` / `scene.remove` leak GPU memory). To take it off only temporarily and `add` it back later use
52
95
  `engine.detach(obj)`. A copy from `assets.model()` shares resources with other copies (`remove` skips them); they are freed together by
53
96
  `assets.release(name)`.
54
- 6. **Sky lighting is recomputed every frame**: to darken or tint use a modifier layer
55
- `engine.sky.modify('layer', { sun, ambient, fog, tint, tintAmount })` (multipliers, layers multiply; `null` removes), and don't change
56
- `sky.sun.intensity` or `sky.modifiers` (the combined result, read-only). Adding your own point lights (street lamps, campfires) is fine.
57
- 7. **Camera**: only change properties of `engine.camera`, never replace it with a new camera (post-processing is bound to this one). When a camera
97
+ 6. **Sky lighting is recomputed every frame**, and you choose how much of it to keep: adjust it and keep the day cycle with a modifier layer
98
+ `engine.mod('look.lights.sun.intensity', { owner: 'cave', mul: 0.3 })` (also `look.lights.hemi.intensity` / `look.fog.far`; entries multiply; `remove()` ends it) or `look.lights.set(...)` as the base they multiply;
99
+ take a value with `engine.look.lights.manual('sun')` and then set `engine.lights.sun.intensity` yourself (`manual('sun', false)` gives it back).
100
+ Writing it directly without `manual` also takes it (the engine stops writing it and warns once). Every engine-written value: recipe 52
101
+ "Who writes it". Adding your own point lights (street lamps, campfires) is fine.
102
+ 7. **Camera**: only change properties of `engine.camera`, never replace the object (post-processing is bound to it; `engine.setCamera('follow')` swaps the camera *module*, not the object). When a camera
58
103
  module is installed it places the camera every frame; to control the view yourself take it with `const cam = engine.takeCamera('me')` and `cam.remove()` it
59
104
  (`engine.cameraOverride` is read-only: it shows the holder in charge, or `null`).
60
105
  8. Collision: the player only respects `engine.collision` (`addCircle / addBox / addObject(mesh)`); a mesh alone does not block anyone.
@@ -63,24 +108,31 @@ Anywhere a position is accepted it is **one argument**: Vector3 / Object3D / `[x
63
108
  `npm run bake` it reads the file.
64
109
  Things needed only nearby use `engine.stream.add({ position, build })`; put long loops in `engine.jobs.add(function* () { ...; yield; })` so they
65
110
  are spread over frames and the start does not stall.
111
+ Smooth normals on built shapes: a non-indexed geometry (`geometry.toNonIndexed()`, a `mergeGeometries` result where one part has no index) gives
112
+ every triangle its own vertices, so `geometry.computeVertexNormals()` shades each face flat (a low-poly look). Weld first with `mergeVertices` from
113
+ `three/addons/utils/BufferGeometryUtils.js` (per part, so hard edges between parts stay), then compute the normals.
114
+ 10. **One copy of the engine and of three per page**: `resolve: { dedupe: ['threedog', 'three'] }` in vite.config.js. A second engine copy
115
+ (a pack that lists threedog under `dependencies` instead of `peerDependencies`, a linked plus an installed copy) breaks shadows of wind and
116
+ cascaded-shadow materials; the engine warns once at load, naming both paths [engine-two-copies].
66
117
 
67
118
  ## Example: a spinning windmill (plain three.js + engine conventions)
68
- This is the plain three.js door. The same windmill as a template with an id, saved and editable without code, is in `recipes/40-scene.md` §1.
119
+ This is the plain three.js door: three's own materials, no style needed (`makeMaterial('building')` instead gives the pack's material for a role, when you want it unified with the pack). The same windmill as a template with an id, saved and editable without code, is in `recipes/40-scene.md` §1.
69
120
 
70
121
  ```js
71
- import { THREE, makeMaterial } from 'threedog';
72
- const mill = new THREE.Group(), wood = makeMaterial('building', { color: 0x8a6a4a, flatShading: true });
122
+ import { THREE } from 'threedog';
123
+ const mill = new THREE.Group(), wood = new THREE.MeshStandardMaterial({ color: 0x8a6a4a, roughness: 0.9, flatShading: true });
124
+ const cloth = new THREE.MeshStandardMaterial({ color: 0xe8e0d0, roughness: 1 });
73
125
  const tower = new THREE.Mesh(new THREE.CylinderGeometry(0.8, 1.2, 6, 6), wood);
74
126
  tower.position.y = 3; tower.castShadow = true;
75
127
  const blades = new THREE.Group(); blades.position.set(0, 5.5, 1.3);
76
128
  for (let i = 0; i < 4; i++) {
77
- const arm = new THREE.Group(), sail = new THREE.Mesh(new THREE.BoxGeometry(0.5, 4, 0.08), makeMaterial('building', { color: 0xe8e0d0 }));
129
+ const arm = new THREE.Group(), sail = new THREE.Mesh(new THREE.BoxGeometry(0.5, 4, 0.08), cloth);
78
130
  sail.position.y = 2; sail.castShadow = true; arm.rotation.z = i * Math.PI / 2; arm.add(sail); blades.add(arm);
79
131
  }
80
132
  mill.add(tower, blades);
81
133
  mill.position.set(20, 0, -10);
82
134
  engine.snapToGround(mill); // snap to ground
83
- engine.add(mill);
135
+ engine.scene.add(mill); // registered like engine.add; engine.add(mill, { id: 'mill' }) also keeps thing.set changes in saves
84
136
  engine.collision?.addCircle(mill, { radius: 1.3 }); // block the player (when the collision module is installed)
85
137
  engine.onFrame(dt => { blades.rotation.z += dt * 1.5; });
86
138
  ```
@@ -12,4 +12,3 @@ Ambience (ambience() module)
12
12
  - `ambience.nearWater(radius?: number) → number` — How much of the ground within `radius` meters of the listener is water (0-1), sampled at 6 points: for a water rule's volume. Example: `{ sound: 'river', volume: (e, a) => a.nearWater(20) * 0.12 } // in data: volume: { add: { nearWater: 0.12 } } (12 m)`
13
13
  - Properties:
14
14
  - `position: THREE.Vector3` Where the sounds are heard from: whoever the player controls (engine.actor), else the camera focus
15
- - `info: { sound: string; on: boolean; volume: number }[]` What each rule is doing (debug, tests): sound name, whether its condition holds, its current target volume
@@ -1,18 +1,21 @@
1
1
  # engine.assets (Assets)
2
2
 
3
- - `assets.manifest(m: AssetManifest)` — Register an asset manifest or asset pack (can be called several times; a later entry with the same name replaces the earlier one). Its name labels it in engine.loading, base resolves its relative paths
3
+ - `assets.manifest(m: AssetManifest | AssetManifest[])` — Register an asset manifest or asset pack (can be called several times; a later entry with the same name replaces the earlier one). Its name labels it in engine.loading, base resolves its relative paths
4
4
  - `assets.builder(name: string) → ((...args: any[]) => any) | null` — The generator function registered under a model name, null for a file model or an unknown name (content builds [name, ...params] models with it)
5
+ - `assets.paramsOf(name: string) → { schema, values, tuned } | null` — The params of a generator registered with a params schema: { schema, values (built with now), tuned (from setParams) }, or null
6
+ - `assets.setParams(name: string, values: Record<string, any>) → Promise<{ why: string; names: str…` — Dev tuning: build a generator with these params (replacing its defaults) and swap every live copy in place; the dev panel's models folder calls it
5
7
  - `assets.preload(onProgress?: (p: number, name: string) => void, opts?: { onlyMarked?: boolean }) → Promise<{ loaded: number; failed:…` — Preload (onProgress(0–1, current name)). Code-generated models and fonts are only loaded up front if marked preload. failed includes entries now showing their fallback
6
8
  - `assets.font(name: string) → Promise<FontFace | null>` — A font from an asset pack by name: downloaded once, added to document.fonts; null when the file failed and it is not critical. style.ui.fonts calls it at start()
7
9
  - `assets.model(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Promise<Object3D>` — Get a model copy (name or path; geometry and materials are shared with other copies). static: true registers it in engine.rays (builds ray acceleration)
8
- - `assets.modelNow(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Object3D | null` — A model copy right now if it has already loaded, else null (never starts a load, never waits): lets code that rebuilds often skip the frame an await costs. Example: `const m = engine.assets.modelNow('villager') ?? await engine.assets.model('villager');`
10
+ - `assets.modelNow(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Object3D | null` — A model copy right now if it has already loaded, else null (never starts a load, never waits): lets code that rebuilds often skip the frame an await costs. Code-built models (a build function in the manifest) count too: they are null until one await model(name) or an entry with preload: true ran (dev warns [asset-not-loaded]). Example: `const m = engine.assets.modelNow('villager') ?? await engine.assets.model('villager');`
9
11
  - `assets.geometry(nameOrUrl: string) → Promise<BufferGeometry>` — Get the geometry of the first mesh in a model
12
+ - `assets.gridFromImage(nameOrUrl: string, opts?: { channel?, range?, bits? }) → Promise<{ data: Float32Array; wid…` — An image as grid data for sampleGrid: PNG at 8 or 16 bits (jpg / webp 8). channel 'r' (default) 'g' 'b' 'a' or 0-3; range maps pixels to [min, max] (default [0, 1])
10
13
  - `assets.texture(nameOrUrl: string, opts?: { color?, pixelated?, repeat? }) → Promise<Texture>` — Get a texture (.ktx2 compressed textures also work)
14
+ - `assets.useTexture(nameOrUrl: string, use: (texture: Texture) => void, o?: { where?, instead?, opts? }) → Promise<boolean>` — Fetch a texture for something that already shows a stand-in: use(texture) runs when it arrives; a failed load is one load-failed dev warning naming `where` and what shows `instead`, and resolves false (an error inside use() is not swallowed). opts are texture()'s options
11
15
  - `assets.release(name: string)` — Release a resource and return GPU memory. Not released while copies of the model are still in the scene; it is released when the last copy is removed with engine.remove
12
- - `assets.trim() → string[]` — Release every model that has no copy in use (called automatically after level changes). Models whose shared geometry was taken by geometry() / cached() are not released automatically. Returns the released names
16
+ - `assets.trim() → string[]` — Release every model that has no copy in use (called automatically after level changes). Models whose shared geometry was taken by geometry() and code-generated models are not released automatically. Returns the released names
13
17
  - `assets.users(name: string) → number` — How many copies of this model are in use now (taken with model() and not yet removed with engine.remove)
14
18
  - `assets.forget(obj: Object3D)` — Called when an object is fully removed (engine.remove already calls it, normally you don't need to): decrements the use count of the model copies under it
15
- - `assets.cached(name: string, build: (params?: any) => T | Promise<T>, params?: any) → Promise<T>` — Code-generated model: generated only once per name + params, returns a copy (for geometry, the same one). Order: files baked by npm run bake (public/models/baked/) -> automatic dev cache (.threedog/cache, invalidated automatically when the generator or a file it imports changes) -> compute now. When the generator is newer than the baked file during development, it computes now and prints a one-time hint "run npm run bake once it is final"
16
19
  - `assets.animate(root: Object3D, config?: AnimatorOptions) → Animator` — Create an animation state machine for a skinned model (without config it is simple play-by-name). A copy of a manifest model whose entry has `animation` starts from that mapping; config wins per state
17
20
  - `assets.mapping(root: Object3D) → AnimatorOptions | null` — The manifest entry's animation mapping for a model copy, or null (not a manifest copy, or no mapping)
18
21
  - `assets.report(nameOrRoot: string | Object3D) → AssetReport` — Import report of a loaded model (by name, or a copy from model()): materials, textures with colorSpace, clips, colliders, templates, and issues for what the file has but the scene lost
@@ -30,11 +33,11 @@
30
33
  - `name?: string` Label shown as the source manifest in engine.loading (default 'manifest#1', '#2'...)
31
34
  - `base?: string | URL` Folder that this manifest's relative paths resolve against: '/packs/forest/', a CDN URL, or new URL('./files/', import.meta.url) in an npm pack. '/x' and full URLs stay as written
32
35
  - `models?: Record<string, AssetEntry>` Models (.glb / .gltf, Draco/Meshopt compression also works): name -> path or generator function
33
- - `textures?: Record<string, AssetEntry>` Textures: name -> path
34
- - `sounds?: Record<string, AssetEntry>` Sounds: name -> path
36
+ - `textures?: Record<string, AssetEntry | Texture | (() => Texture | Prom…` Textures: name -> path, or a texture made in code: a function returning a THREE.Texture (run once, on first use) or the Texture itself. Code textures come back as made (their colorSpace / wrap / repeat are yours) and are never disposed by the engine if passed as a Texture. Example: textures: { brick: () => makeBrickTexture(), sign: mySignTexture }
37
+ - `sounds?: Record<string, AssetEntry | SynthFn | { build: SynthFn; par…` Sounds: name -> file path, or a sound made in code: a synth function (SynthFn) or { build: synthFn, params } (params: its defaults). Used by name like a file: audio.sfx(name), audio.sounds rules (src / variants), music and ambience. Example: sounds: { step: '/sfx/step.ogg', ding: dingSynth }
35
38
  - `fonts?: Record<string, string | FontAssetEntry>` Fonts: name -> file, or { url, family, weight, style, ... } (family defaults to the name). style.ui.fonts lists the names the UI uses
36
39
  - **AnimatorOptions** Animation state machine parameters
37
- - `fade?: number` Default transition seconds, default 0.25 (style pack style.character.animation.fade)
40
+ - `fade?: number` Default transition seconds, default 0.25 (style.character.animation.fade)
38
41
  - `states?: Record<string, AnimatorState>` States: name → state
39
42
  - `transitions?: Record<string, number>` Transition seconds for specific pairs: { 'jump>fall': 0.1, '*>idle': 0.3 }
40
43
  - `params?: Record<string, number>` Initial parameter values
@@ -54,8 +57,8 @@
54
57
  - `states: Record<string, AnimatorState>` State configuration (states can be added directly)
55
58
  - `params: Record<string, number>` Parameters (used by blend trees)
56
59
  - `set(param: string, value: number)` — Set a parameter, e.g. set('speed', 3)
57
- - `go(state: string, fade?: number) → any` — Switch to a state (fade is the transition seconds); null (dev warning) if there is no such state / clip; ignored while sync() drives a state
58
- - `action(name: string, fade?: number) → any` — One-shot clip: state name or clip name, returns to then or the previous state when done; go() cannot interrupt it while playing
60
+ - `go(state: string, opts?: { fade?: number }) → any` — Switch to a state ({ fade }: transition seconds); null (dev warning) if there is no such state / clip; ignored while sync() drives a state
61
+ - `action(name: string, opts?: { fade?: number }) → any` — One-shot clip: state name or clip name, returns to then or the previous state when done; go() cannot interrupt it while playing
59
62
  - `sync(state: string | null, t?: number) → any` — Gameplay drives the clock: show state at gameplay time t (fixed-step seconds) through its timing. The clip never advances or ends by itself and go() leaves it alone; sync(null) hands control back
60
63
  - `describe() → AnimatorInfo` — What is showing: state, clip, clip time, progress, driven, weights
61
64
  - `check(actions?: string[]) → string[]` — Check the mapping against the action names the game plays: each problem as text with its fix ([] = all will play). Example: `anim.check(['idle', 'walk', 'attack', 'hurt'])`
package/docs/api/audio.md CHANGED
@@ -1,42 +1,38 @@
1
1
  # engine.audio (Audio) — engine.audio: buses, sounds by name, ducking
2
2
 
3
- - `audio.addBus(name: string, level?: number)` — Add a bus of your own (routed to master). It gets a settings slider like the others (label key settings.vol.<name>). Example: `engine.audio.addBus('voice', 1); engine.audio.sfx('line-01', { bus: 'voice' });`
3
+ - `audio.addBus(name: string, opts?: { level?: number; owner?: string }) → { owner?: string; remove(): void }` — Add a bus of your own (routed to master). It gets a settings slider like the others (label key settings.vol.<name>) until the handle is removed (the one give-back form, like every other handle). A name that is already a bus throws: two owners of one bus could not both remove it. Example: `const voice = engine.audio.addBus('voice', { level: 1 }); engine.audio.sfx('line-01', { bus: 'voice' }); voice.remove();`
4
4
  - `audio.setVolume(bus: string, v: number)` — Set a bus volume 0-1 ('master' for the total). Example: `engine.audio.setVolume('music', 0.3);`
5
5
  - `audio.duck(levels: Record<string, number>, opts?: { fade?: number }) → { remove(fade?: number): void }` — Lower buses until the handle is removed (dialogue, pause menu, a cutscene). Several ducks stack (their levels multiply). Example: `const d = engine.audio.duck({ music: 0.3, ambience: 0.5 }); engine.events.once('dialogue:end', () => d.remove());`
6
- - `audio.register(name: string, synthFn: SynthFn, opts?: { builtIn?, bus?, params? })` — Register a synthesized sound: synthFn(audio, params, out) connects its nodes to `out` and returns its length in seconds (or { stop(time) } for a loop). Plays for sounds entries that name it ('synth' or { synth: name }); a name with no sounds entry plays it too unless builtIn (engine modules pass builtIn: true so their synths stay silent until the game asks). Example: `engine.audio.register('ding', (a, p, out) => { a.tone({ freq: 880 * p.pitch, dur: 0.2, out }); return 0.2; });`
7
- - `audio.condition(name: string, test: (value: any, e: any) => boolean) → { remove(): void }` — Add a condition key for music / ambience rule lists: `when: { [name]: value }` calls test(value, engine). Modules add theirs (sky: time, weather: weather, triggers: zone); the engine has `state` (engine.audio.state). Example: `engine.audio.condition('inside', v => engine.vars.flag('indoors') === v);`
8
- - `audio.measure(name: string, fn: (e: any) => number) → { remove(): void }` — Add a measure: a number rule data compares (`when: { daylight: { gt: 0.15 } }`; gt / gte / lt / lte) and adds up (`volume: { add: { wind: 0.08 } }`). sky adds daylight, weather rain / snow / wind, ambience nearWater / altitude. A name is a condition or a measure, not both. Example: `engine.audio.measure('danger', e => e.vars.counter('alarm') / 10); // data: when: { danger: { gt: 0.5 } }`
6
+ - `audio.condition(name: string, test: (value: any, e: any) => boolean) → { remove(): void }` — Add a condition key for music / ambience rule lists: `when: { [name]: value }` calls test(value, engine). Modules add theirs (calendar: time, weather: weather, triggers: zone); the engine has `state` (engine.audio.state). Example: `engine.audio.condition('inside', v => engine.vars.flag('indoors') === v);`
7
+ - `audio.measure(name: string, fn: (e: any) => number) → { remove(): void }` — Add a measure: a number rule data compares (`when: { daylight: { gt: 0.15 } }`; gt / gte / lt / lte) and adds up (`volume: { add: { wind: 0.08 } }`). calendar adds daylight, weather rain / snow / wind, ambience nearWater / altitude. A name is a condition or a measure, not both. Example: `engine.audio.measure('danger', e => e.vars.counter('alarm') / 10); // data: when: { danger: { gt: 0.5 } } Measures are not only for sound: render/lookGlow.js reads 'daylight' for night glow, so the calendar (or the sky without one) registers it once and nothing else has to know which module tells day from night. remove() drops only this registration (a later one under the name stays).`
9
8
  - `audio.value(name: string) → number | undefined` — The current value of a measure (debug, tests); undefined when none is registered under that name
10
9
  - `audio.matches(when: AudioCondition | undefined, ...extra: any[]) → boolean` — Does a rule's `when` hold now? An object needs every key to hold (condition keys, or measure comparisons); a function gets (engine, ...extra); missing = always. Example: `engine.audio.matches({ time: 'night', zone: 'forest', rain: { lt: 0.2 } });`
11
10
  - `audio.volumeOf(volume: AudioVolume | undefined, ...extra: any[]) → number` — A rule's volume now: a number, a function (engine, ...extra), or data { base, add: { measure: factor }, min, max }; missing = 1. Example: `engine.audio.volumeOf({ base: 0, add: { rain: 0.22 } }); // 0.22 in full rain`
12
- - `audio.sfx(name: string, opts?: { volume?, pitch?, at?, bus?, loop?, params?, … }) → SoundHandle | null` — Play a sound by name from audio.sounds (file, variants, or a synth). Returns a SoundHandle (stop, fade, setPosition), or null when it is silent: not configured, audio still locked, or held back by the sound's cooldown. Over its `voices` limit the oldest voice stops. Example: `engine.audio.sfx('hit', { at: enemy.root, volume: 0.8 });`
11
+ - `audio.sfx(name: string, opts?: { volume?, pitch?, at?, bus?, loop?, params?, … }) → SoundHandle | null` — Play a sound by name: its audio.sounds rule (src / variants, volume, bus...), or with no rule the asset pack sound of that name (file or synth function from assets.manifest({ sounds })). Returns a SoundHandle (stop, fade, setPosition), or null when it is silent: not configured, a built-in synth the game did not name, audio still locked, or held back by the sound's cooldown. Over its `voices` limit the oldest voice stops. Example: `engine.audio.sfx('hit', { at: enemy.root, volume: 0.8 });`
13
12
  - `audio.noiseBurst(opts?: { dur?, type?, freq?, vol?, bus?, out?, … })` — Synth building block: a burst of filtered noise (footsteps, shutter, rain, thunder). dur seconds, freq Hz, vol 0-1; out: the node to connect to (a synth's `out`), else the named bus
14
13
  - `audio.tone(opts?: { freq?, to?, dur?, vol?, type?, bus?, … })` — Synth building block: a short tone (bird call, notification). freq/to Hz, dur seconds, pan -1..1; out as in noiseBurst. Example: `engine.audio.tone({ freq: 660, to: 880, dur: 0.15, bus: 'ui' });`
15
14
  - `audio.load(url: string) → Promise<any>` — Download and decode an audio file (cached). A sound name registered in an asset pack (manifest sounds) loads that file as an engine.loading task, so sounds entries and music tracks may name assets instead of paths
16
- - `audio.play(url: string, opts?: { bus?, volume?, loop?, fadeIn?, pitch?, at? }) → Promise<SoundHandle | null>` — Play an audio file by path (no sounds entry needed); resolves to a SoundHandle once the file is decoded. Example: `const h = await engine.audio.play('/sfx/door.ogg', { bus: 'ui' }); h.stop(0.5);`
15
+ - `audio.play(url: string, opts?: { bus?, volume?, loop?, fadeIn?, pitch?, at? }) → Promise<SoundHandle | null>` — Play an audio file by path (no sounds entry needed); resolves to a SoundHandle once the file is decoded. Example: `const h = await engine.audio.play('/sfx/door.ogg', { bus: 'ui' }); h.stop({ fade: 0.5 });`
17
16
  - Properties:
18
17
  - `ctx: any` The browser AudioContext (exists only after the first click)
19
18
  - `levels: Record<string, number>` Volume per bus 0-1 ('master' is the total). Every key is a bus: levels: { voice: 1 } adds a 'voice' bus
20
- - `config: import("../../core").AudioConfig` The game's sound config from createEngine({ audio }); sounds and footsteps also hold content packs' (copies: the game's object is never changed). Content packs' ambience / music rules go to ambience() / music(), not here
21
19
  - `buses: Record<string, any>` Bus input GainNodes by name (connect your own nodes here); empty until audio unlocks
22
20
  - `state: string | null` The game's current mode for rule lists, e.g. 'combat' / 'explore' (condition `state` in music and ambience rules)
23
21
  - `master: any` The master GainNode (every bus ends here)
24
22
  - `noise: any` 2 s of white noise, reused by synthesized sounds
25
23
  - `running: boolean` Is audio usable (the player has clicked/pressed a key)?
26
- - `info: { running, state, levels, ducks, voices }` What is playing (for describe and tests): bus levels, the duck multiplier per bus, live voices per sound name
27
24
 
28
25
  ## Data structures
29
- - **AudioConfig** The game's sound config: createEngine({ audio }), read back as engine.audio.config (merged with content packs' ContentAudio). Not part of a style pack
30
- - `sounds?: Record<string, SoundSource>` Sound name -> file / variants / 'synth' / SoundDef
26
+ - **AudioConfig** The game's sound config: createEngine({ audio }), read back as engine.audio.config (merged with content packs' ContentAudio). Not part of a style
27
+ - `sounds?: Record<string, SoundSource>` Sound name -> play rule: an asset sound name / path, variants, or SoundDef
31
28
  - `ambience?: AmbienceRule[]` ambience() rule table
32
29
  - `music?: { tracks?, rules?, fade?, duckDialogue?, duckFade?, hold?, … }` music() defaults: tracks, rules, fade seconds, duckDialogue (how low the music bus ducks during dialogue; default false = no duck)
33
30
  - `footsteps?: Record<string, string>` Ground type (terrain groundType or level material name) -> sound name; 'water' while swimming; default for unmapped types (else 'footstep')
34
31
  - `levels?: Record<string, number>` Volume per bus 0-1, default { master: 0.8, music: 0.5, sfx: 0.8, ambience: 0.7, ui: 0.8 }; an extra key adds a bus
35
- - **SoundDef** One sounds entry in full form. src: a file or variants (random, no immediate repeat); synth: a registered synth name (default: the entry's own name)
32
+ - **SoundDef** One sounds rule in full form: how a sound plays, never what it is made of (that is the asset manifest's: a file or a synth function). src: an asset pack sound name or a path, or variants (random, no immediate repeat); default: the asset of the rule's own name
36
33
  - `src?: string | string[]`
37
- - `synth?: string`
38
- - `params?: Record<string, any>` Passed to the synth (merged over its registered defaults)
39
- - `bus?: AudioBus` Bus it plays on (default 'sfx', or the synth's registered bus)
34
+ - `params?: Record<string, any>` Passed to a synth source (merged over the manifest entry's params)
35
+ - `bus?: AudioBus` Bus it plays on (default 'sfx', or the built-in synth's own bus)
40
36
  - `volume?: number`
41
37
  - `pitch?: number` Playback rate multiplier (1 = as recorded); synths get it as params.pitch
42
38
  - `jitter?: { volume?: number; pitch?: number }` Random spread per play, as a fraction: { pitch: 0.08 } = +-8%
@@ -0,0 +1,41 @@
1
+ # engine.calendar — calendar(opts?: CalendarOptions)
2
+
3
+ Time of day, day, seasons and clock-time timers (calendar() module); NPC schedules, content clock conditions and audio time rules read it
4
+
5
+ - Options `CalendarOptions`:
6
+ - `time?: string | number` Time of day at start: 'HH:MM' or fraction of a day 0–1 (0.5 noon), default 0.33 (afterwards read / write engine.calendar.timeOfDay)
7
+ - `dayLength?: number` Game seconds per day, default Infinity: the time of day never moves until the game sets a length (presets.calendar.cycle has 360) (one hour = dayLength / hoursPerDay game seconds; with clock.rate 1 calendar seconds are real seconds)
8
+ - `hoursPerDay?: number` Hours per day of the displayed clock and of clock notation ('18:30'), default 24
9
+ - `day?: number` Which day to start from, default 1
10
+ - `daysPerSeason?: number` Days of each season given by name only, default 7
11
+ - `seasons?: (string | { name: string, days: number })[]` Seasons, default none ([]): names (each daysPerSeason days) or { name, days } for seasons of their own length, e.g. ['spring', 'summer', 'autumn', 'winter'], [{ name: 'wet', days: 10 }, { name: 'dry', days: 20 }], or ['q1', 'q2', 'q3', 'q4'] for a business year
12
+
13
+ ## Methods and properties
14
+ - `calendar.at(clock: string | number, fn: (day: number) => void, opts?: CalendarAtOptions) → Handle` — Call fn every day at a clock time: at('18:00', fn) or at(0.75, fn). Fires only when time moves forward across the clock time: natural flow, engine.skip and setting timeOfDay later all count; crossing several triggers at once is replayed per catchUp; rewinding time and loading a save do not fire, they only reset the baseline. To hold a state during a time range (lights, shop door) use between
15
+ - `calendar.between(from: string | number, to: string | number, opts: CalendarBetweenOptions) → Handle` — Time-range switch: on() while clock time is in [from, to), otherwise off() (from > to wraps midnight). Aligns once immediately on registration, new game, load, applying a scenario and time rewind; afterwards it calls on/off when crossing a boundary. Example: `engine.calendar.between('09:00', '17:00', { on: () => shop.open(), off: () => shop.close() })`
16
+ - `calendar.daily(fn: (day: number) => void, opts?: CalendarAtOptions) → Handle` — Call fn(day) at the start of each day (00:00)
17
+ - `calendar.onSeason(name: string, fn: (season: string) => void) → Handle` — Call fn(seasonName) on entering season name
18
+ - `calendar.untilMark() → number` — Game seconds until the next clock mark (midnight, at times, between edges); engine.skip ends a segment there; Infinity when the time of day never moves
19
+ - Properties:
20
+ - `hoursPerDay: number` Hours per day (clock notation 'HH:MM', schedules, at / between)
21
+ - `daysPerSeason: number` Days per season for seasons given by name only
22
+ - `seasons: string[]` Season names, [] when the game has no seasons (the default)
23
+ - `timeOfDay: number` Time of day: 0-1 (0 midnight, 0.25 6am, 0.5 noon, 0.75 6pm); one day = dayLength game seconds (the unit of engine.clock.now). Writing it later in the day counts as time passing (at timers crossed fire); writing it earlier only resets the timers' baseline
24
+ - `day: number` Day number (1-based); writing it fires no day:start
25
+ - `dayLength: number` Game seconds per day (1 hour = dayLength / hoursPerDay game seconds; at clock.rate 1 calendar seconds equal real seconds); Infinity = the time of day never moves. Changing it keeps the current time of day
26
+ - `clock: string` Clock text, e.g. "18:00"
27
+ - `daylight: number` Daylight from the clock 0-1 (0 from 18:00 to 06:00, 1 at noon; a sine over the day). Audio rules { daylight }, ambience and the sky's default sun read it
28
+ - `isDay: boolean` Whether it is daytime by the clock (06:00-18:00 of the day's hours)
29
+ - `seasonIndex: number` Current season index, -1 without seasons
30
+ - `season: string | null` Current season name, e.g. 'spring'; null without seasons
31
+ - `dayOfSeason: number` Day within the season (1-based); 0 without seasons
32
+ - `seasonProgress: number` Fraction of the season elapsed, 0-1 (includes time of day); 0 without seasons
33
+ - `totalDays: number` Total game time in days (fractional), for growth, cooldowns and the like
34
+
35
+ ## Data structures
36
+ - **CalendarAtOptions** Parameters of calendar.at() / daily()
37
+ - `days?: number[] | ((day: number) => boolean)` Only fire on these days: a list of days, or (day) => whether to fire
38
+ - `catchUp?: 'all' | 'once' | 'skip'` When one advance crosses several trigger points: 'all' fire them all / 'once' fire once (default) / 'skip' do not make up
39
+ - **CalendarBetweenOptions** Callback of calendar.between: on is called when entering the period, off when leaving it
40
+ - `on?: () => void` Entering the period (or found inside it when aligned)
41
+ - `off?: () => void` Leaving the period (or found outside it when aligned)
@@ -3,6 +3,8 @@
3
3
  Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamera)
4
4
 
5
5
  - followCamera options `FollowCameraOptions`:
6
+ - `projection?: 'perspective' | 'orthographic'` 'orthographic' draws without perspective (isometric / 2.5D; the wheel then changes size); default 'perspective'
7
+ - `size?: number` With projection 'orthographic': world units of view height, default 20
6
8
  - `yaw?: number` Which side of the focus the camera sits on (radians), default 0.8: camera = focus + (sin yaw, cos yaw) × distance, it looks along forward() = -(sin yaw, cos yaw). Behind a character facing f: yaw = f + PI
7
9
  - `pitch?: number` Pitch angle (radians), default 0.42
8
10
  - `distance?: number` Distance (meters), default 13
@@ -20,6 +22,10 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
20
22
  - `shoulder?: number` Over-the-shoulder offset: meters to the right of the target the camera aims (negative = left shoulder), default 0
21
23
  - `pointerLock?: boolean` Click locks the mouse; mouse motion turns the view without dragging (Esc releases), default false
22
24
  - `swallowLockClick?: boolean` The press that locks the mouse is not delivered as Mouse0 / a click (default true); false delivers it too
25
+ - `ground?: 'raise' | 'shorten' | 'none' | ((facts) => Vec3Like | null | void)` What happens when the camera would go below the ground.
26
+ - `mouseLook?: boolean` false: the built-in mouse / stick look and wheel zoom are off, the game drives the view with setView() (default true)
27
+ - `hideTargetNear?: number` Hide the followed object from the camera when the camera is closer than this to the look point (meters, 0 = never; default 0.9). The shadow stays
28
+ - `hideLayer?: number` Layer used to hide the followed object (0-31), default 30
23
29
  - firstPersonCamera options `FirstPersonCameraOptions`:
24
30
  - `height?: number` Eye height above the feet (meters), default 1.6
25
31
  - `sensitivity?: number` Mouse sensitivity, default 1
@@ -37,7 +43,7 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
37
43
  - `yawLimits?: number[] | null` Turn range left / right [min, max] (radians), unlimited by default
38
44
  - `smoothing?: number` Smoothing of the camera following the body
39
45
  - `invertY?: boolean` Invert vertical
40
- - fixedCamera options `FixedCameraOptions`:
46
+ - fixedCamera options `FixedCameraOptions` (also includes the fields of Partial<CameraShot>):
41
47
  - `shots?: Record<string, CameraShot>` Shots: name → shot
42
48
  - `start?: string | null` Initial shot name
43
49
  - `auto?: false | 'nearest'` Automatic switching: false / 'nearest' (pick the one nearest to the player)
@@ -59,7 +65,7 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
59
65
  - `edgePan?: boolean` Pan at the screen edge, default false
60
66
  - `edgeSize?: number` Edge width (fraction of the screen)
61
67
  - `bounds?: { minX?, maxX?, minZ?, maxZ? } | null` Focus range (meters)
62
- - `rotateKeys?: { left?: string[]; right?: string[] } | false` Rotate keys, false turns rotation off
68
+ - `rotate?: boolean` false: no turning. Default true: declares the actions rotateLeft / rotateRight (no keys; presets.bindings.rtsRotate binds Q / R)
63
69
  - `rotateSpeed?: number` Rotation speed (radians/second)
64
70
  - `zoomStep?: number` Zoom ratio per wheel notch
65
71
  - `smoothing?: number` Smoothing
@@ -71,7 +77,8 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
71
77
  - `cam.follow(obj: Object3D | null, opts?: { distance?, height? })` — Follow someone (called automatically when the player is created), null to cancel. opts temporarily changes distance / height (used while driving), restored when the target changes
72
78
  - `cam.forward() → DirXZ` — The "forward" direction on the horizontal plane (player movement is relative to it)
73
79
  - `cam.right() → DirXZ` — The "right" direction on the horizontal plane
74
- - `cam.focusPoint() → Vector3` — Where the world loads around
80
+ - `cam.focusPoint() → Vector3` — Where the world loads around (the followed object's position, else the camera's)
81
+ - `cam.screenToGround(ndcX: number, ndcY: number) → Vector3 | null` — Screen coordinates (-1..1, engine.input.pointer.ndcX / ndcY) → the point on the ground under it, null if nothing is hit (every camera kind)
75
82
  - `cam.update(dt: number, input: Input)` — Update the camera every frame
76
83
  - `cam.onOverride(on: boolean)` — Called when a cutscene takeover starts / ends
77
84
  - `cam.onEnter(switched?: boolean)` — Called when this camera is switched in (switched: switched at runtime)
@@ -81,17 +88,20 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
81
88
  - `target: Object3D | null` The object being followed
82
89
  - followCamera only: every item of the options (the options of `followCamera`) can be read and written at runtime, e.g. `engine.cameraRig.yaw = 1.2`, `pitch`
83
90
  - `cam.frame(target: Object3D | Vec3Like | null, opts?: { strength?: number })` — Lock-on framing: turn yaw each frame toward "behind the followed object, looking at target"; mouse yaw is ignored meanwhile; null hands yaw back. strength default 6 (1/s)
91
+ - `cam.setView(view: { yaw?, pitch?, distance? })` — Set the view from game code: pitch is clamped to minPitch..maxPitch, distance to the zoom range. Negative pitch looks up. Pair with mouseLook: false to own it every frame
92
+ - `cam.getView() → FollowCameraView` — The current view: angles, wanted / actual arm, look point and 3D look direction
84
93
  - `focus: Vector3` Smoothed follow point
85
94
  - `lockPitch?: boolean`
86
95
  - `avoidOcclusion?: boolean` false: no occlusion handling
87
96
  - `framing: { target: Object3D | Vec3Like; strength: number } | null` Lock-on framing set by frame()
97
+ - `arm: number` Actual arm length last frame (after walls and ground), meters
88
98
  - firstPersonCamera only: every item of the options (the options of `firstPersonCamera`) can be read and written at runtime, e.g. `engine.cameraRig.yaw = 1.2`, `pitch`
89
99
  - `cam.lookAt(position: PositionLike)` — Turn toward a world position (Vector3 / object / [x, y, z] / { x, y, z })
90
100
  - `eye: Vector3` Eye position
91
101
  - fixedCamera only:
92
102
  - `cam.add(name: string, shot: CameraShot)` — Add / replace a shot
93
103
  - `cam.cut(name: string)` — Cut to a shot immediately
94
- - `cam.blend(name: string, seconds?: number, ease?: Ease) → Promise<void>` — Transition smoothly to a shot (over seconds seconds); the Promise resolves when done
104
+ - `cam.blend(name: string, opts?: { seconds?: number; ease?: Ease }) → Promise<void>` — Transition smoothly to a shot ({ seconds = 1, ease }); the Promise resolves when done
95
105
  - `cam.nearest(p: Vector3) → string | null` — Name of the shot nearest to a point
96
106
  - `shots: Record<string, any>` All shots
97
107
  - `current: string | null` Current shot name
@@ -105,7 +115,6 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
105
115
  - `ease: Ease`
106
116
  - rtsCamera only: every item of the options (the options of `rtsCamera`) can be read and written at runtime, e.g. `engine.cameraRig.yaw = 1.2`, `pitch`
107
117
  - `cam.moveTo(position: PositionLike, opts?: { instant?: boolean })` — Move the view to position (instant: true skips smoothing)
108
- - `cam.screenToGround(ndcX: number, ndcY: number) → Vector3 | null` — Screen coordinates (-1..1) → a point on the ground, null if nothing is hit
109
118
  - `following: boolean` Is it following target
110
119
  - `focus: Vector3` Focus (on the ground)
111
120
  - `rotate: boolean` Can it rotate
@@ -118,3 +127,5 @@ Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamer
118
127
  - `fov?: number` Field of view (degrees)
119
128
  - `at?: Vec3Like` Position used to judge the "nearest shot", defaults to position
120
129
  - `trackHeight?: number` How high above the character to look at (meters)
130
+ - `projection?: 'perspective' | 'orthographic'` 'orthographic' draws this shot without perspective (isometric / 2.5D); default 'perspective'
131
+ - `size?: number` With projection 'orthographic' (required there): world units of view height; the width follows the aspect