threedog 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -3,10 +3,12 @@
3
3
  There is a single pathfinding entry point: `engine.characters.findPath(from, to)`; NPC schedules use it too.
4
4
  - Without `nav()` (or before it is built): the collision module's grid A* (good enough for open terrain with a few obstacles).
5
5
  - With `nav()`: after a level loads, a Recast navmesh is built; paths are more accurate and go around walls more cleverly. **Only level ground (the
6
- level module) is supported for now**; procedural terrain keeps using A*.
6
+ level module) is supported**; procedural terrain keeps using A*. The mesh is built once per level: `engine.terrain.edit` and other ground changes do not
7
+ update it, so a game that reshapes walkable ground at runtime leaves `nav()` out.
7
8
 
8
9
  ## 1. Install (main.js)
9
- ```js
10
+ A level is a file or a `THREE.Object3D` built in code: `level({ scene: group })`, its meshes named as in `10-blender-level.md`.
11
+ ```js fragment
10
12
  import { level, collision, followCamera, characters, nav } from 'threedog';
11
13
  engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), characters(),
12
14
  nav({ agentRadius: 0.4, agentHeight: 1.8, maxClimb: 0.45, maxSlope: 45, debug: false })); // debug: true draws the navmesh
@@ -14,30 +16,30 @@ engine.use(level({ url: '/models/town.glb' }), collision(), followCamera(), char
14
16
  - Mesh source: the walkable meshes in the level (naming convention in `10-blender-level.md`). Walls = the level's `col_` boxes + every
15
17
  `addBox / addCircle` in the collision module;
16
18
  they sync automatically as dynamic obstacles: add an obstacle in game and the affected tiles rebuild themselves, no manual refresh.
17
- - Recast (about 1 MB) is downloaded only in start(); until it is ready findPath falls back to A*.
19
+ - Recast (728 KB, 218 KB gzipped) starts loading when `nav()` is installed, and a game without `nav()` never downloads it; the path worker's bundle holds a second copy. Until it is ready findPath falls back to A*.
18
20
 
19
21
  ## 2. Use
20
- ```js
21
- const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, z }...] or null (unreachable)
22
+ ```js fragment
23
+ const path = engine.characters.findPath(engine.player.position, { x: 4, z: 5 }); // [{ x, y, z }...] or null (unreachable); a y on either end picks the floor
22
24
  const wall = engine.collision.addBox([16, 0, 0], { halfWidth: 4.5, halfDepth: 1 }); // temporarily block a gap (center, half width, half depth); the navmesh updates with it
23
25
  wall.remove(); // remove the obstacle
24
- engine.npcs.add({ name: '信使', position: [4, 0, -5], schedule: [{ at: 0, position: [4, 0, 5] }] }); // the NPC finds its own way there
26
+ engine.npcs.add({ name: 'Courier', position: [4, 0, -5], schedule: [{ at: 0, position: [4, 0, 5] }] }); // the NPC finds its own way there
25
27
  engine.nav.dispose(); // unload the navmesh; afterwards A* is used again
26
28
  ```
27
29
  Native Recast objects: `engine.nav.navMesh / query / tileCache / crowd` (crowd needs `nav({ crowd: true })`).
28
30
 
29
31
  ## 3. Verify
30
32
  - `describe().nav`: `{ ready: true, version, obstacles: number of obstacles }`; in `describeText()` it is the "nav: {...}" line.
31
- - In a test: after `engine.pause()` call `findPath` and look at the waypoints (going around a wall they pass through the gap); after `addBox`,
33
+ - In a test: after `engine.haltLoop()` call `findPath` and look at the waypoints (going around a wall they pass through the gap); after `addBox`,
32
34
  `engine.step(0.1)` and query again: the path should switch sides.
33
- - Did the NPC arrive: after `engine.step(30)`, check `engine.npcs.get('信使').position`.
34
- - To see the mesh: `nav({ debug: true })` + `npm run shot -- /your-page.html`. Related test: `npm test -- 导航网格` (test page in the engine repository:
35
+ - Did the NPC arrive: after `engine.step(30)`, check `engine.npcs.get('Courier').position`.
36
+ - To see the mesh: `nav({ debug: true })` + `npm run shot -- /your-page.html`.
35
37
  `packages/engine/tests/nav/`).
36
38
 
37
39
  ## 4. Many paths at once: findPathAsync
38
40
  `findPath` answers now, on the main thread. For crowds (dozens of NPCs repathing, AI squads) use `findPathAsync`: the same search (navmesh if ready, else A*)
39
41
  runs in `engine.threads` workers and `done(path, status)` runs at the start of a fixed step about 4 steps (67 ms) later, through `engine.commits`.
40
- ```js
42
+ ```js fragment
41
43
  const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { // status 'ok' | 'noPath' | 'notReady', as findPath({ detailed: true })
42
44
  guard.path = path;
43
45
  }, { radius: 0.5 });
@@ -47,15 +49,58 @@ engine.characters.pathsPerStep = 64; // requests sent per fixed step (
47
49
  - Built-in NPCs already use it; keep `findPath` for the few calls that need a path this step (player click-to-move).
48
50
  - threads on / off / slow / crashed give identical paths on the identical step: the worker mirrors the navmesh (exported bytes) and the collision colliders;
49
51
  if either changes while a batch is in flight, that batch is recomputed on the main thread on the new state.
50
- - With A*, ground shape (water, slope) is sampled on a 1 m raster cached 5 s (colliders and terrain trees are tested exactly), and the search stays inside
52
+ - With A*, ground shape (height, water, slope) is sampled on a 1 m raster cached 5 s, every floor of it, so what stands under a bridge or a storey counts as it does for `findPath` (colliders and terrain trees are tested exactly), and the search stays inside
51
53
  the start-goal box plus a margin, so an async path can differ slightly from `findPath`'s.
52
- - A save taken while a request is in flight does not keep it: the NPC asks again after loading. Tests: `npm test -- "paths:"`.
54
+ - A save taken while a request is in flight does not keep it: the NPC asks again after loading. Tests: `threedog test "paths:"`.
53
55
 
54
56
  ## 5. One source for "can walk there"
55
57
  `createEngine({ movement: { radius, height, maxSlope, stepHeight } })` sets it once; read it as `engine.movement`. Collision, the Rapier capsule, the
56
58
  navmesh, A* and level steps all read it, so a module never writes its own 0.4 or 0.45. A character's position belongs to its mover: other systems
57
59
  request movement (`placeAt`, `move`, vehicle `enter`) and never set `player.position`.
58
60
 
61
+ A navmesh is cut for one body, so bodies of other sizes get their own. `nav({ agentRadius })` is the size built at load; a path asked for with another `radius` (`findPath`, `findPathAsync`, and `walkTo` and NPCs, which pass the character's own) uses a mesh of that size, built the first time it is asked for and kept until the next rebuild. A small body takes the gap a large one cannot, and a body too wide for every way gets `noPath` and stays put.
62
+ - Sizes are whole cells (`cellSize`, 0.3 m by default), rounded up: 0.5 and 0.6 share a mesh, and only a body no wider than `agentRadius` shares that one. To tell closer sizes apart, or fit a gap within a cell of the body, make `cellSize` smaller.
63
+ - Each extra size is another mesh in memory, about as big as the first, and its first ask builds it there and then, on the main thread: about 10 ms on a 40 m level, 0.3 s on a 200 m one with 300 walls. Ask once during loading to take that off the first walk: `engine.nav.findPath(a, b, { radius })`. With one size none of this happens. Obstacles and rebuilds reach every size.
64
+ - Links exist on each size where both ends still reach its mesh, and their ends sit a little differently on each. `engine.nav.links` is the links of `agentRadius`; `crossing.to` on a path is the walker's own.
65
+ - Height, step and slope are the same for all sizes: only the radius differs.
66
+ - `nav({ crowd: true })` keeps one crowd on the `agentRadius` mesh: Recast's crowd runs on a single mesh, so give it the size of the widest crowd NPC. Use plain NPCs where sizes must differ.
67
+
68
+ Floors: a `y` on a path, a stop or `collision.walkable([x, y, z])` picks the floor nearest that height, and `{ x, z }` means the ground. A height more than `engine.movement.height` from every surface there goes to the nearest one and warns once `[nav-height]`. A box added with `y` blocks only that floor, for paths, walkers and NPCs alike. Going between floors needs the navmesh; A* stays on the walker's floor and answers `noPath` for a goal on another one. Without `nav()`, a game names its stairs itself: `engine.mod('characters.path', { owner, set: ({ from, to }) => points })` returns the waypoints with their `y`, and `walkTo`, NPCs and `findPath` follow them. A walker that falls off asks again, so the list must work from anywhere it can be.
69
+
70
+ ## 6. NPC links across gaps
71
+ A link joins two places no one can walk between (Recast calls it an off-mesh connection): a gap, a ledge, a teleporter. Paths use it like any other way, and a walker with no help from the game crosses in a straight line at walking speed.
72
+ ```js fragment
73
+ nav({ links: [
74
+ { id: 'gap', from: [-2.2, 0, 0], to: [2.2, 1.5, 0] }, // both ways
75
+ { id: 'drop', from: [10, 4, 2], to: [12, 0, 2], oneWay: true }, // down only
76
+ ] });
77
+ const path = engine.characters.findPath(a, b); // [{ x, y, z }, { x, y, z, link: { id: 'gap', from, to } }, { x, y, z }...]: the leg after a point with link is the crossing
78
+ ```
79
+ - Put each end on or near walkable ground: within `radius` sideways (default the agent radius + 3 cells, enough for a point at a ledge or a ladder just off it) and within `maxClimb` in height. A `y` left out is the ground there.
80
+ - Each end then moves onto the mesh, and that is where walkers step on and land: the mesh stops about the agent radius short of every edge, so a ladder at a deck's side or through a hatch ends 0.6 to 0.8 m in from the edge (cells round it), on the deck, wherever its top was written: in a 1.4 m hatch a foot at the opening's edge gives ends 0.6 to 0.9 m apart, a foot at its middle 1.3 m or more. `engine.nav.links` and `crossing.to` give those places. The straight line between them cuts through the deck's edge, so a ladder that must look straight uses `linkPose` to climb first and step in last (below).
81
+ - A link reaches at most the neighbouring tile, counted where its ends meet the mesh: two platforms up to `tileSize` x `cellSize` meters (9.6 m by default) minus a little on each side. An end that attaches nowhere gets the `nav-link` warning at the build; no path uses that link.
82
+ - An obstacle on an end cuts the link until the obstacle goes. Elsewhere, rebuilt tiles keep their links, and `findPathAsync` sees the same ones. Links are fixed at `nav()`: none can be added at run time.
83
+
84
+ The engine moves the walker and says when; how it looks and how long it takes are yours. NPCs, `character.walkTo` and `nav({ crowd: true })` NPCs all cross this way. There is no default animation: the body keeps its last state.
85
+ ```js
86
+ engine.events.on('link:enter', ({ character, crossing }) => { // crossing: { link, from, to, seconds, time }
87
+ if (crossing.link === 'gap') { crossing.seconds = 0.7; character.playAction('jump'); }
88
+ });
89
+ engine.events.on('link:exit', ({ id, crossing }) => console.log(id, 'crossed', crossing.link));
90
+ engine.characters.linkPose = (t, position) => { position.y += Math.sin(t * Math.PI) * 1.2; }; // t 0-1: bend the straight line into a hop
91
+ engine.characters.linkPose = (t, position, { from: a, to: b }) => { // or through a hatch: up the opening, then the step onto the deck; coming down, the step first
92
+ const up = b.y > a.y, side = up ? Math.max(0, t - 0.85) / 0.15 : Math.min(1, t / 0.15), rise = up ? Math.min(1, t / 0.85) : Math.max(0, t - 0.15) / 0.85;
93
+ position.set(a.x + (b.x - a.x) * side, a.y + (b.y - a.y) * rise, a.z + (b.z - a.z) * side);
94
+ };
95
+ ```
96
+ - During a crossing the walker has no gravity or collision and its talk, goal and behavior wait. `npc.placeAt` ends it, and `link:exit` still comes. A control holder above the walker (a cutscene, a ragdoll, a `walkTo` on an NPC) does not wait for it: the walker lands at the far end at once, with its `link:exit`. A walker with no speed (a `move.speed` mod of 0) also lands at once, unless `link:enter` sets `seconds`.
97
+ - An NPC's crossing is saved (`rec.nav.link`). After a load it goes on from the same spot: `link:enter` is not sent again, so a clip started there does not restart; `linkPose` and `link:exit` work as before. An NPC that goes out of range mid-crossing lands at the far end at once, with `character: null` in `link:exit`. A `walkTo` is not saved: its crossing ends with the walk, and `walk.remove()` lands the character at the far end.
98
+ - `linkPose` must depend only on its arguments, or a loaded crossing jumps. The game cannot hold a walker on a link until a clip ends: give `seconds` the clip's length.
99
+ - With `crowd: true` the crowd takes a link about 1 m short of its end, so the NPC walks the rest and crosses from the end like any walker; the agent is pulled back to the NPC after the crossing, and only the character's own crossing counts. Recast does not say which link an agent took, so the nearest link end is used: keep the ends of two links apart. Recast times its traversal by the distance in x, z, so ends closer than the NPC's speed / 30 m on the mesh (one x, z, say, a ladder up through a solid deck) are over before the NPC can see them: such a link is not for crowd NPCs. Any opening is far enough: the deck stops short of it, as above.
100
+ - A link has no queue. Walkers on it share the line and pass through each other, up and down at once, and other agents do not avoid them: six crowd NPCs pacing through one hatch never jammed (44 crossings in 46 s), often two on it 0.2 m apart. Taking turns is the game's.
101
+ - A walker is not done while a link is left on its path, however close the goal is in x, z, so a goal at the top of a ladder is reached at the top. An NPC standing within `arriveDistance` of such a goal with no path yet, or one steered by the crowd, still stops at the foot: give the goal a place away from the ladder.
102
+ - Paths choose a link by its length, like walking: there is no extra cost for a jump. Start and goal heights still come from `engine.surface`, so a path from under a deck starts on top of it.
103
+
59
104
  ## Fences and rivers (collision)
60
105
 
61
106
  Walls and water that are not meshes: `engine.collision.addSegment(a, b, { thickness })` is a thin wall along a line; `addBlocked(fn)` marks ground impassable where `fn(x, z)` is true. Both return `{ remove() }` and are free when unused.
@@ -70,9 +115,9 @@ engine.collision.addSegment([-18, 0, 0], [-18, 0, 12], { thickness: 0.4 });
70
115
 
71
116
  Walkers stop at the edge and slide along it; `collision.walkable()` and A* pathing, sync and async, see both. `fn` must be pure and deterministic (no clock, no random). Async paths cannot send a function to the worker, so `fn` is sampled into the 1 m ground raster instead (re-sampled when you add or remove a field): give `bounds`, or every requested tile is sampled in full. Navmesh mode (`nav()` installed) does not see `addBlocked`; use `addSegment` or bake the river into the mesh there.
72
117
 
73
- ## Line of sight and straight-line checks: collision.lineClear
74
- `engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?" for a 3D segment: boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m above it; a collider's `y` / `height` count). It is a boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (pass the character radius for "can I walk straight there").
75
- ```js
118
+ ## Line of sight, stealth vision cones and straight-line checks: collision.lineClear
119
+ `engine.collision.lineClear(a, b, { radius })` answers "is anything solid between a and b?", the wall test of a guard's stealth vision cone (the cone itself is your own distance and angle check on `guard.facing`) for a 3D segment: boxes, circles and terrain trees, with heights (a 1 m wall does not block a sight line 3 m above it; a collider's `y` / `height` count). It is a boolean; `addBlocked` water is ignored. Give eye heights in `a` / `b`; `radius` fattens the line (pass the character radius for "can I walk straight there").
120
+ ```js fragment
76
121
  const sees = engine.collision.lineClear([guard.x, 1.6, guard.z], [player.x, 1.6, player.z]); // true = clear view
77
122
  const straight = engine.collision.lineClear(me.position, goal, { radius: engine.movement.radius });
78
123
  ```
@@ -1,11 +1,13 @@
1
1
  # Animation state machine (skeletal animation)
2
2
 
3
+ **In this recipe**: the model (1), clip names (2), skinned characters (3), procedural bodies (3b), 2D sprite characters (3c), which modules need a character (3d), other objects (4), gameplay-driven progress (5), checking (6).
4
+
3
5
  There is a single entry point: `engine.assets.animate(model, config)` -> Animator (advanced every frame by the engine; never call mixer.update yourself).
4
6
  For characters (player, NPCs), passing `model` builds the Animator automatically and switches clips by character state (idle walk run swim jump fall drive).
5
7
 
6
8
  ## 1. The model
7
- Export a glTF with animations from Blender, put it in `art/models/` -> `npm run assets` -> `public/optimized/hero.glb`. Register it and fetch a copy (the
8
- skeleton is cloned correctly; clips are in `userData.animations`):
9
+ Export a glTF with animations from Blender, put it in `art/models/` -> `npm run assets -- optimize` -> `public/optimized/hero.glb`. Register it and fetch a copy (the
10
+ skeleton is cloned correctly; clips are in `model.animations`, three's own place, so `model.clone()` animates too):
9
11
  ```js
10
12
  engine.assets.manifest({ models: { hero: '/models/hero.glb', dog: '/models/dog.glb' } });
11
13
  const hero = await engine.assets.model('hero');
@@ -19,13 +21,14 @@ states: { idle: { clip: 'Idle_Sword' }, attack: { clip: 'Sword_Slash', loop: fal
19
21
  ```
20
22
  **Keep the mapping as data, on the model's manifest entry** (it describes the file, so it travels with it in an asset pack). `assets.animate(model)`
21
23
  and characters start from it; config passed in code adds states and wins per state. Swapping the model then only edits its manifest entry:
22
- ```js
24
+ ```js fragment
23
25
  engine.assets.manifest({ name: 'heroes', models: { hero: { url: '/models/hero.glb', animation: {
24
26
  fade: 0.2,
25
27
  states: { idle: { clip: 'Idle_Sword' }, walk: { clip: 'Walk' }, attack: { clip: 'Sword_Slash', loop: false, timing: 0.62 }, hurt: { clip: 'HitRecieve', loop: false } },
26
28
  } } } });
27
29
  engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // no clips / animation in code
28
- engine.assets.mapping(engine.player.anim.root); // after whenReady: the entry's mapping, or null
30
+ await engine.player.whenReady;
31
+ engine.assets.mapping(engine.player.anim.root); // the entry's mapping, or null
29
32
  ```
30
33
  A character's default names (`Idle`, `Walk`...) never shadow a mapped state, and the entry's `fade` beats `characters({ animation })`.
31
34
 
@@ -53,7 +56,7 @@ over: it runs after the mover's state each step and returns a state name or null
53
56
  like any other state, a speed change stays `engine.mod('move.speed')`. A state only names the pose: climbing also needs someone to move the body
54
57
  (recipe 57, Moved by script, has a ladder).
55
58
  ```js
56
- createPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
59
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero, clips: { crouch: 'Crouch', glide: 'Glide' },
57
60
  states: (c, f) => f.grounded && engine.input.down('crouch') ? 'crouch' : !f.grounded && f.vy < 0 && gliding ? 'glide' : null });
58
61
  ```
59
62
  Deep water follows `water`: `'swim'` (default), `'block'` (never enters), `'wade'` (walks the bottom), or `(c, { depth }) => mode` per spot;
@@ -77,18 +80,12 @@ that color. A model keeps its own materials.
77
80
  **By asset name.** `model` also takes the name of a registered model asset: a file model, or a procedural builder. The character is built at once
78
81
  with a gray capsule; when the asset loads, a skeleton-correct copy replaces it under the same root, so position, facing, state, collision and the
79
82
  world view stay. Then `ready` turns true, `whenReady` settles and `character:model` is emitted. A name no model asset has throws with the registered
80
- names; a failed load keeps the capsule and warns once; a character disposed before loading ends never gets the model.
81
- ```js
82
- engine.assets.manifest({ models: { hero: '/models/hero.glb' } });
83
- const p = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'hero' }); // capsule now, the hero once loaded
84
- await p.whenReady; // p.anim is set from here (unless the load failed)
85
- ```
83
+ names; a failed load keeps the capsule and warns once; a character disposed before loading ends never gets the model. `p.anim` is set after `await p.whenReady` (unless the load failed).
86
84
 
87
85
  ## 3b. Procedural bodies are assets too (`model: 'humanoid'`)
88
- Character bodies are assets: every character picks one with `model`, the same path for a GLB and a procedural builder. an asset
89
- pack can supply a code-built humanoid (e.g. box limbs, swung by the engine while walking, running, swimming, jumping); a builder is built at once, so its joints
90
- (`player.armL`, `legR`...) exist right after `createPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
91
- ```js
86
+ Every character picks its body with `model`, the same path for a GLB and a procedural builder. An asset pack can supply a code-built humanoid (box limbs swung by the engine
87
+ while walking, running, swimming, jumping); a builder is built at once, so its joints (`player.armL`, `legR`...) exist right after `createPlayer`. Without `model` (and without `rig`) a character is a gray capsule, warned once.
88
+ ```js fragment
92
89
  import { assets } from './assets.js'; // an asset pack of yours (or a published one) with a 'humanoid' builder
93
90
  engine.assets.manifest(assets);
94
91
  engine.characters.createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' });
@@ -100,6 +97,61 @@ engine.npcs.add({ id: 'fisher', model: 'humanoid', colors: { body: 0x4f6d8f } })
100
97
  limbs: [{ joint: 'legL', offset: 0, amp: 0.9, kind: 'leg' }] }` (object names, so it survives copies and baking) animates like the humanoid; mark
101
98
  meshes `userData.part = 'body'` for `colors`. A hand-built one-off passes `{ rig }` instead ([02-npc](02-npc.md)).
102
99
 
100
+ ## 3c. Sprite characters: a 2D billboard or flat body in plain three.js
101
+ A 2D sprite character is a plain three.js object handed to `model`, so there is no sprite module to learn. `THREE.Sprite` always faces the camera (a billboard);
102
+ a `Mesh` with a `PlaneGeometry` stays flat and turns with `character.root`, takes light and can cast a shadow, which a `Sprite` does neither of.
103
+ Frames are drawing, so they live in `picture/` (recipe 62) and gameplay never touches them. `onPose` gives them the character's state each frame:
104
+ ```js fragment
105
+ // picture/sprites.js: a sheet of cols x rows frames; which row is which is your sheet's layout
106
+ const ROW = { idle: 0, walk: 1, run: 1, jump: 2, fall: 2 };
107
+ export function spriteBody(texture, cols, rows, framesPerSecond) {
108
+ const map = texture.clone(); // offset lives on the texture, so one clone per character; the image stays shared
109
+ map.needsUpdate = true;
110
+ map.repeat.set(1 / cols, 1 / rows);
111
+ const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map }));
112
+ sprite.center.set(0.5, 0); // feet on the character's origin
113
+ let t = 0;
114
+ const animate = (c, dt) => {
115
+ t += dt;
116
+ map.offset.set(Math.floor(t * framesPerSecond) % cols / cols, 1 - ((ROW[c.state] ?? 0) + 1) / rows);
117
+ };
118
+ return { sprite, animate };
119
+ }
120
+ // main.js: the sheet is a name in assets.js like any texture
121
+ const hero = spriteBody(await engine.assets.texture('hero-sheet', { pixelated: true }), 4, 3, 8);
122
+ engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero.sprite }).onPose(hero.animate);
123
+ ```
124
+ **In an orthographic view of a 3D scene** use `pixelSprite` from `threedog/pixel` instead of a `Sprite` or a free plane (recipe 62 section 4b): a plain `Mesh` that stands upright, so walls behind it do not cut its head, and shows one texel per art pixel. `model` takes it as it is. It ignores the turn of `character.root`, and `onPose` picks the frame:
125
+ ```js fragment
126
+ const hero = pixelSprite({ grid: engine.cameraRig.pixelSnap.grid, material, width: 16, height: 24, columns: 4, rows: 3, snap: 'followed' });
127
+ const ch = engine.characters.createPlayer({ ...presets.player.thirdPerson, model: hero });
128
+ const right = engine.cameraRig.pixelSnap.grid.axes().right; // the same vector every frame
129
+ ch.onPose(c => spriteFrame(hero, ROW[c.state] * 4, Math.sin(c.facing) * right.x + Math.cos(c.facing) * right.z < 0)); // no state machine here: which frame shows is the game's
130
+ ```
131
+ `c.facing` is an angle in radians around Y (0 looks along +Z), so `c.facing < 0` is not "looks left": which way is left depends on how the camera is turned. Mirror when the heading `(sin, cos)` points against the screen's right axis, as above. Run once in a view turned 45 degrees: walking toward the screen's right gave "not mirrored"; the other direction was not run.
132
+ `character.root` and `hero.position` stay exact, so physics and saves see the true position. A one-off `new Character(engine, { model: hero })` still needs `engine.add(character.root)`, as in recipe 02.
133
+ - **What the engine still does**: everything but the drawing. The mover, ground and collision, `state`, `facing`, `walkTo`, the camera and the save work as for any body; `anim`
134
+ has no clips to play. A one-off NPC is `new Character(engine, { model })` the same way ([02-npc](02-npc.md)).
135
+ - **Facing**: a `Sprite` ignores `root`'s turn and a negative scale. Pick a row from `c.facing`, or mirror with a negative `map.repeat.x` and the matching `offset`.
136
+ - **Edges**: `alphaTest` on the material gives hard edges and no sorting trouble between overlapping sprites. For a side or top-down view see recipe 21 section 6; for a pixel look, recipe 62 section 4b.
137
+
138
+ ## 3d. Which modules need an engine character, which take a sprite or any position
139
+ Tried with a `pixelSprite` mesh and a `Character` whose `model` is one (`threedog new-game name --pixel` is the starting game). Each row below was run once in a real browser, in a few lines; "not run" means only the docs were read.
140
+ | Module | On a sprite / plain object / position | Result |
141
+ |---|---|---|
142
+ | `characters` (`createPlayer`, `new Character`, `walkTo`, `onPose`) | the sprite is the character's `model` | works: moves, collides, `state` and `facing` drive `onPose`; `walkTo` on an NPC character walked there |
143
+ | `interactions.add(object, ...)` | any mesh or sprite, no character | works: E near it, `once`, `counter`, saved as used |
144
+ | `dialogue` | no object at all (a name and flags) | works: flags are in the save |
145
+ | `triggers.add({ position })` | a position; `who` is the actor or an id | works: fired for the player character |
146
+ | `pickups.spawn(position, { mesh })` | a position and your own mesh; `give` as a function without `inventory()` | spawned with a sprite mesh; collecting: not run |
147
+ | `quests` | steps with `target` an object or `{ x, z }` and `done(e)` | works to start and report steps; a step moved on by a dialogue flag: not run past the flag |
148
+ | `collision.addBlocked(fn)` | a function of x, z (the player was kept in the arena) | works; `addObject(mesh)`: not run |
149
+ | `characters.findPath` | positions | returned a path; `nav.findPath` needs the `nav` module: not run |
150
+ | `audio.sfx`, `audio.tone`, `ambience.add` | no object | ran without error (no sound file named, so nothing audible was checked) |
151
+ | `weather.set`, `calendar.at`, `sky` | no object | installed and started; `weather.set('rain')` kept the name `clear` without a weather table (give the module one), `calendar.at` firing: not run |
152
+ | `makeWindow(engine, opts)` | no object | created a window object (`open`, `toggle`, `remove`) |
153
+ Needs an engine character: `createPlayer`, `walkTo`, `onPose`, schedules, characters' collision and ground. Everything else above takes a position or any `THREE.Object3D`. A sprite that only stands there (a signpost, an NPC that never walks) needs no `Character`; one that walks, follows ground or is scheduled does.
154
+
103
155
  ## 4. Non-character objects (a dog, a windmill, a door)
104
156
  ```js
105
157
  const dog = await engine.assets.model('dog'); engine.add(dog);
@@ -139,7 +191,7 @@ action ends; the animation only shows `t`.
139
191
  alone, so a character's per-frame locomotion cannot override it. `sync(null)` hands control back; the next `go()` switches as usual. Entering a synced
140
192
  state cross-fades like `go()` (the `transitions` table applies).
141
193
  `timing` on the state maps gameplay seconds to clip seconds:
142
- ```js
194
+ ```js fragment
143
195
  const anim = engine.player.anim; // or engine.assets.animate(model, {...})
144
196
  Object.assign(anim.states, {
145
197
  // gameplay: windup 0-0.16, hit 0.16-0.28, recovery 0.28-0.62. The clip raises the sword until 0.24 s and brings it down by 0.5 s:
@@ -163,17 +215,13 @@ engine.onFixed(() => { // one call
163
215
  Use `anim:end` only for presentation (change an expression, play the next clip). Native objects: `anim.mixer` (AnimationMixer), `anim.actions` (clip
164
216
  name -> AnimationAction). Things without a skeleton that only move/rotate as a whole use `engine.timeline.tween`, not an Animator.
165
217
 
166
- Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
218
+ Footsteps: `engine.events.on('character:step', ({ character }) => ...)` hears each foot come down (`character.groundType()` is what it stepped on), and `character:land` each landing; the engine's own footstep sound listens the same way, so yours adds to it. Bones after the pose: `const h = player.onPose((c, dt) => { sword.position.copy(hand.getWorldPosition(v)); })` runs every frame right after the character's pose is
167
219
  applied (clips or procedural rig); `h.remove()` stops it. Presentation only.
168
220
 
169
221
  ## 6. Verify
170
222
  - `anim.describe()` -> `{ state, clip, time, progress, driven, t, weights }` (clip seconds, 0-1 progress, whether sync drives it, the last gameplay t,
171
223
  each fading state's share); the player's is in `describe().player.anim`.
172
- - In a test: `engine.pause(); anim.go('move'); engine.step(0.4)`, then look at `anim.state` and `anim.actions.get('Walk').getEffectiveWeight()` (all
224
+ - In a test: `engine.haltLoop(); anim.go('move'); engine.step(0.4)`, then look at `anim.state` and `anim.actions.get('Walk').getEffectiveWeight()` (all
173
225
  clip weights sum to 1).
174
226
  - Characters: `describe().player.state` (idle/walk/run...) matches `engine.player.anim.state`.
175
227
  - `anim.check([...actions])` is `[]`.
176
- - Related tests: `npm test -- "Animation state machine"` (in the engine repository: two-bone figure built in code by `makeRig()`, in
177
- `packages/engine/tests/vehicle/`), `npm test -- 骨骼动画链路` (a real CC0 glTF character, `packages/engine/tests/anim/`: manifest mapping, cross-fade, sync, alignment of the
178
- slash with the hit phase, dev warnings) and `npm test -- 骨骼动画最小链路` (a skinned GLB generated in code by `tests/anim/rig.js` through GLTFExporter,
179
- loaded like a file: manifest mapping, `check`, sync holding the pose against frame time).
@@ -1,5 +1,7 @@
1
1
  # Custom module
2
2
 
3
+ **In this recipe**: 1. Template (example: stamina, in the game as `stamina.js`) · Type: what the module may own · 2. Hooks and order cheat sheet · 3. Extra steps when it goes into the engine · 4. Verify
4
+
3
5
  When to write a module: a "mechanic" that has its own state, per-frame logic and saving (stamina, a heat meter, wave spawning, oxygen, a combo
4
6
  counter). The contracts every module should follow (state, game time, skip, describe, ops) and a second copyable module are in
5
7
  `49-game-module-contract.md`; this page is the template and the hook cheat sheet. A module is a file of your game (next to `main.js`, or in `plugins/`);
@@ -14,7 +16,7 @@ import { readParams } from 'threedog';
14
16
 
15
17
  export function stamina(opts = {}) {
16
18
  const PARAMS = { max: { type: 'number', default: 100 }, drain: { type: 'number', default: 20 }, regen: { type: 'number', default: 10 } };
17
- const { max, drain, regen } = readParams('stamina', PARAMS, opts); // a misspelled option throws in dev with the fix; put PARAMS on the module as params to show it in engine.catalog()
19
+ const { max, drain, regen } = readParams('stamina', PARAMS, opts); // a misspelled option throws in dev with the fix (a release build warns once), a wrong type or a missing required option throws in every build; put PARAMS on the module as params to show it in engine.catalog()
18
20
  let e = null, ctx = null, tired = null, shown = -1;
19
21
  const api = {
20
22
  value: max, max,
@@ -46,58 +48,69 @@ export function stamina(opts = {}) {
46
48
  ```
47
49
  Install it: `engine.use(openWorld({ camera: 'follow', ...}), stamina({ max: 80 }))` (dependencies must be installed first). Or put the file in `plugins/` with `export default stamina({ max: 80 })`: plugged with `engine.use` at start, switched off by `plugins.json` `off` (THREE.md, plugins folder).
48
50
 
49
- ## Type: what the module may own (required)
50
- `type` is not when it runs (that is `stage`); it says what the module may own. Missing or unknown throws with the fix. Pick by what it changes:
51
+ ## Type: what the module may own
52
+ `type` is not when it runs (that is `stage`); it says what the module may own. It is optional: a module without one is `'rules'`, game logic. An unknown name throws with the list. Pick by what it changes:
51
53
 
52
- | type | for | refused in dev |
54
+ | type | for | dev warns when it |
53
55
  |---|---|---|
54
56
  | `'rules'` | game logic: save parts, ops, events; may take input, control or the camera for a while. The usual one for a game module | - |
55
- | `'world'` | game state: records, ops, ground / collision / navigation data | drawing (rule R47: no `scene.add`, `renderer.` in its file) |
56
- | `'picture'` | what is seen and heard: picture values, three.js objects, particles, sounds | `ops.define`, writing world records |
57
- | `'ui'` | panels and menus: declares input actions, runs ops | `input.bind` (keys are the game's), `saves.register` (preferences are not game saves) |
57
+ | `'world'` | game state: save parts, records, ops, ground / collision / navigation data; draws nothing | - |
58
+ | `'picture'` | what is seen and heard: picture values, three.js objects, particles, sounds | defines an op, writes world records |
59
+ | `'ui'` | panels and menus: declares input actions, runs ops | writes world records, binds keys (`input.bind`; keys are the game's), registers a save part (preferences are not game saves) |
58
60
  | `'actor'` | characters and their control | - |
59
61
  | `'net'` | multiplayer: remote characters, the transport | - |
60
62
  | `'tool'` | a one-shot job that undoes itself (a photo, a bake) | - |
61
63
 
62
64
  No subtypes: inside a type the differences are declarations (`provides`, `requires`, `ctx.mod` values, material slots, post stage, sounds).
63
65
  A module that does two kinds of thing is two definitions returned together (`weather()` returns the `weather` state and the `weatherDraw` drawing part;
64
- `engine.use(weather())` installs both). The refusal names the module, its type, what it did, why not, and the fix; copy the fix.
66
+ `engine.use(weather())` installs both). The warning comes once and refuses nothing: it names the module, its type, what it did, why not, and the fix. A game's own module may do what it needs; a split into two modules is usually the fix.
65
67
 
66
68
  ## 2. Hooks and order cheat sheet
67
69
  - `install(e, ctx)` returns the public object; `init(e, ctx)` (may be async) prepares at start; `ctx.track(handle)` ties a listener or timer to
68
70
  the module (next bullet but four); while `isReady(e)` returns false the loading screen waits for it
69
- (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e)` (may be async) runs after a save loaded, to rebuild
70
- what the loaded state needs nearby, with gameplay frozen until it resolves.
71
+ (the hook is called isReady; `ready` is always a boolean property in the engine); `afterLoad(e, turn)` (may be async; recipe 20 says what `turn` is for) runs after a save loaded, to rebuild
72
+ what the loaded state needs nearby, with gameplay frozen and ops refused (`'loading'`) until it resolves. It rebuilds by writing state directly, inside
73
+ `e.ops.allow(...)` when the write is guarded, not through `e.ops.run`.
71
74
  - `fixed(dt, e)` movement, timing, gameplay keys (`input.pressed` read in fixed is this step's snapshot, independent of frame rate); `frame(dt, e)`
72
75
  animation, camera, UI (it reads this frame's latest input); `afterRender(dt, e)` after rendering.
73
76
  - `describe(e, ctx)`: see recipe 49 contract 4; `ctx.near(object or {x,z}, { name, kind })` reports things nearby. `skip(dt, e, done)`: recipe 49 contract 3.
74
- - `applyState(e, p)`: called by `engine.applyState` / URL parameters; it only receives the keys `time`, `weather` and `cutscene`.
77
+ - `applyState(e, p)`: called by `engine.applyState` / URL parameters with the keys `time`, `season`, `weather`, `cutscene`, `play` and `at` (core handles the rest); `stateKeys: ['time']` lists what the module handles, and it refuses with `{ refused: { key: reason } }`.
75
78
  - `stage`: only when the hooks run (first -> last): `control` timeline, camera -> `ground` terrain, level -> `environment` weather, sky, water -> `gameplay`
76
79
  interactions, dialogue -> `effects` particles, objective markers -> `late` (the default) characters, physics -> `audio` music. Within
77
- a stage, to read another module's result for this frame, write `after: ['its-name']` (or `before`); across stages the stage always wins, so a
80
+ a stage, to read another module's result for this frame, write `after: ['its-name']` (or `before`). The name may be a capability, `after: ['ground']`: whichever module provides it
81
+ now, so the order survives a `replaces`. Across stages the stage always wins, so a
78
82
  `before` / `after` that contradicts it (a `control` module `after` an `audio` one) makes `engine.use` throw `module-order` naming both modules: give
79
83
  them the same stage or drop the line. `engine.use(a, b)` is all-or-nothing: if `b` fails, nothing of `a` stays installed.
84
+ - Installed is not running: `engine.has('nav')` says it is installed; after `await engine.loading.settled()`, `engine.explain({ module: 'nav' })` says whether it runs and, if not, why.
85
+ - A module with `provides: ['inventory']`, or one another module `requires`, is checked in dev against that capability's contract when it binds: a missing method is one
86
+ `module-contract` warning and a line in `engine.catalog(name).problems`. The module still runs: only the game knows which calls it makes.
80
87
  - Between modules: notify with `e.events.emit('stamina:empty')` and let others `on` it; use optional dependencies as `e.hud?.` and list them in
81
88
  `optional: ['hud']` (for engine modules R16 of `npm run check` verifies this). Never import another module's files directly.
82
89
  - A module the game cannot run without sets `critical: true`: if its `init` fails, `engine.start()` rejects with the module name and reason (default
83
90
  false: a failed init is reported and start goes on). A module installed after start gets no `fixed` / `frame` before its `init` finished:
84
- `engine.moduleStates` shows `initializing` / `running` / `failed`, and `await engine.loading.settled()` waits for it. A module whose `isReady` never
91
+ `engine.explain({ module })` shows `initializing` / `running` / `failed`, and `await engine.loading.settled()` waits for it. A module whose `isReady` never
85
92
  turns true makes `start()` reject after `engine.loading.timeoutMs` (default 120 s), naming it.
86
93
  - The `type` decides what an error does: in a `picture` or `ui` module (gameplay works without it) an error in a hook only switches that module off
87
- (`module:disabled`, listed in `engine.disabledModules`); in any other type it freezes the game in development/tests and is recorded in `engine.error`.
94
+ (`module:disabled`, listed in `describe().disabledModules`); in any other type it freezes the game in development/tests and is recorded in `engine.error`.
95
+ - `requires` means the provider works, not only that it is installed: until a required provider runs, the module is `'blocked'` in `engine.explain({ module })` (no init, no hooks) and `engine.catalog(name).blockedBy` says on what. If it can live without the provider, list it in `optional` instead. A `critical` module blocked by a failure stops `start()`.
96
+ - Whatever the module registers goes through `ctx`: `ctx.ops.define`, `ctx.saves.register`, `ctx.ui.define`, `ctx.stream.addReadyCheck`, `ctx.budget.metric`, `ctx.things.addSource` / `explainWith`,
97
+ `ctx.ground.provide` / `addColliders`. They take the same arguments as the engine call, and `engine.catalog(name).resources` lists them. They leave with the module, so `engine.unuse` then
98
+ `engine.use` of the same module works; a save part's data stays in the save and goes back to the part when it registers again.
88
99
  - Listeners and timers the module adds go through `ctx.track(...)`: `ctx.track(e.events.on('item:add', fn))`, also `onFixed` / `onFrame` /
89
100
  `clock.after` / `audio.measure` / a `makeWindow` window, anything with `remove()`. They leave with the module: when its `engine.use(...)` batch
90
- rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook (the spec `npm test -- "Lifecycle: every built-in"`
91
- checks every engine module). A class the module builds takes `ctx.track` as a constructor argument. DOM listeners use
101
+ rolls back, when its `init` fails, and on `engine.dispose()` before its `dispose` hook (the spec `threedog test "Lifecycle: every built-in"`
102
+ checks every engine module). A class the module builds takes `ctx` as a constructor argument. DOM listeners use
92
103
  `addEventListener(type, fn, { signal: engine.signal })`, and UI elements attach to `engine.uiRoot` (not `document.body`); scene GPU memory,
93
104
  jobs and stream entries are collected by `engine.dispose()`. The `dispose(e)` hook only collects what the core can't, such as Workers, the
94
105
  physics world, WASM objects and real-time timers, and is called in reverse install order.
106
+ - Your data in a replaceable provider: `ctx.feeds('collision', () => addMyWalls())` runs before the `use()` of a new holder returns.
107
+ - Foundation slots are the ones a running game cannot swap: `world` alone, because it owns every record. Choose your own holder before `start()`; every other slot takes `replaces` at any time.
95
108
  - A module's changes to shared values go through `ctx.mod(point, { mul: 0.8, layer: 'effect' })` (= `ctx.track(e.mod(point, { owner: ctx.name, ... }))`),
96
109
  so they leave with it too. A module that must be the only one of its kind declares `provides: ['inventory']`; others `requires: ['inventory']`
97
110
  (a capability, never a module name), and a game swaps it with `engine.use(mine(), { replaces: 'inventory' })` (`55-mods-time-wrap.md`). `engine.unuse('name')` removes a module with nothing in its place, and refuses while another still requires it. Picture slots: `62-picture-code.md` 3e:
98
111
  `engine.inventory` is then the new module's API, so the dependents keep working. A missing capability throws naming both fixes: install the
99
112
  engine's part of that name first, or your own module with `provides`.
100
- - `engine.phase` says where the engine is: `'constructed'` -> `'loading'` (start() running: frame hooks run, fixed steps do not, so no game
113
+ - `engine.phase` says where the engine is: `'constructed'` -> `'starting'` (modules init) -> `'loading'` (assets and the world; in both frame hooks run, fixed steps do not, so no game
101
114
  time passes while the machine loads) -> `'ready'` (the world is built; fixed steps from here) -> `'running'` (start() resolved) ->
102
115
  `'disposed'`. `engine.ready` is true in the last two live ones; `engine.step()` while loading runs frame hooks only.
103
116
  - While frozen (`engine.freeze`, flow pause) `fixed` is skipped entirely and `frame` still runs: check `e.frozen` before gameplay decisions.
@@ -110,15 +123,15 @@ A module that does two kinds of thing is two definitions returned together (`wea
110
123
  hand. What cannot be saved ends with its playthrough: a background result goes through `engine.commits` (a load or new game drops old ones;
111
124
  keep `e.commits.epoch` on a queued request and drop it when that changed), and an effect of a running playthrough (an open dialogue, a
112
125
  running cutscene, the music playing) stops on `ctx.track(e.events.on('session:end', ...))`. What is derived from save parts is rebuilt on
113
- `'session:start'` and `'save:loaded'`. A module's `describe()` should show such state: the session spec (`npm test -- Session`) compares every
114
- installed module's describe after two new games, and the Lifecycle spec round-trips the engine's own.
126
+ `'session:start'` and `'save:loaded'`, and what a rollback took down on `'session:failed'`. A `'session:end'` listener only stops things: it starts nothing for the next state. A module's `describe()` should show such state: the session spec (`threedog test "session fresh page"`) compares `describe()` after a new game with a fresh page, and the Lifecycle spec round-trips the engine's own.
115
127
  - When you only need a per-frame callback and no module structure: `const h = engine.onFrame(dt => ...)` / `engine.onFixed`, and `h.remove()` cancels it.
116
128
 
117
129
  ## 3. Extra steps when it goes into the engine
130
+ - Declare a `type`: rule R47 requires it of engine modules, and a `world` module's file draws nothing.
118
131
  - Write the declarations and JSDoc in `index.d.ts` (or `types/*.d.ts`) of the engine package; `npm run types` checks that the exports of index.js are declared.
119
132
  - Hand out a picture as `.material`, `.uniforms`, `.patches` (see `09-materials-lights-models.md` §3), put text in i18n, then `npm run map` to generate API.md + `api/` / CODEMAP.md.
120
133
 
121
134
  ## 4. Verify
122
135
  - `npm run check` (hard rules + types + generated docs up to date).
123
136
  - In a test: watch `stamina.value` in the describe returned by `engine.step(2)`; `engine.saves.collect().parts.stamina` shows the save content.
124
- - Add an automated test: write one entry like those in `tests/specs/*.mjs` and run only it with `npm test -- name`.
137
+ - Add an automated test: write one entry like those in `tests/specs/*.mjs` and run only it with `threedog test name`.
@@ -1,15 +1,11 @@
1
1
  # Performance investigation (F3, budget, profile, describe().perf)
2
2
 
3
+ **In this recipe**: 1. Where things stand · 2. Set a budget · 3. Whose CPU is slow · 4. Common fixes · 4a. Less detail far away · 4b. Render scale · 5. Verify
4
+
3
5
  Order: first use numbers to decide which category is over (frame rate? draw calls? CPU? startup?), then find who takes the most, and after changing,
4
6
  compare before/after with the same method.
5
- Which renderer measures: tests that compare pixels run on software rendering (SwiftShader; numbers only for relative comparison), the others on the GPU when headless can reach it. `threedog shot`, `perf`, `stress` and
6
- `gallery --shots` use the hardware GPU when headless can reach it (`threedog doctor` says whether it can; `--gpu` / `--software` or
7
- `THREEDOG_RENDER=gpu|software` force one). On a machine without one, ask the user to press F3 in the browser (bound by `createEngine({ bindings: { ...presets.bindings.debug } })`; the templates do). Method and reference data: `../PERF.md`.
8
- - **What this machine can carry**: `threedog stress [--only lights,skinned] [--json]` ramps one load at a time (triangles, draw calls, instances, lights,
9
- shadow lights, shadow map size, overlapping transparency, particles, post effects, skinned characters) on a neutral scene until the frame passes 33 ms,
10
- and prints where 16.7 / 33 ms are crossed, with CPU and GPU ms. Turn the row for your target machine into `engine.budget` limits (section 2).
11
- - **Guards in `npm test`**: a loose slowdown alarm (`slowdown`: a fixed scene more than 30% costlier than `tests/perf-baseline.json`) and a
12
- bundle ceiling (`bundle size`: the blank template's gzip JS); both name what to look at when they fail.
7
+ Which renderer measures: `threedog shot`, `perf`, `stress` and `gallery --shots` use the hardware GPU when headless can reach it (`threedog doctor` says whether it can; COMMANDS.md, `--gpu`). On a machine without one, ask the user to press F3 in the browser (bound by `createEngine({ bindings: { ...presets.bindings.debug } })`; the open-world template does).
8
+ What this machine can carry: `threedog stress` (COMMANDS.md) prints where 16.7 / 33 ms are crossed for each kind of load. Turn the row for your target machine into `engine.budget` limits (section 2).
13
9
 
14
10
  ## 1. Where things stand
15
11
  - **One report with verdicts**: `engine.inspect.perf()` / `threedog inspect perf` (MCP `inspect` target `perf`): draw calls (shadow and post passes
@@ -22,14 +18,12 @@ Which renderer measures: tests that compare pixels run on software rendering (Sw
22
18
  `'off'` restores. For real GPU timings use `threedog capture` (Spector.js) or the browser's GPU profiler.
23
19
  - **Other view modes and the panel**: `debug.view('triggers')` shows hidden zones (`triggers({ debugColor, debugOpacity })` colors them); modules add their own modes (`engine.debug.defineView(name, { what, apply })`)
24
20
  and `engine.debug.viewModes()` lists every mode. `engine.debug.panel` is the F3 panel (dev builds; null without the `debug()` module).
25
- - **F3 panel** (`debug()` module, included in openWorld, collapsed by default; the action `debugPanel` opens it, `presets.bindings.debug` binds F3): frame rate, CPU ms/frame, draw calls, triangles,
26
- chunks visible/loaded, vegetation instances, chunk upload ms, pending generation, time of day;
27
- with a budget set it also shows over-limit items and startup time; the "20-second stress test" makes the player run forward fast automatically and
28
- reports the average frame rate and the worst frame at the end.
21
+ - **F3 panel** (`debug()` module; `openWorld` installs it in dev builds only, collapsed; the action `debugPanel` opens it, `presets.bindings.debug` binds F3): frame rate, CPU ms/frame, draw calls, triangles,
22
+ chunks, vegetation instances, time of day; with a budget set also over-limit items and startup time.
29
23
  - **Text**: `engine.describe().perf` =
30
24
  `{ fps, cpuMs, cpu, apply, drawCalls, triangles, pixelRatio, budget, startup, stream, batching, jobs, commits, chunks?, vegetation? }`;
31
25
  the perf line of `npm run shot -- / --describe-only` (in headless mode fps/cpu are `-`; look at draw calls and triangles).
32
- - **CPU time of a frame**: `engine.cpuMs` is the main-thread time from input to the end of the afterRender hooks; `engine.cpuPhases` splits it into
26
+ - **CPU time of a frame**: `engine.inspect.perf().cpuMs` is the main-thread time from input to the end of the afterRender hooks; its `cpuPhases` splits it into
33
27
  `fixed` (input + fixed steps), `frame` (frame hooks, stream, jobs), `render` (draw submission, upload of new objects, shader compiles) and `afterRender`.
34
28
  GPU time is not in it. With `npm run perf -- --only=stream` the stream-in numbers below are measured for you.
35
29
  - **Applying background results** (`engine.budget.cost.report()`, also `describe().perf.apply` and the budget categories `applyBuildMs` ...): terrain
@@ -37,11 +31,9 @@ Which renderer measures: tests that compare pixels run on software rendering (Sw
37
31
  trip minus the worker's own compute: queueing and structured clone, an async wait, approximate), `build` (creating the three.js objects), `collider`
38
32
  (physics colliders), `upload` (extra render time of the frames that first draw new objects: GPU upload and shader compile, approximate), `stream`
39
33
  (the synchronous part of a `stream.add` build callback). Per stage: `n`, `totalMs`, `maxMs`, smoothed `frameMs`, and `bytes` (transit).
40
- - **Startup**: `engine.startup` = `{ totalMs, startMs, preloadMs, streamMs, compileMs, firstFrameMs, phases, modules: { name: { init, ready } } }`; `npm test` also prints a
41
- startup line (with the slowest module) for each item. `firstFrameMs` is page open to the first frame drawn after the loading screen, and `phases`
34
+ - **Startup**: `engine.startup` = `{ totalMs, startMs, preloadMs, streamMs, compileMs, firstFrameMs, phases, modules: { name: { init, ready } } }`. `firstFrameMs` is page open to the first frame drawn after the loading screen, and `phases`
42
35
  splits it into parts that add up to it: `script` (page open until `createEngine`), `construct`, `setup` (game code until `start()`), `init` (saves,
43
- renderer, module init), `preload`, `world` (nearby builds), `compile` (shaders + hidden warm-up frame), `draw`. `inspect.perf().text` prints the line;
44
- `threedog perf --only=startup` measures the examples.
36
+ renderer, module init), `preload`, `world` (nearby builds), `compile` (shaders + hidden warm-up frame), `draw`. `inspect.perf().text` prints the line.
45
37
 
46
38
  ## 2. Set a budget (so going over reports itself)
47
39
  Off by default and costs nothing. The game gives the limits in `createEngine` (only the given categories are checked):
@@ -51,7 +43,7 @@ const engine = createEngine({ canvas, budget: { drawCalls: 250, fps: 55, low1: 3
51
43
  const r = engine.budget.report(); // { ok, over: [{ category, value, limit, top }] }; going over also prints one console hint
52
44
  ```
53
45
  `top` lists the biggest draw-call users grouped by an object's `userData.budgetTag`. Tag your own things to see who it is:
54
- ```js
46
+ ```js fragment
55
47
  house.userData.budgetTag = 'houses'; // children inherit the parent's tag; untagged ones count as 'other'
56
48
  engine.budget.byTag(); // [{ tag, drawCalls, triangles }...], largest first
57
49
  engine.budget.metric('fishCount', () => fish.length, { limit: 50 }); // a module's own category
@@ -84,12 +76,42 @@ false = all on the main thread, same results.
84
76
  - Your own worker script: `engine.threads.lane({ create: () => new Worker(new URL('./w.js', import.meta.url), { type: 'module' }), local: makeHandler })`;
85
77
  the worker file is `serve(makeHandler())` from `threedog/worker`. Results that change gameplay go through `engine.commits`.
86
78
 
87
- **Two worker rules** (full text and examples in `../CONVENTIONS.md`, "Worker limits"):
88
- - `engine.commits`: when the due tick comes and the worker has not replied, the main thread runs your `fallback()` and applies that (a later reply is
89
- ignored). The engine does not clear pending requests on save load or level change, so give every request a `valid()` that checks identity
90
- (generation counter, record still exists, same zone) or call `t.remove()`.
91
- - `engine.threads.pure(fn)` / `world.simulate(..., { worker: true })`: the function is recompiled from its source, so it cannot capture outside
92
- variables or imports; put constants inside it. A bad outside variable is reported by name on the first call.
79
+ **Two worker limits**, with examples in `../CONVENTIONS.md`, "Worker limits": `engine.commits` runs your `fallback()` when the worker is late and does not clear pending requests on a load or level change, so give each a `valid()`; `threads.pure` functions are recompiled from source and capture nothing.
80
+
81
+ ## 4a. Less detail far away: which tool for which job
82
+
83
+ Four tools lower the cost of distant things, and each owns a different case. Pick by what is actually over budget: triangles or draw calls.
84
+
85
+ | You have | Use | Saves | Costs |
86
+ |---|---|---|---|
87
+ | A few heavy models (a statue, a vehicle, a tower) | `engine.assets.lod` or `lod: true` | Triangles | Each copy stays its own draw calls |
88
+ | Many copies of a light model (crates, fences) | `engine.batching`, on by default | Draw calls | Every copy keeps full triangles |
89
+ | A static level seen from far off | `engine.hlod` | Draw calls, by merging per cell | Same triangles unless a node `xxx_LOD1` exists |
90
+ | Plants by the thousand | `engine.vegetation` with `lodGeometry` | Both, per chunk ring | Plants only |
91
+
92
+ ```js fragment
93
+ // 1. once: writes public/optimized/tower.lod1.glb, .lod2.glb and lists them in assets.optimized.js
94
+ // threedog assets optimize --lod (--lod-shares 0.5,0.2 sets the triangle share of each level)
95
+ // 2. one line in the game; without it no level is ever downloaded
96
+ const tower = await engine.assets.lod('tower'); // distances follow the model's size
97
+ const gate = await engine.assets.lod('gate', { distances: [40, 120] }); // or your own, in meters
98
+ // content/props.js: { model: 'tower', x: 10, z: 4, collide: 'box', lod: true } // or lod: [40, 120]; also on a template
99
+ tower.levels[1].object; // a plain THREE.LOD: read, replace, tower.addLevel(...), tower.autoUpdate = false
100
+ ```
101
+
102
+ - **Batching:** instances share one geometry, so a copy cannot change level alone. A LOD object is never batched, which means `lod` on a model placed many times can
103
+ cost more than it saves. Compare `describe().perf` with and without it; dev warns at 32 copies.
104
+ - **What stays on the full model:** `engine.raycast`, `engine.rays`, your own `THREE.Raycaster`, `collision` and saves. A level draws with the full mesh's material, so swap
105
+ materials on `tower.levels[0].object` and on each level.
106
+ - **Asking what is drawn:** far off the full model waits on the batch layer with `visible` true, so read `tower.getCurrentLevel()`, not `tower.levels[0].object.visible`.
107
+ - **Skipped by the tool, with the reason in its report:** skinned, morphing and animated models, and models under 1000 triangles. `assets.lod` still works on them: one level, and a
108
+ dev warning.
109
+ - **The level follows `engine.camera`** only, so a shadow pass does not change it. `delete tower.update`, while level 0 shows, restores the plain method; far rays then miss the full model.
110
+ - **A narrow lens:** `camera.zoom` counts towards the distance, `camera.fov` does not. A sniper scope that narrows `fov` shows the far level up close, so use `zoom` or set
111
+ `tower.autoUpdate = false` while scoped.
112
+ - **Check the last level up close once:** a low level can lose round details (a dial, a dome) that a few dozen pixels hide and a scope shows. If it shows, raise `--lod-shares` or move the distance out.
113
+ - **Popping:** levels switch at once, softened by a hysteresis of 0.1 of the distance (`hysteresis` changes it). There is no crossfade; if a switch shows, move the distance out.
114
+ - **Scale:** default distances follow a prop's `scale`. On `assets.lod` they follow the model as loaded, so give `distances` when you scale it yourself.
93
115
 
94
116
  ## 4b. Render scale (resolution) is never lowered silently
95
117
  - Default render scale: `min(devicePixelRatio, 1.5)`; the low tier uses at least 0.75 x devicePixelRatio (a 2x laptop screen gets 1.5, not 1), never above 1.5.
@@ -97,11 +119,12 @@ false = all on the main thread, same results.
97
119
  than the target allows (main-thread time, plus GPU time where the browser has the timer query; without it, a low fps that is not just the display's own
98
120
  refresh). The first 3 s after ready and frames that compile shaders are not judged, and a display or power mode locked at 30 Hz is not overload. The first
99
121
  time it lowers, dev builds warn once: `render scale X -> Y because frames cost N ms ...; turn off with adaptiveResolution: false`. It is the only thing
100
- lowered automatically (shadows and post are never traded first).
101
- - `describe().render.scale`: `{ current, devicePixelRatio, upscaled, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
122
+ lowered automatically (shadows and post are never traded first). `engine.setPixelRatio(p)` sets the top it climbs back to, so a ratio the game chose stays; a direct
123
+ `renderer.setPixelRatio` stops it altogether, and so does `pixelSize` (recipe 62 section 4b).
124
+ - `describe().render.scale`: `{ current, devicePixelRatio, upscaled, pixelSize, autoLowered, adaptive, floor, max }`. `upscaled: true` means current < devicePixelRatio, the picture
102
125
  is softer than the screen: if that looks wrong in a screenshot, check this before the style. Fixed quality: `pixelRatio: n` plus `adaptiveResolution: false`.
103
126
 
104
127
  ## 5. Verify (once before and once after, under the same conditions)
105
- - `npm run perf` (native vs engine vs per-module cost of openWorld), compared with the tables in `../PERF.md`; differences under 10-30% are noise.
128
+ - `npm run perf` (native vs engine vs per-module cost of openWorld), run before and after on the same machine; differences under 10-30% are noise.
106
129
  - Compare a specific scenario: `npm run shot -- / --pos x,z --time 12:00 --describe-only` to see draw calls and triangles.
107
- - Related tests: `npm test -- 性能预算`, `npm test -- 阴影`, `npm test -- startup time`. Attach the before/after numbers when reporting.
130
+ - Attach the before/after numbers when reporting.