threedog 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -1,6 +1,7 @@
1
1
  // Props (each item of content/props.js): data is a plain record in engine.world with kind 'prop'; model and collision are "presentation that exists only when
2
2
  // near".
3
- // record: { id, kind: 'prop', position: {x,y,z}, model, rot?, scale?, collide?, occluder?, offsetY?, static?, batch?, zone? } (plain values only)
3
+ // record: { id, kind: 'prop', position: {x,y,z}, model, rot?, scale?, ground?, collide?, occluder?, offsetY?, static?, batch?, source?, zone? } (plain values only)
4
+ // rot = the entry's rot plus its place's. source names the arrangement an entry was copied from: a tag for world.query, nothing at runtime reads it.
4
5
  // Initial world data (initial: true on add): the save records only moves / removals, independent of content.load running before or after loading a save;
5
6
  // positions using level markers carry a zone (data is kept across level changes).
6
7
  // id: the written id if content gives one; otherwise `prop:<model name>:<index in this props array>` (same on every load of the same content, no collisions).
@@ -12,14 +13,15 @@
12
13
  // collision: built / torn down with the model (only things near the player need to block), so props beyond the collision radius take no space in the collision
13
14
  // table.
14
15
  // An entry with template (instead of model) is an instance of a content template: see templates.js.
15
- import { buildModel, settle, fitKey, unbuildModel } from './models.js';
16
+ import { buildModel, settle, fits, unbuildModel } from './models.js';
16
17
  import { placeTemplate } from './templates.js';
17
18
  import { srcOf } from './ids.js';
18
- import { placeY } from '../../core/ground.js';
19
- import { list, PLACEMENT_FIELDS, collideProblem } from './rules.js';
20
- import { DEV, fmt, closest } from '../../core/validate.js';
21
- import { codedError } from '../../core/errorHints.js';
22
-
19
+ import { placeY } from '../../core/scene/ground.js';
20
+ import { isTilted, tiltError } from './models.js';
21
+ import { PLACEMENT_FIELDS, collideProblem } from './rules.js';
22
+ import { list } from '../../core/base/util.js';
23
+ import { DEV, fmt, closest } from '../../core/base/validate.js';
24
+ import { codedError } from '../../core/base/errorHints.js';
23
25
 
24
26
  /** Stable id of a prop: the written id if given, otherwise "model name + array index" */
25
27
  const propId = (p, i) => p.id ?? `prop:${list(p.model)[0]}:${i}`;
@@ -37,16 +39,19 @@ export function addProps(e, api, props, st, zoneOf, ids) {
37
39
  if (p.grid) return placeGridItem(e, p, i, zoneOf(p), ids, at); // a pre-placed grid item (grid module)
38
40
  const collide = collideProblem(p.collide);
39
41
  if (collide) throw codedError('content-misuse', `props[${i}] (model ${JSON.stringify(p.model)}): collide ${collide}`);
40
- const id = propId(p, i), { x, y, z } = api.where(p), zone = zoneOf(p), floor = api._floorOf(p);
42
+ if (p.collide && isTilted(p) && !e.collider3d) throw tiltError({ ...p, id: p.id });
43
+ const id = propId(p, i), free = p.ground === false, { x, y, z } = api.where(free ? { ...p, y: undefined, floor: undefined } : p), zone = zoneOf(p), floor = api._floorOf(p);
41
44
  if (p.id != null) ids.claim(p.id, `props[${i}] (model ${JSON.stringify(p.model)})`);
42
45
  // compute y from the ground now (same as when the model is built): unmoved props equal the content and stay out of the save
43
- const def = { id, kind: 'prop', position: { x, y: y ?? placeY(e, `props[${i}] (model ${JSON.stringify(p.model)})`, x, z), z }, model: p.model };
44
- for (const k of ['rot', 'scale', 'collide', 'occluder', 'static', 'batch']) if (p[k] !== undefined) def[k] = p[k];
45
- if (p.y) def.offsetY = p.y;
46
+ const def = { id, kind: 'prop', position: { x, y: free ? p.y ?? 0 : y ?? (placeY(e, `props[${i}] (model ${JSON.stringify(p.model)})`, x, z)), z }, model: p.model };
47
+ for (const k of ['scale', 'ground', 'collide', 'occluder', 'static', 'batch', 'lod', 'source']) if (p[k] !== undefined) def[k] = p[k];
48
+ const rot = api._facingOf(p);
49
+ if (rot !== undefined) def.rot = rot;
50
+ if (p.y && !free) def.offsetY = p.y;
46
51
  if (floor !== undefined) def.floor = floor; // kept so a moved prop lands on the same storey
47
52
  if (zone != null) def.zone = zone;
48
53
  const rec = world.add(def, { initial: true });
49
- if (rec && (rec.kind !== 'prop' || JSON.stringify(rec.model) !== JSON.stringify(p.model))) throw codedError('pickup-prop-id', `Prop id "${id}" is already used by other data (${rec.kind}${rec.model ? ' ' + JSON.stringify(rec.model) : ''}): give this item a different id, e.g. { id: '${id}-2', model: ... }`);
54
+ if (rec && (rec.kind !== 'prop' || JSON.stringify(rec.model) !== JSON.stringify(p.model))) throw codedError('world-id', `Prop id "${id}" is already used by other data (${rec.kind}${rec.model ? ' ' + JSON.stringify(rec.model) : ''}): give this item a different id, e.g. { id: '${id}-2', model: ... }`);
50
55
  if (DEV) world.setOrigin(id, { definedAt: at, model: p.model });
51
56
  });
52
57
  }
@@ -73,13 +78,13 @@ function placeGridItem(e, p, i, zone, ids, at) {
73
78
  ids.claim(p.id, `props[${i}] (grid ${p.grid} item ${p.item})`);
74
79
  const { kind, fields } = e.grids.placement(p.grid, p.item, p.cell, p.rotation ?? 0);
75
80
  const rec = e.world.add({ id: p.id, kind, ...fields, ...structuredClone(p.fields ?? {}), ...(zone != null && { zone }) }, { initial: true });
76
- if (rec && rec.kind !== kind) throw codedError('pickup-prop-id', `grid item id "${p.id}" is already used by other data (kind ${rec.kind}): give it a different id`);
81
+ if (rec && rec.kind !== kind) throw codedError('world-id', `grid item id "${p.id}" is already used by other data (kind ${rec.kind}): give it a different id`);
77
82
  if (DEV) e.world.setOrigin(p.id, { definedAt: at });
78
83
  }
79
84
 
80
85
  /** Dev error when the world module is not installed */
81
86
  export function needWorld(e) {
82
- if (!e.world) throw codedError('world-missing', 'content has props or pickups, whose data is stored in world: call engine.use(world()) first (the openWorld() preset already installs it)');
87
+ if (!e.world) throw codedError('module-needs', 'content has props or pickups, whose data is stored in world: call engine.use(world()) first (the openWorld() preset already installs it)');
83
88
  return e.world;
84
89
  }
85
90
 
@@ -87,12 +92,12 @@ export function needWorld(e) {
87
92
  function presentProps(e, api, world, st) {
88
93
  if (st.propsPresenter) return;
89
94
 
90
- st.propsPresenter = world.present('prop', {
95
+ st.propsPresenter = st.track(world.present('prop', {
91
96
  // build by view distance: follows the terrain view distance (fog distance if no terrain), also when changed at runtime
92
97
  radius: () => Math.max(world.radius, e.stream.activeRadius),
93
98
  build: rec => buildModel(e, api, rec, rec.model, rec), // a failed model generation is reported by world (does not block loading), retried when near again
94
99
  // moved / rot or scale changed (world.move sends no event, so compare here): world already put the model at the new position; collision and rays follow
95
- update(rec, o) { if (o.userData.fit !== fitKey(rec)) settle(e, rec, o, rec); },
100
+ update(rec, o) { if (!fits(e, o, rec)) settle(e, rec, o, rec); },
96
101
  dispose: (rec, o) => unbuildModel(e, o),
97
- });
102
+ }));
98
103
  }
@@ -1,5 +1,5 @@
1
1
  // Content vocabulary: the "conditions" and "effects" that content files (content/*.js) can use. Shared by the loader, the validator packages/tools/content-check.mjs and the map packages/tools/gamemap.mjs.
2
- // Plain data + small functions, no import of three or the engine (the validator reads it directly in node). Real execution is in loader.js.
2
+ // Plain data + small functions, no import of three and nothing from the engine but node-safe core/base/util.js (the validator reads it directly in node). Real execution is in loader.js.
3
3
  //
4
4
  // Conditions (quest step done, dialogue option if, line variant if): several items in one object must all hold; array = every item holds
5
5
  // { flag: 'metFisher' } { notFlag: 'x' } { has: { berry: 3 } } { lacks: { film: 6 } } { counter: { sunsetPhotos: 1 } }
@@ -19,14 +19,17 @@
19
19
  //
20
20
  // Game content kinds: the same content/rules.js may export kinds: { name: { desc, load, check, map } }, so a game keeps its own data
21
21
  // (enemies, recipes, loot tables, waves, shop stock) in content/<name>.js. The loader, content-check and GAMEMAP all read this one table:
22
- // desc one line (map, file list) · load(e, data, content) hands the data to the game when engine.content.load runs (required)
22
+ // desc one line (map, file list) · load(e, data, content) hands the data to the game when engine.content.load runs (optional: a game that imports the file itself needs none)
23
23
  // check(data, ctx) optional validation in npm run check: ctx.err(msg) / ctx.warn(msg); ctx.data is all content (items, npcs…), ctx.known(obj) lists ids
24
24
  // map(data) optional GAMEMAP lines (default: the number of entries and their ids)
25
- // fields optional { key: 'int?' | { type, min, max, values, desc } } (core/params.js format, no default): the keys of each entry; content-check
25
+ // fields optional { key: 'int?' | { type, min, max, values, desc } } (core/base/params.js format, no default): the keys of each entry; content-check
26
26
  // reports unknown keys (did you mean), wrong types, out of range, and missing required keys; engine.content.fields(name) returns it
27
27
  // export default { kinds: { recipes: { desc: 'crafting recipes (id -> { needs: { item: n }, makes })', load: (e, data) => e.crafting.add(data),
28
28
  // check: (data, ctx) => { for (const [id, r] of Object.entries(data)) if (!ctx.data.items?.[r.makes]) ctx.err(`recipe ${id} makes unknown item ${r.makes}`); } } } };
29
29
 
30
+ import { list, isObject } from '../../core/base/util.js';
31
+ import { sectionDocs, sectionEffects } from '../../core/inspect/metadata.generated.js';
32
+
30
33
  const counts = o => Object.entries(o || {}).map(([k, n]) => `${k}×${n}`).join('、');
31
34
  const opText = v => Array.isArray(v) ? `${v[0]}${v[1] ? ' ' + Object.entries(v[1]).map(([k, x]) => `${k}=${x}`).join(' ') : ''}` : String(v);
32
35
  const posText = v => typeof v === 'string' ? v : v.place ? `${v.place}${v.x || v.z ? `(${v.x ?? 0},${v.z ?? 0})` : ''}` : `(${v.x},${v.z})`;
@@ -45,81 +48,64 @@ const RULE_STRINGS = {
45
48
  give: { ref: 'itemCounts', desc: 'give items', describe: v => `give ${counts(v)}` },
46
49
  take: { ref: 'itemCounts', desc: 'take items', describe: v => `take ${counts(v)}` },
47
50
  bump: { ref: 'counter', desc: 'counter +1', describe: v => `counter ${v}+1` },
48
- startQuest: { ref: 'quest', desc: 'start a quest', describe: v => `start quest ${v}` },
49
51
  toast: { ref: 'text', desc: 'show a toast', describe: v => `toast "${v}"` },
50
52
  particles: { ref: 'particles', desc: 'play particles', describe: v => `particles ${v.name}×${v.count ?? ''}` },
51
53
  marker: { ref: 'position', desc: 'add an objective marker (hud module)', describe: v => `marker ${posText(v)}${v.label ? `"${v.label}"` : ''}` },
52
- clearMarker: { ref: 'position', desc: 'remove an objective marker', describe: v => `remove marker ${posText(v)}` },
54
+ // raw: the value names the marker (content-check still reads it as a place); a place that is gone, on a level left behind, must not stop the clearing
55
+ clearMarker: { ref: 'position', raw: true, desc: 'remove an objective marker', describe: v => `remove marker ${posText(v)}` },
53
56
  op: { ref: 'op', desc: "run a game op (engine.ops.run); the game's own actions are ops", describe: v => `op ${opText(v)}` },
54
57
  },
55
- // content file name -> description (only these files are recognized in content/)
56
- files: {
57
- items: 'items (id -> name, icon, description); also export startItems for starting items',
58
- pickups: 'pickups on the ground (list)',
59
- containers: 'chests / shelves (container id -> { capacity, items: starting goods }; starting goods are placed only the first time, then saved)',
60
- npcs: 'NPCs (id -> name, schedule, dialogue)',
61
- dialogues: 'dialogues (id -> speaker, nodes)',
62
- quests: 'quests (id -> title, steps, reward; a step can have a target position)',
63
- actions: 'own key actions of the game (action name -> default key, label)',
64
- places: 'place names (coordinates computed at runtime in main.js)',
65
- triggers: 'trigger zones (tag -> position / from level, enter/exit effects)',
66
- level: 'level markers (spawn point, NPCs, trigger zones)',
67
- vegetation: 'vegetation (name -> model, growth rule)',
68
- props: 'props (list: model, position, facing, collision; or { template, x, z } = an instance of a template; or { id, grid, item, cell } = a grid item), streamed in on demand',
69
- templates: 'reusable objects (name -> model, collide, interact, container, sound, animate, state defaults, physics body); shared read-only definitions',
70
- audio: 'sounds by asset name, ambience and music rules as data, footsteps (sounds, ambience, music: { tracks, rules }, footsteps)',
71
- views: 'named fixed camera views (name -> { position: [x, y, z], target?: [x, y, z], fov? }); engine.views.show(name), ?view=name, npm run shot -- -w game --view name',
72
- grids: 'placement grids (name -> { cell, origin, size, zone?, flat? }); layout rules, not saved',
73
- renames: "renamed or deleted authored ids (old id -> new id, or null = deleted on purpose): the player's saved changes follow the new id",
74
- rules: 'condition words added by the game ({ conditions }); actions are ops, not effect words',
75
- },
76
- // Placement fields: the keys one entry of a content file may have, in the core/params.js spec format. Declared once here, read by the loader
58
+ // Placement fields: the keys one entry of a content file may have, in the core/base/params.js spec format. Declared once here, read by the loader
77
59
  // (unknown keys), content-check (unknown keys with did-you-mean, wrong type, out of range, not in values) and engine.content.fields() (an editor
78
60
  // panel's rows), so the three cannot drift apart. props has three entry shapes: a plain model ('props'), a template instance ('props.template',
79
61
  // plus the template's state fields) and a grid item ('props.grid'). Required-ness of x / z / model is checked by the content rules themselves
80
62
  // (x, z are optional when place is given), so they are marked optional here.
81
63
  fields: (() => {
82
64
  const at = {
83
- place: { type: 'string', optional: true, desc: 'place name (places.js / level marker); x and z are then offsets from it' },
65
+ place: { label: 'Place', rare: true, type: 'string', optional: true, desc: "place name (places.js / level marker); x and z are then offsets from it and turn with the place's rot" },
84
66
  x: { type: 'number', optional: true, desc: 'meters along x (offset from place when place is given)' },
85
67
  z: { type: 'number', optional: true, desc: 'meters along z (offset from place when place is given)' },
86
- floor: { type: 'number', optional: true, desc: 'reference height of the storey it stands on (multi-layer ground)' },
87
- y: { type: 'number', optional: true, desc: 'meters above the ground it stands on' },
68
+ floor: { label: 'Storey height', rare: true, type: 'number', optional: true, desc: 'reference height of the storey it stands on (multi-layer ground)' },
69
+ y: { label: 'Height', type: 'number', optional: true, desc: 'meters above the ground it stands on (the height itself when ground is false)' },
88
70
  };
89
71
  const pose = {
90
- rot: { type: 'number', optional: true, desc: 'facing around the vertical axis, radians' },
91
- scale: { type: 'number', optional: true, min: 0, desc: 'uniform scale (1 = model size)' },
72
+ rot: { label: 'Facing', type: 'number|position', optional: true, desc: 'facing around the vertical axis, radians; or [x, y, z] radians to tilt it (a tilted collide needs a collider3d provider)' },
73
+ scale: { label: 'Size', type: 'number|position', optional: true, desc: 'uniform scale (1 = model size), or [x, y, z] per axis' },
92
74
  };
75
+ // a plain tag, so world.query({ where: r => r.source === 'stall' }) finds every copy of one arrangement; nothing else reads it
76
+ const copied = { source: { label: 'Copied from', rare: true, type: 'string', optional: true, desc: 'name of the arrangement this entry was copied from; queryable, no other effect' } };
93
77
  return {
94
78
  props: {
95
79
  id: { type: 'string', optional: true, desc: 'stable id (needed when entries are later inserted in the middle)' },
96
- model: { type: 'any', desc: "model name, or [name, ...args] for a generated model" }, ...at, ...pose,
97
- collide: { type: 'any', optional: true, desc: "collision: 'box', 'circle', { circle: radius, occluder?: false }, or false = none" },
98
- occluder: { type: 'bool', optional: true, desc: 'false = a solid prop the follow camera may pass through (walkers are still stopped)' },
99
- static: { type: 'bool', optional: true, desc: 'never moves (may be merged into one draw call)' },
100
- batch: { type: 'bool', optional: true, desc: 'false = never batch this copy' },
80
+ model: { type: 'any', desc: "model name, or [name, ...args] for a generated model" }, ...at, ...pose, ...copied,
81
+ ground: { type: 'bool', optional: true, desc: 'false = do not snap to the ground: y is the height in the world' },
82
+ collide: { label: 'Collision', rare: true, type: 'any', optional: true, desc: "collision: 'box', 'circle', { circle: radius, occluder?: false }, or false = none" },
83
+ occluder: { label: 'Blocks camera', rare: true, type: 'bool', optional: true, desc: 'false = a solid prop the follow camera may pass through (walkers are still stopped)' },
84
+ static: { label: 'Never moves', rare: true, type: 'bool', optional: true, desc: 'never moves (may be merged into one draw call)' },
85
+ batch: { label: 'Merge copies', rare: true, type: 'bool', optional: true, desc: 'false = never batch this copy' },
86
+ lod: { label: 'Far detail', rare: true, type: 'any', optional: true, desc: 'true = lower-detail levels far away (threedog assets optimize --lod), or rising distances in meters like [40, 120]; such a copy is never batched' },
101
87
  },
102
88
  'props.template': {
103
89
  template: { type: 'string', desc: 'template name (content/templates.js)' },
104
- id: { type: 'string', optional: true, desc: 'stable id; instances with state should have one' }, ...at, ...pose,
105
- items: { type: 'object', optional: true, desc: "starting goods of the instance's container { itemId: count }" },
90
+ id: { type: 'string', optional: true, desc: 'stable id; instances with state should have one' }, ...at, ...pose, ...copied,
91
+ items: { label: 'Starts with', rare: true, type: 'object', optional: true, desc: "starting goods of the instance's container { itemId: count }" },
106
92
  },
107
93
  'props.grid': {
108
94
  id: { type: 'string', desc: 'stable id (the player can move or pick it up)' },
109
95
  grid: { type: 'string', desc: 'grid name (content/grids.js)' },
110
96
  item: { type: 'string', desc: 'grid item name' },
111
97
  cell: { type: 'position', desc: 'grid cell [col, row]' },
112
- rotation: { type: 'int', optional: true, values: [0, 1, 2, 3], desc: 'quarter turns' },
113
- fields: { type: 'object', optional: true, desc: 'record fields of this copy' },
98
+ rotation: { label: 'Quarter turns', type: 'int', optional: true, values: [0, 1, 2, 3], desc: 'quarter turns' },
99
+ fields: { label: 'Own fields', rare: true, type: 'object', optional: true, desc: 'record fields of this copy' },
114
100
  },
115
101
  pickups: {
116
102
  id: { type: 'string', optional: true, desc: 'stable id' },
117
103
  item: { type: 'string', desc: 'item id (items.js)' }, ...at,
118
104
  count: { type: 'int', optional: true, min: 1, desc: 'how many one pickup gives' },
119
- data: { type: 'any', optional: true, desc: 'extra data handed to the game' },
120
- radius: { type: 'number', optional: true, min: 0, desc: 'pickup reach in meters' },
121
- auto: { type: 'bool', optional: true, desc: 'taken by walking into it, no key' },
122
- respawn: { type: 'number', optional: true, min: 0, desc: 'seconds until it comes back (0 = never)' },
105
+ data: { label: 'Extra data', rare: true, type: 'any', optional: true, desc: 'extra data handed to the game' },
106
+ radius: { label: 'Reach', rare: true, type: 'number', optional: true, min: 0, desc: 'pickup reach in meters' },
107
+ auto: { label: 'Walk to take', rare: true, type: 'bool', optional: true, desc: 'taken by walking into it, no key' },
108
+ respawn: { label: 'Comes back after', rare: true, type: 'number', optional: true, min: 0, desc: 'seconds until it comes back (0 = never)' },
123
109
  },
124
110
  views: {
125
111
  position: { type: 'position', optional: true, desc: 'camera position [x, y, z]' },
@@ -142,48 +128,48 @@ const S = RULE_STRINGS;
142
128
  export const CONDITIONS = RULE_STRINGS.conditions;
143
129
  /** Built-in effect words of the engine */
144
130
  export const EFFECTS = RULE_STRINGS.effects;
131
+ /** Every effect word of the engine: the built-in ones and those a section's owner declares, which metadata.mjs reads out for the tools that run without an engine */
132
+ export const ALL_EFFECTS = { ...EFFECTS, ...Object.fromEntries(Object.entries(sectionEffects).map(([k, d]) => [k, { ...d, describe: v => d.describe.replace('{v}', v) }])) };
145
133
  /** ref → ref -> how to write the value */
146
134
  export const REFS = RULE_STRINGS.refs;
147
- /** content file name -> description */
148
- export const CONTENT_FILES = RULE_STRINGS.files;
149
- /** content entry shape -> { key: field spec } (core/params.js format): 'props', 'props.template', 'props.grid', 'pickups', 'views'. Read via fields.js */
135
+ /** content entry shape -> { key: field spec } (core/base/params.js format): 'props', 'props.template', 'props.grid', 'pickups', 'views'. Read via fields.js */
150
136
  export const PLACEMENT_FIELDS = RULE_STRINGS.fields;
151
137
  /** Why a prop's or template's `collide` is wrong, or null. One rule for the load and content-check: a mistyped object must not quietly become a box */
152
138
  export function collideProblem(v) {
153
139
  if (v === undefined || v === false || v === 'box' || v === 'circle') return null;
154
- const form = !!v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).every(k => k === 'circle' || k === 'occluder');
140
+ const form = isObject(v) && Object.keys(v).every(k => k === 'circle' || k === 'occluder');
155
141
  if (form && Number.isFinite(v.circle) && v.circle > 0 && (v.occluder === undefined || typeof v.occluder === 'boolean')) return null;
156
142
  return `must be one of false, "box", "circle" or { circle: radius in meters above 0, occluder?: false }, got ${JSON.stringify(v)}`;
157
143
  }
144
+ /** Why a place cannot load, or null: a turned place moves everything standing on it, so a bad rot stops at the load and in content-check alike */
145
+ export const placeProblem = p => p?.rot !== undefined && !Number.isFinite(p.rot) ? `rot must be a number of radians about Y, got ${JSON.stringify(p.rot)}` : null;
158
146
  /** Clock time notation 'HH:MM' (24-hour) */
159
147
  export const CLOCK_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
160
148
 
161
149
  /** Merge the engine vocabulary and the game vocabulary (default export of the game's content/rules.js) -> { conditions, effects }. Games add conditions only */
162
150
  export function mergeRules(game = {}) {
163
- return { conditions: { ...CONDITIONS, ...game.conditions }, effects: EFFECTS };
151
+ return { conditions: { ...CONDITIONS, ...game.conditions }, effects: ALL_EFFECTS };
164
152
  }
165
- /** Every content name a game may use: the engine's files plus the game's kinds (rules.js kinds) -> description; the one list loader, content-check and GAMEMAP share */
153
+ /** Every content name a game may use: the engine's sections plus the game's kinds (rules.js kinds) -> description; the one list loader, content-check and GAMEMAP share */
166
154
  export function contentFiles(game = {}) {
167
- const out = { ...CONTENT_FILES, startItems: 'starting items (exported from items.js)' };
155
+ const out = { ...sectionDocs };
168
156
  for (const [name, k] of Object.entries(game?.kinds || {})) out[name] ??= k?.desc || 'game data kind';
169
157
  return out;
170
158
  }
171
- /** Problems with a game's kinds table (name clashes with an engine file, no load): a list of messages */
159
+ /** Problems with a game's kinds table (name clashes with an engine file, a load that is no function): a list of messages */
172
160
  export function kindProblems(game = {}) {
173
161
  return Object.entries(game?.kinds || {}).flatMap(([name, k]) => [
174
- ...(CONTENT_FILES[name] || name === 'startItems' ? [`kind "${name}" is an engine content file name: pick another name (engine files: ${Object.keys(CONTENT_FILES).join(', ')})`] : []),
175
- ...(typeof k?.load !== 'function' ? [`kind "${name}" has no load(e, data) function, so its data would never reach the game`] : []),
162
+ ...(sectionDocs[name] ? [`kind "${name}" is an engine content file name: pick another name (engine files: ${Object.keys(sectionDocs).join(', ')})`] : []),
163
+ ...(k?.load !== undefined && typeof k.load !== 'function' ? [`kind "${name}": load must be a function (e, data) => …, or left out when the game imports the file itself`] : []),
176
164
  ]);
177
165
  }
178
166
  /** Error text for a content name that is neither an engine file nor a registered kind */
179
167
  export const unknownContent = (name, game) => `unknown content "${name}". Known: ${Object.keys(contentFiles(game)).join(', ')}. `
180
- + `For the game's own data, register it in content/rules.js: export default { kinds: { ${name}: { desc: '…', load: (e, data) => { … } } } }`;
181
- /** Error text when a game's content/rules.js still exports effects */
182
- export const NO_GAME_EFFECTS = "content/rules.js: games no longer add effect words. Register the action as an op (engine.ops.define('noun.verb', { can, run }) in main.js) "
168
+ + `For the game's own data, register it in content/rules.js: export default { kinds: { ${name}: { desc: '…', load: (e, data) => { … } } } }, and list \`rules\` in content/index.js too: the loader only knows what it is handed`;
169
+ /** Error text for an effects key in a game's content/rules.js */
170
+ export const NO_GAME_EFFECTS = "content/rules.js: effects is not a key here. Register the action as an op (engine.ops.define('noun.verb', { can, run }) in main.js) "
183
171
  + "and call it from content with { op: ['noun.verb', { args }] }; see recipes/23-ops.md";
184
172
 
185
- /** Wrap a single value into an array (a model written as 'tree' or ['tree', ...args]); the one copy for the content files @param {any} v @returns {any[]} */
186
- export const list = v => (Array.isArray(v) ? v : [v]);
187
173
  const say = (vocab, x) => Object.entries(x).map(([k, v]) => vocab[k]?.describe?.(v) ?? `${k} ${JSON.stringify(v)}`);
188
174
 
189
175
  /** Describe a condition as one human-readable sentence (for the map); vocab defaults to the engine vocabulary */
@@ -193,7 +179,7 @@ export function describeCond(c, vocab = CONDITIONS) {
193
179
  return list(c).map(x => say(vocab, x).join(S.and)).join(S.and);
194
180
  }
195
181
  /** Describe an effect as one human-readable sentence (for the map); vocab defaults to the engine vocabulary */
196
- export function describeEffect(a, vocab = EFFECTS) {
182
+ export function describeEffect(a, vocab = ALL_EFFECTS) {
197
183
  if (!a) return '';
198
184
  if (typeof a === 'function') return S.fn;
199
185
  return list(a).map(x => say(vocab, x).join(S.then)).join(S.then);
@@ -5,15 +5,15 @@
5
5
  // canGrow: (rec, e) => rec.watered }
6
6
  // Why the stage lives on the record and not on a separate registry: the record is what world saves, what content-check / content.fields() describe
7
7
  // and what the editor edits, so `stage` is an ordinary state field (default 0, range 0..n-1) and `stageAt` (engine.clock.now when it entered the stage)
8
- // sits beside it. Growth is counted in game seconds (clock.now), so a far record, a loaded save or a time skip all catch up in one pass.
8
+ // sits beside it. Growth is counted in calendar seconds (clock.now), so a far record, a loaded save or a time skip all catch up in one pass.
9
9
  // Node-safe (no three): content-check imports this file directly, so the engine and the check accept the same stages.
10
- import { closest } from '../../core/validate.js';
10
+ import { closest } from '../../core/base/validate.js';
11
+ import { isModelName } from '../../core/base/util.js';
11
12
 
12
13
  const STAGE_KEYS = ['name', 'duration', 'scale', 'model'];
13
- const isModel = m => typeof m === 'string' || (Array.isArray(m) && typeof m[0] === 'string');
14
14
 
15
15
  /**
16
- * Problems of a template's stages list (empty list = fine). Every stage but the last needs a duration (game seconds spent there); the last may omit it
16
+ * Problems of a template's stages list (empty list = fine). Every stage but the last needs a duration (calendar seconds spent there); the last may omit it
17
17
  * (stays there). model is a model name like the template's own model (no functions: stages are data an editor can show and content-check can read).
18
18
  * @param {string} where e.g. "template 'crop'"
19
19
  * @param {any} stages
@@ -37,12 +37,12 @@ export function stagesProblems(where, stages) {
37
37
  else if (names.has(s.name)) out.push(`${at}: name '${s.name}' is used by an earlier stage; stage names must differ`);
38
38
  else names.add(s.name);
39
39
  const last = i === stages.length - 1;
40
- if (s.duration === undefined) { if (!last) out.push(`${at} needs duration (game seconds spent in this stage); only the last stage may leave it out`); }
41
- else if (!Number.isFinite(s.duration) || s.duration <= 0) out.push(`${at}: duration must be a positive number of game seconds, got ${JSON.stringify(s.duration)}`);
40
+ if (s.duration === undefined) { if (!last) out.push(`${at} needs duration (calendar seconds spent in this stage); only the last stage may leave it out`); }
41
+ else if (!Number.isFinite(s.duration) || s.duration <= 0) out.push(`${at}: duration must be a positive number of calendar seconds, got ${JSON.stringify(s.duration)}`);
42
42
  if (s.scale !== undefined && (!Number.isFinite(s.scale) || s.scale <= 0)) {
43
43
  out.push(`${at}: scale must be a positive number (multiplies the instance scale), got ${JSON.stringify(s.scale)}`);
44
44
  }
45
- if (s.model !== undefined && !isModel(s.model)) out.push(`${at}: model must be a model name (like the template's model), got ${JSON.stringify(s.model)}`);
45
+ if (s.model !== undefined && !isModelName(s.model)) out.push(`${at}: model must be a model name (like the template's model), got ${JSON.stringify(s.model)}`);
46
46
  });
47
47
  return out;
48
48
  }
@@ -21,25 +21,26 @@
21
21
  // A placement may override only rot / scale / y / items and the state fields; a different look or behaviour is a different template.
22
22
  // Recipe: docs/recipes/30-templates.md.
23
23
  // body: { shape: 'box' | 'ball' | 'hull', mass?, friction?, restitution?, damping?, angularDamping? } makes each copy a rigid body (needs rigid()):
24
- // it can be pushed, the model moves itself and its position is copied back to the record, so a pushed crate's place is saved like any other change.
24
+ // it can be pushed, the model moves itself and its position is copied back to the record, so a pushed crate's place is saved like any other change,
25
+ // and its whole state (turn, speed, asleep) with it in the save part 'rigid'. A copy nothing moved stays out of the save.
25
26
  // Ids: an instance with state (state / container / interact / body) should have a written id (ids.js); without one dev warns.
26
- import { checkOptions, freezeDef, missingText, fmt, DEV } from '../../core/validate.js';
27
- import { xzOf } from '../../core/math.js';
28
- import { placeY } from '../../core/ground.js';
29
- import { buildModel, settle, fitKey, unbuildModel } from './models.js';
27
+ import { checkOptions, freezeDef, missingText, fmt, DEV } from '../../core/base/validate.js';
28
+ import { xzOf } from '../../core/base/math.js';
29
+ import { placeY } from '../../core/scene/ground.js';
30
+ import { buildModel, settle, fits, fitsShape, unbuildModel, scaleOf } from './models.js';
30
31
  import { srcOf, stateful, templateId } from './ids.js';
31
32
  import { PLACEMENT_FIELDS, collideProblem } from './rules.js';
32
33
  import { fieldsShape } from './fields.js';
33
- import { whyBad, readParams, keysSchema } from '../../core/params.js';
34
+ import { whyBad, readParams, keysSchema } from '../../core/base/params.js';
34
35
  import { stagesProblems, stagedFields, growStages } from './stages.js';
35
- import { codedError } from '../../core/errorHints.js';
36
+ import { codedError } from '../../core/base/errorHints.js';
36
37
 
37
- const DEF_KEYS = ['model', 'collide', 'occluder', 'static', 'interact', 'container', 'sound', 'animate', 'state', 'fields', 'body', 'stages', 'update', 'canGrow'];
38
+ const DEF_KEYS = ['model', 'collide', 'occluder', 'static', 'lod', 'interact', 'container', 'sound', 'animate', 'state', 'fields', 'body', 'stages', 'update', 'canGrow'];
38
39
  const BODY_KEYS = ['shape', 'mass', 'friction', 'restitution', 'damping', 'angularDamping'];
39
40
  // what a placement may set besides the state fields: the placement field table (rules.js), so the loader, content-check and content.fields() agree
40
41
  const PLACE_KEYS = Object.keys(PLACEMENT_FIELDS['props.template']);
41
42
  // content.spawn gets its position as an argument, so only the id and the picture / goods keys of the same table
42
- const SPAWN_KEYS = PLACE_KEYS.filter(k => !['template', 'place', 'x', 'z', 'floor'].includes(k));
43
+ const SPAWN_KEYS = PLACE_KEYS.filter(k => !['template', 'place', 'x', 'z', 'floor', 'source'].includes(k));
43
44
 
44
45
  const STRINGS = {
45
46
  noModel: "template '{name}' needs a model: a model name from an asset pack (engine.assets.manifest({ models: { chest: '/models/chest.glb' | fn } })), e.g. { model: 'chest' }",
@@ -99,7 +100,7 @@ export function defineTemplates(e, api, st, defs) {
99
100
  limitContainers(e, st, name);
100
101
  }
101
102
  // a save brings back runtime instances and their goods, but container limits are definition data: put them back from the template
102
- st.templateLoad ??= e.events.on('world:load', () => { for (const name of st.templates.keys()) limitContainers(e, st, name); });
103
+ st.templateLoad ??= st.track(e.events.on('world:load', () => { for (const name of st.templates.keys()) limitContainers(e, st, name); }));
103
104
  }
104
105
 
105
106
  /** The definition of a template, or a dev error listing the known ones. @internal */
@@ -117,6 +118,9 @@ export function placeTemplate(e, api, st, p, i, zone, ids, origin) {
117
118
  const name = p.template, d = templateOf(st, name), id = templateId(p, i), { x, y, z } = api.where(p), floor = api._floorOf(p);
118
119
  const own = instanceFields(name, d, p, PLACE_KEYS, st.templateFields.get(name));
119
120
  if (floor !== undefined) own.floor = floor; // same as props: a moved instance lands on the same storey
121
+ const rot = api._facingOf(p);
122
+ if (rot !== undefined) own.rot = rot;
123
+ if (p.source !== undefined) own.source = p.source;
120
124
  if (ids && p.id != null) ids.claim(p.id, `props[${i}] (template ${name})`);
121
125
  else if (ids && stateful(d)) ids.unnamed(id, `props[${i}] (template ${name})`);
122
126
  const rec = e.world.add({ id, kind: name, position: { x, y: y ?? placeY(e, `props[${i}] (template ${name})`, x, z), z }, ...own, ...(zone != null && { zone }) }, { initial: true });
@@ -142,8 +146,8 @@ function instanceFields(name, d, p, keys, shape) {
142
146
  const state = Object.keys(d.state ?? {});
143
147
  for (const key of Object.keys(p)) if (DEF_KEYS.includes(key) && !state.includes(key)) throw codedError('content-template', fmt(STRINGS.defKey, { name, key }));
144
148
  checkOptions(`template '${name}' instance`, p, [...keys, ...state]);
145
- // dev: a state value outside the template's fields (range, values, type) fails here, for engine.content.spawn as well as for content
146
- if (DEV) for (const k of state) { const why = p[k] !== undefined && whyBad(shape[k], p[k]); if (why) throw codedError('content-template', `template '${name}' instance: ${k} ${why}`); }
149
+ // a state value outside the template's fields (range, values, type) fails here, for engine.content.spawn as well as for content
150
+ for (const k of state) { const why = p[k] !== undefined && whyBad(shape[k], p[k]); if (why) throw codedError('content-template', `template '${name}' instance: ${k} ${why}`); }
147
151
  if (p.items && !d.container) throw codedError('content-template', fmt(STRINGS.noBox, { name }));
148
152
  const own = structuredClone(d.state ?? {});
149
153
  for (const k of state) if (p[k] !== undefined) own[k] = structuredClone(p[k]);
@@ -166,20 +170,21 @@ function limitContainers(e, st, name) {
166
170
 
167
171
  /** How a template's instances look: shared prototype model, collision, interaction; built near, torn down far (once per template name). */
168
172
  function present(e, api, st, name) {
169
- if (st.templateViews.has(name)) return;
170
- if (e.world.presents(name)) throw codedError('content-template', fmt(STRINGS.taken, { name }));
171
- st.templateViews.add(name);
172
173
  const def = () => st.templates.get(name); // a later load may replace the definition: always read the current one
173
- const body = !!def().body; // a physics body moves the model itself: the record follows the model (positionFrom 'view'), so a pushed position is saved
174
- e.world.present(name, {
174
+ const body = !!def().body, was = st.templateViews.get(name); // a physics body moves the model itself: the record follows the model (positionFrom 'view'), so a pushed position is saved
175
+ if (was?.body === body) return;
176
+ was?.remove(); // a reload that adds or takes out `body`: who places the model changes, and world reads that once per presenter. Every copy rebuilds, from the record
177
+ if (e.world.presents(name)) throw codedError('content-template', fmt(STRINGS.taken, { name }));
178
+ st.templateViews.set(name, st.track(e.world.present(name, { // tracked: without content there is no definition to build from, and a new content() must be able to present the kind
175
179
  radius: () => Math.max(e.world.radius, e.stream.activeRadius), // same build distance as props
176
180
  positionFrom: body ? 'view' : 'record',
177
181
  async build(rec) {
178
- const d = def(), model = modelOf(d, rec), id = rec.id;
182
+ const d = def(), model = modelOf(d, rec), id = rec.id, mine = e.world.building(id);
179
183
  const o = await buildModel(e, api, rec, model, d.body ? { ...d, static: false, collide: false } : d, stageScale(d, rec));
180
184
  o.userData.model = JSON.stringify(model); // the built model, as text (describe / tests read it); serialized once per build, never per frame
181
185
  o.userData.modelFrom = modelSource(d, rec); // update compares this cheap key every frame: a stage with another model rebuilds the copy
182
- if (d.body) addBody(e, rec, o, d.body);
186
+ if (d.body && e.world.building(id) === mine) addBody(e, rec, o, d); // a build a load or rebuild replaced meanwhile is dropped: its body would take the id, and the saved state, from the real one
187
+ o.userData.useFrom = e.interactions;
183
188
  if (d.interact && e.interactions) o.userData.use = e.interactions.add(o, {
184
189
  id, radius: d.interact.radius ?? 2.5, height: d.interact.height, action: d.interact.action,
185
190
  label: () => label(e, def().interact?.label, e.world.get(id)) ?? name,
@@ -192,47 +197,72 @@ function present(e, api, st, name) {
192
197
  const d = def();
193
198
  // a stage that names another model: tear this copy down, world builds the new one next frame (the record, and so the save, is untouched)
194
199
  if (d.stages && !sameModel(o.userData, d, rec)) { e.world.rebuild(rec.id); return; }
200
+ if (d.interact && o.userData.useFrom !== e.interactions) { e.world.rebuild(rec.id); return; } // its use lives in the interactions module it was built with: another one starts empty
195
201
  const mul = stageScale(d, rec);
196
- if (!d.body && o.userData.fit !== fitKey(rec, mul)) settle(e, rec, o, d, mul); // a body places itself; a stage scale re-aligns collision too
197
- else if (d.body) restBody(e, rec, o);
202
+ if (d.body) { // a body places itself. Its turn and size were built into the solver: a new one needs a new body, built where the record stands
203
+ if (!fitsShape(o, rec, mul) || !sameBody(e, o.userData, d)) { e.world.rebuild(rec.id); return; }
204
+ restBody(e, rec, o);
205
+ } else if (!fits(e, o, rec, mul)) settle(e, rec, o, d, mul); // a stage scale re-aligns collision too
198
206
  d.animate?.(rec, o, dt);
199
207
  },
200
208
  dispose(rec, o) { o.userData.use?.remove(); o.userData.body?.remove(); unbuildModel(e, o); },
201
- });
209
+ })));
210
+ st.templateViews.get(name).body = body;
202
211
  }
203
212
 
213
+ const SETTLE = 0.05; // meters: a body that only settled (contact with uneven ground) moves less than this; a push moves it more
204
214
  /**
205
- * A rigid body for one built copy, never batched (it moves). It rests on the ground at the record's place: the collider is centred on the model's origin,
206
- * so the copy is lifted by half its height, and that resting place counts as the authored one (world.rest), so an untouched crate stays out of the save.
207
- * The body starts asleep: it stays exactly there until something hits it; then its moves are copied to the record (positionFrom 'view') and saved.
215
+ * A rigid body for one built copy, never batched (it moves). The body owns the pose and the record follows it (positionFrom 'view'), so one thing decides a copy's place:
216
+ * - A copy still where content put it stands on the ground: the collider is centred on the model's origin, so it is lifted by half its height, and that place counts
217
+ * as the authored one (world.rest). It starts asleep and atRest, which keeps it out of the save: content rebuilds it.
218
+ * - A copy with state in the save (the 'rigid' part, keyed by record id): that state is the pose, speed and sleep, and the record takes it, since no step runs before the next read.
219
+ * - A copy moved with no state (rebuilt by a new holder, a save without it, or a record moved after that state: rigid drops it): it starts awake at the record, so one left in the air comes down.
208
220
  */
209
- function addBody(e, rec, o, b) {
210
- const { shape, ...opts } = b, s = o.userData.proto.size, scale = rec.scale ?? 1;
211
- o.userData.batch = false;
212
- const ground = e.surface(rec.position.x, rec.position.z, rec.floor), y = Math.max(rec.position.y, ground + s.y * scale / 2);
213
- e.world.rest(rec.id, { x: rec.position.x, y, z: rec.position.z });
214
- o.position.y = rec.position.y;
221
+ function addBody(e, rec, o, d) {
222
+ const { shape, ...opts } = d.body, s = o.userData.proto.size, ud = o.userData, p = rec.position;
223
+ ud.batch = false; ud.bodyFrom = d.body; ud.holder = bodyHolder(e);
224
+ const half = s.y * scaleOf(rec)[1] / 2, floor = e.surface(p.x, p.z, rec.floor) + half;
225
+ // a state from the save decides this copy's place, even when the record reads as unmoved (put back by an undo): resting it would rewrite the baseline to a place it is not at
226
+ const unmoved = !e.rigid?.stateFor?.(rec.id) && e.world.rest(rec.id, { x: p.x, y: rec.ground === false ? Math.max(p.y, floor) : floor, z: p.z });
227
+ o.position.y = p.y;
215
228
  o.updateMatrixWorld(true);
229
+ if (!ud.holder) return; // the copy stands as a plain model; sameBody builds its body when a holder is ready
216
230
  const add = shape === 'ball' ? 'addBall' : shape === 'hull' && o.isMesh ? 'addHull' : 'addBox'; // a hull needs one mesh; a group gets a box
217
- o.userData.body = e.rigid[add](o, opts);
218
- o.userData.body?.body.sleep();
231
+ const b = ud.body = ud.holder[add](o, { ...opts, id: rec.id });
232
+ if (!b) return;
233
+ // a place written with no height (thing.set [x, 0, z]) means on the ground: a body put inside it goes through a thin floor and falls for good
234
+ b.place = at => { const y = e.surface(at.x, at.z, rec.floor) + half; return at.y < y - SETTLE ? { x: at.x, y, z: at.z } : at; };
235
+ if (b.atRest === false) { const t = b.body.translation(); p.x = t.x; p.y = t.y; p.z = t.z; return; }
236
+ b.atRest = true;
237
+ if (unmoved) b.body.sleep();
238
+ else { const at = b.place(p); if (at !== p) { p.y = at.y; ud.holder.setPosition(b, at); } }
219
239
  }
220
- const SETTLE = 0.05; // meters: a body that only settled (contact with uneven ground) moves less than this; a push moves it more
221
- /** While an authored body only settles where content put it, that settled pose is its authored rest (it stays out of the save); once pushed, the record keeps the change */
240
+ /** Who can hold a body now: a rigid still loading its solver is not one yet, so a copy built meanwhile waits instead of throwing */
241
+ const bodyHolder = e => e.rigid?.ready ? e.rigid : null;
242
+ /**
243
+ * Does the copy carry what the template asks for now, in the holder installed now? A body is a handle into one solver: another holder has none of it, and a hot reload
244
+ * that changes `body` cannot reach a built one. Same definition is a yes without serializing; a reloaded equal one is adopted, as sameModel does.
245
+ */
246
+ function sameBody(e, ud, d) {
247
+ if (ud.holder !== bodyHolder(e)) return false;
248
+ if (ud.bodyFrom === d.body) return true;
249
+ if (JSON.stringify(ud.bodyFrom) !== JSON.stringify(d.body)) return false;
250
+ ud.bodyFrom = d.body;
251
+ return true;
252
+ }
253
+ /**
254
+ * While a body only settles where content put it, the settled pose is its authored rest and it stays out of the save. Settling ends when it first sleeps:
255
+ * from then on anything that wakes it is play, however small the move, and the body's state goes in the save, so nothing a player did is lost to a tolerance.
256
+ */
222
257
  function restBody(e, rec, o) {
223
- const ud = o.userData, b = ud.body?.body;
224
- if (ud.pushed || !b) return;
258
+ const ud = o.userData, entry = ud.body;
259
+ if (!entry?.atRest) return;
225
260
  ud.restAt ??= { ...rec.position };
226
- const p = rec.position, r = ud.restAt;
227
- if (Math.abs(p.x - r.x) > SETTLE || Math.abs(p.y - r.y) > SETTLE || Math.abs(p.z - r.z) > SETTLE) { ud.pushed = true; return; }
228
- if (b.isSleeping()) e.world.rest(rec.id, p, SETTLE);
261
+ const p = rec.position, r = ud.restAt, asleep = entry.body.isSleeping();
262
+ if ((ud.settled && !asleep) || Math.abs(p.x - r.x) > SETTLE || Math.abs(p.y - r.y) > SETTLE || Math.abs(p.z - r.z) > SETTLE) { entry.atRest = false; return; }
263
+ if (asleep) { e.world.rest(rec.id, p, SETTLE); ud.settled = true; }
229
264
  }
230
265
 
231
- /** The model a copy shows: its stage's model, else the nearest earlier stage's, else the template's (so it never depends on what was built before) */
232
- function modelOf(d, rec) {
233
- for (let i = Math.min(rec.stage ?? 0, (d.stages?.length ?? 0) - 1); i >= 0; i--) if (d.stages[i].model) return d.stages[i].model;
234
- return d.model;
235
- }
236
266
  /**
237
267
  * Which definition and which stage supplied the model (the stage index, -1 for the template's own). Two equal keys always mean the same model, so
238
268
  * the per-frame check compares one object and one number instead of serializing the model of every instance every frame.
@@ -241,6 +271,8 @@ function modelSource(d, rec) {
241
271
  for (let i = Math.min(rec.stage ?? 0, (d.stages?.length ?? 0) - 1); i >= 0; i--) if (d.stages[i].model) return { d, at: i };
242
272
  return { d, at: -1 };
243
273
  }
274
+ /** The model a copy shows: its stage's model, else the nearest earlier stage's, else the template's (so it never depends on what was built before) */
275
+ function modelOf(d, rec) { const { at } = modelSource(d, rec); return at < 0 ? d.model : d.stages[at].model; }
244
276
  /** Same model as when built? Same definition + same source stage is a yes without serializing; only a reloaded definition falls back to comparing text */
245
277
  function sameModel(ud, d, rec) {
246
278
  const k = modelSource(d, rec), b = ud.modelFrom;
@@ -254,11 +286,10 @@ const stageScale = (d, rec) => d.stages?.[rec.stage ?? 0]?.scale ?? 1;
254
286
 
255
287
  /**
256
288
  * Gameplay of a template kind on the fixed step (world.simulate, once per name; each step reads the current definition, so a later load replaces it).
257
- * Growth runs near and far (far catches up in game seconds, several stages at once); update runs near only: a far copy only grows.
289
+ * Growth runs near and far (far catches up in calendar seconds, several stages at once); update runs near only: a far copy only grows.
258
290
  */
259
291
  function simulate(e, st, name) {
260
292
  if (st.templateSims.has(name)) return;
261
- st.templateSims.add(name);
262
293
  const grow = rec => {
263
294
  const d = st.templates.get(name);
264
295
  if (!d?.stages) return;
@@ -267,10 +298,10 @@ function simulate(e, st, name) {
267
298
  e.world.set(rec.id, next); // through world.set: world:change fires and the save keeps it, like any other gameplay change
268
299
  e.events.emit('template:stage', { id: rec.id, template: name, stage: next.stage, name: d.stages[next.stage].name });
269
300
  };
270
- e.world.simulate(name, {
301
+ st.templateSims.set(name, st.track(e.world.simulate(name, {
271
302
  near: (rec, dt) => { grow(rec); st.templates.get(name)?.update?.(rec, dt, e); },
272
303
  far: rec => grow(rec),
273
- });
304
+ })));
274
305
  }
275
306
 
276
307
  const label = (e, l, rec) => typeof l === 'function' ? l(rec, e) : l && e.i18n.has(l) ? e.t(l) : l;