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
@@ -14,13 +14,15 @@
14
14
  // shape 'sphere' | 'box' (can rotate) | 'cylinder' (vertical, default)
15
15
  // position center { x, y, z } / Vector3 / Object3D / [x, y, z]. For box and cylinder, y is the bottom height; if y is omitted, the ground height there is used
16
16
  // radius sphere/cylinder radius (default 1.5); size [width, height, depth] (box, default [2,2,2]); height cylinder height (default 3)
17
+ // volume your own region instead of shape: { contains({x,y,z}) -> boolean, bounds?: { min, max } } (the same plain volume addWaterBody takes); bounds
18
+ // (Box3-like) lets the zone be indexed and drawn by the debug view, without it the zone is checked every step
17
19
  // rotation box rotation around the Y axis in radians (default 0)
18
20
  // onEnter(t, who, id) / onExit(t, who, id) / onStay(dt, t, who, id) callbacks; who is the position that entered, id the world record id of who it is
19
21
  // (engine.actor for the default who, the id for an id in a custom who, object.userData.id for an Object3D, null for a bare position)
20
22
  // once fire on the first enter only (default false; exit follows at once); t.used is true afterwards, and a new playthrough (engine.session) re-arms it
21
23
  // enabled false pauses detection (handle.enabled can be changed any time)
22
24
  // tag name carried in events, for shared handling
23
- // who what can trigger: default is engine.actor (engine.actorPosition(): the player, or what engine.actor names; engine.focus without a player); or an
25
+ // who what can trigger: default is engine.actor and every seat's actor (engine.actorPosition(): the player, or what engine.actor names; engine.focus without a player); or an
24
26
  // actor id, a Vector3 / Object3D, or a function returning an array of those () => [e.actor, ...peerIds] (several actors)
25
27
  // (a zone with a function / object `who` is checked every step; zones with the default `who` cost nothing while the actor is far away)
26
28
  // cooldown seconds after leaving during which enter will not fire again (stops edge jitter from re-triggering), default 0
@@ -33,21 +35,23 @@
33
35
  // enter again. Zones added during play belong to the game: wrap them in engine.session.track(h).
34
36
  //
35
37
  // Debug display: engine.debug.view('triggers') draws all trigger zones as wireframes, engine.debug.view('off') clears them. It is a debug view mode
36
- // (core/debugView.js) and not a triggers option, so it works like every other "show me the hidden thing": one call, owner-scoped, said in describe().render.
38
+ // (core/inspect/debugView.js) and not a triggers option, so it works like every other "show me the hidden thing": one call, owner-scoped, said in describe().render.
37
39
  // The debug lines take their color from triggers({ debugColor, debugOpacity }); neutral gray if absent.
38
40
  // The action triggersDebug toggles that view; it has no key of its own (presets.bindings.debug binds F4 with the debug panel's F3).
39
- import { engineOwned } from '../../core/things.js';
41
+ import { engineOwned } from '../../core/scene/things.js';
40
42
  import * as THREE from 'three';
41
- import { readParams, keysSchema } from '../../core/params.js';
42
- import { Cells } from '../../core/cells.js';
43
+ import { readParams, keysSchema } from '../../core/base/params.js';
44
+ import { Cells } from '../../core/stream/cells.js';
45
+ import { codedError } from '../../core/base/errorHints.js';
46
+ import { placeY } from '../../core/scene/ground.js';
43
47
 
44
- // Zones are indexed (core/cells.js, the shared xz index) by the cells their bounding box covers, so a step looks at the zones near the actor instead of every
48
+ // Zones are indexed (core/stream/cells.js, the shared xz index) by the cells their bounding box covers, so a step looks at the zones near the actor instead of every
45
49
  // zone. A zone with its own `who` (any position, unknown until it runs) or one covering more than MAX_CELLS cells goes to the always-checked `_global` list.
46
50
  const CELL = 16, MAX_CELLS = 64, PAD = 0.01; // PAD: contains() is inclusive, so a point exactly on the edge must still find the zone's cell
47
51
  const DEBUG_GRAY = 0x9a9a9a;
48
52
  const bySeqDesc = (a, b) => b._seq - a._seq; // the order zones have always run in: newest first
49
53
 
50
- const ADD_KEYS = ['shape', 'position', 'radius', 'size', 'height', 'rotation', 'onEnter', 'onExit', 'onStay', 'once', 'enabled', 'tag', 'who', 'cooldown', 'userData'];
54
+ const ADD_KEYS = ['shape', 'position', 'radius', 'size', 'height', 'rotation', 'onEnter', 'onExit', 'onStay', 'once', 'enabled', 'tag', 'who', 'cooldown', 'userData', 'occupancy', 'volume'];
51
55
 
52
56
  const STRINGS = {
53
57
  'zh-CN': { 'module.triggers': '触发区', 'triggers.debug': '显示触发区' },
@@ -78,13 +82,18 @@ export class Triggers {
78
82
  add(opts = {}) {
79
83
  readParams('triggers.add()', keysSchema(ADD_KEYS), opts);
80
84
  const { shape = 'cylinder', position: at = {}, radius = 1.5, size = [2, 2, 2], height = 3, rotation = 0, onEnter = null, onExit = null, onStay = null,
81
- once = false, enabled = true, tag = '', who = null, cooldown = 0, userData = {} } = opts;
85
+ once = false, enabled = true, tag = '', who = null, cooldown = 0, userData = {}, occupancy = 'zone', volume = null } = opts;
86
+ if (volume && typeof volume.contains !== 'function') throw codedError('module-params', 'triggers.add({ volume }): needs volume.contains({ x, y, z }) -> boolean and optionally bounds { min, max }');
87
+ if (occupancy !== 'zone' && occupancy !== 'each') throw codedError('module-params', `triggers.add({ occupancy }): 'zone' (default: one enter when the first actor arrives, one exit when the last leaves) or 'each' (an enter and an exit per actor); got ${JSON.stringify(occupancy)}`);
88
+ if (!(radius >= 0 && Number.isFinite(radius))) throw codedError('module-params', `triggers.add({ radius }): must be a finite number >= 0, got ${radius}`); // NaN never matched and sat in the cell index
82
89
  const position = at.isObject3D ? at.position : Array.isArray(at) ? { x: at[0], y: at[1], z: at[2] } : at;
83
90
  const e = this.engine, x = position.x ?? 0, z = position.z ?? 0;
84
- const y = position.y ?? e.surface(x, z);
91
+ const y = position.y ?? (volume ? 0 : placeY(e, 'triggers.add()', x, z)); // a volume carries its own place
92
+ // a volume with bounds is indexed and drawn as its bounding box (the shape of a box with rotation 0); contains() stays the volume's own
93
+ const bb = volume?.bounds, box = bb ? { x: (bb.min.x + bb.max.x) / 2, y: bb.min.y, z: (bb.min.z + bb.max.z) / 2, size: [bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z] } : null;
85
94
  const t = {
86
- shape, x, y, z, radius, hx: size[0] / 2, hy: size[1] / 2, hz: size[2] / 2, sy: size[1], height, rotation,
87
- c: Math.cos(rotation), s: Math.sin(rotation), onEnter, onExit, onStay, once, enabled, tag, who, cooldown, userData,
95
+ shape: volume ? 'volume' : shape, volume, x: box?.x ?? x, y: box?.y ?? y, z: box?.z ?? z, radius, hx: (box?.size ?? size)[0] / 2, hy: (box?.size ?? size)[1] / 2, hz: (box?.size ?? size)[2] / 2, sy: (box?.size ?? size)[1], height, rotation,
96
+ c: Math.cos(rotation), s: Math.sin(rotation), onEnter, onExit, onStay, once, enabled, tag, who, cooldown, userData, occupancy, _in: null,
88
97
  inside: false, used: false, _cool: 0, _mesh: null, _gone: false,
89
98
  remove: () => this._remove(t),
90
99
  contains: p => this._contains(t, p),
@@ -96,21 +105,23 @@ export class Triggers {
96
105
  }
97
106
 
98
107
  _remove(t) { // remove only through the handle t.remove(); zones still occupied send exit first (so music areas and content onExit can clean up)
99
- const i = this._list.indexOf(t); if (i < 0) return;
100
- if (t.inside) this._exit(t, null);
101
- this._list.splice(i, 1); this._unregister(t); this._busy.delete(t);
108
+ if (t._gone) return;
109
+ // leave the books first: onExit may call t.remove() again or add / remove other zones, so no index taken before the callback is used after it (M08)
102
110
  t._gone = true;
111
+ const i = this._list.indexOf(t); if (i >= 0) this._list.splice(i, 1);
112
+ this._unregister(t); this._busy.delete(t);
113
+ if (t.inside) this._exit(t, null);
103
114
  if (t._mesh) { t._mesh.parent?.remove(t._mesh); t._mesh.geometry.dispose(); t._mesh = null; }
104
115
  }
105
116
  _register(t) {
106
- if (t.who) { this._global.push(t); return; }
107
- const ex = (t.shape === 'box' ? t.hx * Math.abs(t.c) + t.hz * Math.abs(t.s) : t.radius) + PAD;
108
- const ez = (t.shape === 'box' ? t.hx * Math.abs(t.s) + t.hz * Math.abs(t.c) : t.radius) + PAD;
117
+ if (t.who || (t.volume && !t.volume.bounds)) { this._global.push(t); return; }
118
+ const ex = (t.shape === 'box' || t.volume ? t.hx * Math.abs(t.c) + t.hz * Math.abs(t.s) : t.radius) + PAD;
119
+ const ez = (t.shape === 'box' || t.volume ? t.hx * Math.abs(t.s) + t.hz * Math.abs(t.c) : t.radius) + PAD;
109
120
  t._span = this._cells.cover(t, t.x - ex, t.z - ez, t.x + ex, t.z + ez, MAX_CELLS);
110
121
  if (!t._span) this._global.push(t);
111
122
  }
112
123
  _unregister(t) {
113
- if (t._span) this._cells.uncover(t); else this._global.splice(this._global.indexOf(t), 1);
124
+ if (t._span) this._cells.uncover(t); else { const i = this._global.indexOf(t); if (i >= 0) this._global.splice(i, 1); }
114
125
  }
115
126
  /** All trigger zones (a new array) */
116
127
  list() { return [...this._list]; }
@@ -146,9 +157,9 @@ export class Triggers {
146
157
  }
147
158
 
148
159
  _contains(t, p) {
149
- const dx = p.x - t.x, dz = p.z - t.z;
150
- if (t.shape === 'sphere') { const dy = p.y - t.y; return dx * dx + dy * dy + dz * dz <= t.radius * t.radius; }
151
- const dy = p.y - t.y;
160
+ if (t.volume) return !!t.volume.contains(p);
161
+ const dx = p.x - t.x, dy = p.y - t.y, dz = p.z - t.z;
162
+ if (t.shape === 'sphere') return dx * dx + dy * dy + dz * dz <= t.radius * t.radius;
152
163
  if (t.shape === 'box') {
153
164
  if (dy < 0 || dy > t.sy) return false;
154
165
  const lx = dx * t.c - dz * t.s, lz = dx * t.s + dz * t.c; // same rotation convention as the collision module's rectangle
@@ -160,7 +171,8 @@ export class Triggers {
160
171
  _defaultWho() {
161
172
  const e = this.engine;
162
173
  this._one[0] = e.actorPosition(); // engine.actor: the player by default, or the vehicle / squad member the game handed control to
163
- this._ids.length = 1; this._ids[0] = e.actor;
174
+ this._one.length = this._ids.length = 1; this._ids[0] = e.actor;
175
+ for (const s of e.input.seats) if (s.actor && s.actor !== e.actor) { this._one.push(e.actorPosition(s.actor)); this._ids.push(s.actor); } // every local player, as interactions and pickups
164
176
  return this._one;
165
177
  }
166
178
 
@@ -201,6 +213,7 @@ export class Triggers {
201
213
  else { ps.push(x); ids.push(null); }
202
214
  }
203
215
  }
216
+ if (t.occupancy === 'each') return this._visitEach(t, dt, ps, ids);
204
217
  let hit = null, id = null;
205
218
  if (ps) for (let k = 0; k < ps.length; k++) { const p = ps[k]; if (p && this._contains(t, p)) { hit = p; id = ids[k] ?? null; break; } }
206
219
  if (hit && !t.inside) {
@@ -212,6 +225,27 @@ export class Triggers {
212
225
  } else if (!hit && t.inside) this._exit(t, null);
213
226
  else if (hit && t.inside) t.onStay?.(dt, t, hit, id);
214
227
  }
228
+ /** @internal occupancy 'each': every actor in the zone enters, stays and exits on its own; t.inside is true while anyone is in. Cooldown runs from when the zone empties */
229
+ _visitEach(t, dt, ps, ids) {
230
+ const e = this.engine, inn = t._in ??= new Map(), now = new Map();
231
+ if (ps) for (let k = 0; k < ps.length; k++) { const p = ps[k]; if (p && this._contains(t, p)) now.set(ids[k] ?? p, { p, id: ids[k] ?? null }); }
232
+ for (const [key, o] of inn) if (!now.has(key)) { inn.delete(key); this._left(t, null, o.id); if (t._gone) return; }
233
+ if (t.inside && !inn.size) { t.inside = false; t._cool = t.cooldown; }
234
+ for (const [key, o] of now) {
235
+ if (inn.has(key)) { t.onStay?.(dt, t, o.p, o.id); if (t._gone) return; continue; }
236
+ if (t._cool > 0 && !inn.size) return;
237
+ inn.set(key, o); t.inside = true;
238
+ t.onEnter?.(t, o.p, o.id);
239
+ e.events.emit('trigger:enter', { tag: t.tag, trigger: t, who: o.p, id: o.id });
240
+ if (t._gone) return;
241
+ if (t.once) { t.used = true; this._exit(t, null); return; }
242
+ }
243
+ }
244
+ /** @internal one actor left: the callback and the event */
245
+ _left(t, who, id) {
246
+ t.onExit?.(t, who, id);
247
+ this.engine.events.emit('trigger:exit', { tag: t.tag, trigger: t, who, id });
248
+ }
215
249
  /** @internal each zone's save key: tag (or '(shape)') plus its order among zones with that label, so code that adds the same zones gets the same keys */
216
250
  _keys() {
217
251
  const n = new Map();
@@ -235,10 +269,10 @@ export class Triggers {
235
269
  }
236
270
  _exit(t, who) {
237
271
  // id: who was inside (remembered at enter), so an exit says who left even though the position that left is gone
238
- const id = t._id ?? null;
272
+ const id = t._id ?? null, all = t._in ? [...t._in.values()] : null;
239
273
  t.inside = false; t._cool = t.cooldown; t._id = null;
240
- t.onExit?.(t, who, id);
241
- this.engine.events.emit('trigger:exit', { tag: t.tag, trigger: t, who, id });
274
+ if (all) { t._in.clear(); for (const o of all) this._left(t, who, o.id); return; } // occupancy 'each': everyone leaves
275
+ this._left(t, who, id);
242
276
  }
243
277
 
244
278
  // ---------- debug view 'triggers' ----------
@@ -260,9 +294,10 @@ export class Triggers {
260
294
  };
261
295
  }
262
296
  _addDebugMesh(t) {
297
+ if (t.volume && !t.volume.bounds) return; // nothing to draw without bounds
263
298
  let geo;
264
299
  if (t.shape === 'sphere') geo = new THREE.SphereGeometry(t.radius, 12, 8);
265
- else if (t.shape === 'box') geo = new THREE.BoxGeometry(t.hx * 2, t.sy, t.hz * 2).translate(0, t.sy / 2, 0);
300
+ else if (t.shape === 'box' || t.volume) geo = new THREE.BoxGeometry(t.hx * 2, t.sy, t.hz * 2).translate(0, t.sy / 2, 0);
266
301
  else geo = new THREE.CylinderGeometry(t.radius, t.radius, t.height, 16, 1, true).translate(0, t.height / 2, 0);
267
302
  const lines = new THREE.LineSegments(new THREE.WireframeGeometry(geo), this._mat);
268
303
  geo.dispose();
@@ -278,17 +313,47 @@ const TRIGGER_PARAMS = {
278
313
  debugOpacity: { type: 'number', default: 0.8, desc: "line opacity of the debug view 'triggers'" },
279
314
  };
280
315
 
316
+ /**
317
+ * The triggers section of content data: fromLevel = the level's trigger_<tag> marker, otherwise placed by position. Enter / exit effects look up the merged table,
318
+ * and the listener is attached only once. They act for whoever crossed the zone (a { give } lands in that actor's bag); a zone emptied by removal has no id: engine.actor
319
+ */
320
+ function triggerContent() {
321
+ const table = {};
322
+ let subs = null;
323
+ return {
324
+ desc: 'trigger zones (tag -> position / from level, enter/exit effects)',
325
+ undo(d, { engine: e }) {
326
+ const had = new Set(e.triggers._list), was = { ...table };
327
+ return () => {
328
+ for (const t of [...e.triggers._list]) if (!had.has(t)) t.remove();
329
+ for (const tag of Object.keys(table)) delete table[tag];
330
+ Object.assign(table, was);
331
+ };
332
+ },
333
+ commit(d, { engine: e, content, where, bind, track }) {
334
+ Object.assign(table, d);
335
+ if (Object.values(d).some(t => t.fromLevel)) e.triggers.fromMarkers();
336
+ for (const [tag, t] of Object.entries(d)) if (!t.fromLevel) bind(e.triggers.add({ ...t, tag, position: where(t.position), onEnter: null, onExit: null }), t.position);
337
+ subs ??= [
338
+ track(e.events.on('trigger:enter', ({ tag, id }) => content.run(table[tag]?.onEnter, { actor: id ?? e.actor }))),
339
+ track(e.events.on('trigger:exit', ({ tag, id }) => content.run(table[tag]?.onExit, { actor: id ?? e.actor }))),
340
+ ];
341
+ },
342
+ };
343
+ }
344
+
281
345
  /** Trigger zone module. Provides engine.triggers once installed. Optional dependency: level (used by fromMarkers) */
282
346
  export function triggers(opts = {}) {
283
347
  const o = readParams('triggers', TRIGGER_PARAMS, opts);
284
348
  let tr = null;
285
349
  return {
286
- name: 'triggers', type: 'rules', label: 'Triggers', params: TRIGGER_PARAMS, options: o, noSkip: 'zone enter/exit is re-evaluated on the next fixed step', optional: ['level'], stage: 'gameplay', after: ['interactions'],
350
+ content: { triggers: triggerContent() },
351
+ name: 'triggers', skipKind: 'none', type: 'rules', label: 'Triggers', params: TRIGGER_PARAMS, options: o, noSkip: 'zone enter/exit is re-evaluated on the next fixed step', optional: ['level'], stage: 'gameplay', after: ['interactions'],
287
352
  install(e, ctx) {
288
353
  tr = new Triggers(e, o, ctx.track);
289
354
  // audio rule condition { zone: 'cave' | ['cave', 'mine'] }: some trigger zone with that tag is occupied
290
355
  ctx.track(e.audio.condition('zone', v => [].concat(v).some(tag => tr.byTag(tag).some(t => t.inside))));
291
- e.saves.register('triggers', { save: () => tr._save(), load: d => tr._load(d) });
356
+ ctx.saves.register('triggers', { notAtomic: 'bodies crossing a zone change it in the step, and its load fires exits', save: () => tr._save(), load: d => tr._load(d) });
292
357
  return tr;
293
358
  },
294
359
  fixed(dt) { tr.update(dt); },
@@ -301,3 +366,5 @@ export function triggers(opts = {}) {
301
366
  },
302
367
  };
303
368
  }
369
+
370
+ export const handRolled = 'none: a zone check by hand is the same maths as any distance or box test';
@@ -2,15 +2,17 @@
2
2
  // (c.plants[name]: matrices, colors, stable ids), tree collision circles (c.colliders), felled-tree records (saved) and instanceAt.
3
3
  // Data only: this file makes no mesh and touches no material. Draw parts subscribe with view({ species, change, ring, show, drop })
4
4
  // (vegetation/draw.js is the engine's own, slot 'vegetation-draw'); the models and materials given to define() are read there.
5
- import { isModelName, vegetationModel } from '../../core/namedModel.js';
6
- import { warnMissing } from '../../core/validate.js';
7
- import { readParams, keysSchema } from '../../core/params.js';
8
- import { reportError } from '../../core/errors.js';
9
- import { xzOf } from '../../core/math.js';
5
+ import { Vector3 } from 'three';
6
+ import { vegetationModel } from '../../core/assets/namedModel.js';
7
+ import { isModelName } from '../../core/base/util.js';
8
+ import { DEV, warnMissing, warnOnce } from '../../core/base/validate.js';
9
+ import { readParams, keysSchema } from '../../core/base/params.js';
10
+ import { reportError } from '../../core/base/errors.js';
11
+ import { xzOf } from '../../core/base/math.js';
10
12
  import { GroundChunks } from './groundChunks.js';
11
13
  import { fadeBand } from './nearFade.js';
12
14
  import { makeDensity, thin } from './densityMap.js';
13
- import { codedError } from '../../core/errorHints.js';
15
+ import { coded, codedError } from '../../core/base/errorHints.js';
14
16
  // parameters read by vegetation.define(); keys inside rule (sent to the worker thread)
15
17
  const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'positions', 'densityMap', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade'];
16
18
  const RULE_KEYS = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'scale', 'stretch', 'sink', 'tintJitter', 'tints', 'biomes', 'collider', 'avoidFlat', 'salt'];
@@ -25,37 +27,39 @@ function checkPositions(label, list, rule) {
25
27
  if (!Array.isArray(p) || p.length < 2 || p.length > 4 || !p.every(Number.isFinite)) throw codedError('vegetation-option', `${label}: positions[${i}] = ${JSON.stringify(p)}; each entry is [x, z], [x, z, scale] or [x, z, scale, yaw] (finite numbers)`);
26
28
  });
27
29
  const clash = SCATTER_ONLY.filter(k => rule && k in rule);
28
- if (clash.length) throw codedError('vegetation-option', `${label}: rule.${clash.join(' / rule.')} only filters random placement and does not apply to positions (every listed spot is planted). Drop it, or add a second species for the scattered ones`);
30
+ if (DEV && clash.length) warnOnce(coded('vegetation-option', `${label}: rule.${clash.join(' / rule.')} only filters random placement and does not apply to positions (every listed spot is planted). Drop it, or add a second species for the scattered ones`));
29
31
  }
30
32
 
31
33
  // Single-instance removal/restore (chop a tree, mine a rock): records are owned by vegetation and saved with the save (save key 'vegetation', entry
32
34
  // 'veg:<name>:<cx>,<cz>:<id>'), and reapplied when a chunk reloads.
33
35
  // The id is this tree's stable number (independent of quality and vegetation density), not its index in the instance array.
34
36
  // const hit = engine.vegetation.instanceAt(position, { radius: 2, species: '松树' }); // → { species, cx, cz, id, position } or null
35
- // engine.vegetation.removeInstance(hit.species, hit.cx, hit.cz, hit.id, { regrowSeconds: 300 }); // grows back after 300 game seconds
37
+ // engine.vegetation.removeInstance(hit.species, hit.cx, hit.cz, hit.id, { regrowSeconds: 300 }); // grows back after 300 calendar seconds
36
38
  // engine.vegetation.restoreInstance(...) // restore immediately
37
39
  // Hiding: the slot goes into c.hidden[name] (the draw part draws it as a zero matrix, count unchanged) and out of the chunk's collision circles.
38
- // Regrowth: the record stores the expiry time (engine.clock game seconds), checked once per second; the clock is saved, so the countdown continues after
40
+ // Regrowth: the record stores the expiry time (engine.calendar seconds), checked once per second; the clock is saved, so the countdown continues after
39
41
  // reload.
40
42
  const KEY_RE = /^veg:(.*):(-?\d+),(-?\d+):(\d+)$/;
41
43
  const hashName = s => { let h = 7; for (const ch of s) h = (Math.imul(h, 31) + ch.codePointAt(0)) | 0; return h & 0x7fffffff; };
42
44
  // stable id -> instance slot of one placement result (built once per result, kept off the record so it never travels)
43
45
  const SLOTS = new WeakMap();
44
46
  function slotOf(r, id) {
45
- if (!r.ids) return id < r.n ? id : undefined;
46
47
  let m = SLOTS.get(r);
47
48
  if (!m) { m = new Map(); SLOTS.set(r, m); for (let i = 0; i < r.ids.length; i++) m.set(r.ids[i], i); }
48
49
  return m.get(id);
49
50
  }
50
51
 
52
+ const REMOVE_KEYS = ['regrowSeconds'];
53
+
51
54
  export class Vegetation {
52
- constructor(engine, opts = {}) {
55
+ constructor(engine, opts = {}, ctx) {
53
56
  this.engine = engine; this.species = new Map();
54
57
  // where it grows: on terrain chunks when the terrain module is installed (placed in its workers), else on vegetation's own chunks over
55
58
  // whatever provides the ground (a level, a code-built ground, flat). Both hosts keep chunks of one shape, so everything below is shared
56
59
  if (engine.terrain && Object.keys(opts).length) throw codedError('vegetation-option', `vegetation({ ${Object.keys(opts).join(', ')} }): with terrain() installed vegetation grows on the terrain chunks, and density / view distance are terrain options (terrain({ density, viewChunks })). The vegetation() options are for ground without terrain (a level, a code-built ground)`);
57
- /** @internal the chunk table vegetation lives in: engine.terrain, or its own GroundChunks */
58
60
  /** @internal the draw parts drawing the plants (view()) */ this.views = new Set();
61
+ /** @internal the chunk table vegetation lives in: engine.terrain, or its own GroundChunks */
62
+ /** @internal what its chunks live on: terrain, or its own ground chunks. The settings menu sizes the view through it */
59
63
  this.host = engine.terrain ?? new GroundChunks(engine, this, opts);
60
64
  // on terrain: this is the terrain's planter (it calls mount / unmount / drop / ring; terrain never reads engine.vegetation); a chunk's
61
65
  // visibility comes from the terrain data part, so a game that replaces the terrain drawing keeps its trees
@@ -63,14 +67,14 @@ export class Vegetation {
63
67
  this._planter = engine.terrain.setPlanter(this);
64
68
  this._view = engine.terrain.view({ show: (c, v) => this._emit('show', c, v) });
65
69
  }
66
- this._removed = new Map(); // 'name:cx,cz' -> Map(id -> regrow time (clock game seconds), null = permanent)
70
+ this._removed = new Map(); // 'name:cx,cz' -> Map(id -> regrow time (calendar seconds), null = permanent)
67
71
  this._acc = 0;
68
72
  this._pending = []; // density images still loading (densityMap.url); the module's init waits for them
69
- this._initDone = false; // set when init took _pending: an image of a species added later is not awaited, so its error is caught where it is added
70
- // dev asset hot swap (core/assetHot.js): a species made from a swapped model is added again with the new geometry / materials. Why here and
73
+ this._initDone = false; // set when init has waited for _pending: an image of a species added later is not awaited, so its error is caught where it is added
74
+ // dev asset hot swap (core/assets/assetHot.js): a species made from a swapped model is added again with the new geometry / materials. Why here and
71
75
  // not in the generic scene walk: a species' materials are patched copies (wind, season) and its geometry may be merged from a model
72
- engine.assets.onSwap?.(s => this._swapped(s));
73
- engine.saves.register('vegetation', {
76
+ ctx.track(engine.assets.onSwap(s => this._swapped(s)));
77
+ ctx.saves.register('vegetation', { notAtomic: 'its load redraws the instances it hides: not plain data a rollback restores by itself',
74
78
  save: () => {
75
79
  const removed = {};
76
80
  for (const [ck, m] of this._removed) { for (const [id, until] of m) removed[`veg:${ck}:${id}`] = until; }
@@ -141,7 +145,7 @@ export class Vegetation {
141
145
  // reaches the placer (terrain worker or ground chunks), and a list of numbers travels as plain data
142
146
  rule: { salt: hashName(name), ...(o.rule || {}), ...(o.positions != null ? { positions: o.positions } : {}) },
143
147
  density, // densityMap sampler (main thread only: a function may read game state), applied in mount()
144
- nearOnly: !!o.nearOnly, maxRing, lodRing: o.lodRing ?? 1, fade: o.effects === false ? null : fadeBand(o.fade, !!o.nearOnly, maxRing, this.host.CHUNK),
148
+ nearOnly: !!o.nearOnly, maxRing, lodRing: o.lodRing ?? 1, fade: o.effects === false ? null : fadeBand(o.fade, !!o.nearOnly, maxRing, this.host.chunkSize),
145
149
  castShadow: o.castShadow ?? !o.nearOnly, shadowRing: o.shadowRing ?? 1, receiveShadow: o.receiveShadow ?? true,
146
150
  };
147
151
  sp.source = o; // what it was made from: the draw part reads geometry / model / material / wind from it, a hot swap adds it again (_swapped)
@@ -187,8 +191,11 @@ export class Vegetation {
187
191
  }
188
192
  return out;
189
193
  }
190
- /** @internal module init: density images of species added before start */
191
- async whenLoaded() { const p = this._pending; this._pending = []; this._initDone = true; await Promise.all(p); }
194
+ /** @internal module init: density images and named models of species added before start; a named model's define() may add an image of its own, so until none is left */
195
+ async whenLoaded() {
196
+ try { while (this._pending.length) { const p = this._pending; this._pending = []; await Promise.all(p); } }
197
+ finally { this._initDone = true; }
198
+ }
192
199
  /**
193
200
  * Place every chunk again: after changing the ground behind the same provider (a ground function reading game state), or what a densityMap
194
201
  * function reads. A new setGround or level is followed automatically
@@ -198,7 +205,7 @@ export class Vegetation {
198
205
  list() { return [...this.species.values()]; }
199
206
  /**
200
207
  * Change at runtime how far a vegetation kind casts shadows: within `ring` chunk rings of the player (0 = only the chunk you stand in, 1 = the default,
201
- * larger = further and dearer). Takes effect at once; the add() option shadowRing is only the starting value. An unknown name warns with the known ones
208
+ * larger = further and dearer). Takes effect at once; the define() option shadowRing is only the starting value. An unknown name warns with the known ones
202
209
  * @example engine.vegetation.setShadowRing('tree', 0); // graphics setting "shadows: low": trees shadow only the nearest chunk
203
210
  * @param {string} name species name given to vegetation.define
204
211
  * @param {number} ring chunk rings, 0 or more
@@ -283,8 +290,9 @@ export class Vegetation {
283
290
  /** @internal save-key format */
284
291
  key(species, cx, cz, id) { return `veg:${species}:${cx},${cz}:${id}`; }
285
292
  isRemoved(species, cx, cz, id) { return !!this._removed.get(`${species}:${cx},${cz}`)?.has(id); }
286
- /** Remove one instance (regrowSeconds: game seconds until it grows back, 0/omitted = permanent). The record is saved with the save */
287
- removeInstance(species, cx, cz, id, { regrowSeconds = 0 } = {}) {
293
+ /** Remove one instance (regrowSeconds: calendar seconds until it grows back, 0/omitted = permanent). The record is saved with the save */
294
+ removeInstance(species, cx, cz, id, opts) {
295
+ const { regrowSeconds = 0 } = readParams('vegetation.removeInstance()', keysSchema(REMOVE_KEYS), opts);
288
296
  const ck = `${species}:${cx},${cz}`;
289
297
  if (!this._removed.has(ck)) this._removed.set(ck, new Map());
290
298
  this._removed.get(ck).set(id, regrowSeconds > 0 ? this.engine.clock.now + regrowSeconds : null);
@@ -318,7 +326,7 @@ export class Vegetation {
318
326
  instanceAt(position, opts = {}) {
319
327
  readParams('vegetation.instanceAt()', keysSchema(['radius', 'species']), opts);
320
328
  const [x, z] = xzOf(position), { radius = 2, species = null } = typeof opts === 'object' && opts ? opts : {};
321
- const T = this.host, CH = T.CHUNK;
329
+ const T = this.host, CH = T.chunkSize;
322
330
  let best = null, bestD = radius * radius;
323
331
  for (let cz = Math.floor((z - radius) / CH); cz <= Math.floor((z + radius) / CH); cz++)
324
332
  for (let cx = Math.floor((x - radius) / CH); cx <= Math.floor((x + radius) / CH); cx++) {
@@ -330,7 +338,7 @@ export class Vegetation {
330
338
  for (let i = 0; i < r.n; i++) {
331
339
  if (hid?.has(i)) continue;
332
340
  const dx = ox + a[i * 16 + 12] - x, dz = oz + a[i * 16 + 14] - z, d = dx * dx + dz * dz;
333
- if (d < bestD) { bestD = d; best = { species: name, cx, cz, id: r.ids ? r.ids[i] : i, position: new this.engine.THREE.Vector3(ox + a[i * 16 + 12], a[i * 16 + 13], oz + a[i * 16 + 14]) }; }
341
+ if (d < bestD) { bestD = d; best = { species: name, cx, cz, id: r.ids[i], position: new Vector3(ox + a[i * 16 + 12], a[i * 16 + 13], oz + a[i * 16 + 14]) }; }
334
342
  }
335
343
  }
336
344
  }
@@ -341,7 +349,7 @@ export class Vegetation {
341
349
  mount(c, name, r) {
342
350
  const sp = this.species.get(name);
343
351
  // densityMap thins here, before the colliders are taken, so a dropped plant blocks nothing; survivors keep their stable ids
344
- if (sp?.density) r = thin(r, c.cx * this.host.CHUNK, c.cz * this.host.CHUNK, sp.density.at, sp.rule.salt);
352
+ if (sp?.density) r = thin(r, c.cx * this.host.chunkSize, c.cz * this.host.chunkSize, sp.density.at, sp.rule.salt);
345
353
  c.plants ||= {}; c.colliders ||= {}; c.collidersAll ||= {};
346
354
  // none left (terrain dug, densityMap thinned all): drop the record, so the draw part tears its mesh down too and collision matches what is drawn
347
355
  if (r.n === 0) delete c.plants[name]; else c.plants[name] = r;
@@ -6,9 +6,9 @@
6
6
  // a zoning grid the game edits), which cannot travel to the terrain worker; and thinning the already placed instances keeps every survivor's
7
7
  // stable id, so felled-tree records and saves stay valid whether the map is on, off or changed. Each instance keeps or drops by its own hash
8
8
  // against the density there, so raising the density only adds plants, it never moves the ones already standing.
9
- import { readParams, keysSchema } from '../../core/params.js';
10
- import { grayAt, loadGray } from '../../core/grayMap.js';
11
- import { codedError } from '../../core/errorHints.js';
9
+ import { readParams, keysSchema } from '../../core/base/params.js';
10
+ import { grayWorld, loadGray } from '../../core/scene/grayMap.js';
11
+ import { codedError } from '../../core/base/errorHints.js';
12
12
 
13
13
  const MAP_KEYS = ['url', 'data', 'width', 'height', 'size', 'center', 'outside'];
14
14
 
@@ -26,10 +26,7 @@ export function makeDensity(spec, label) {
26
26
  const M = { ...spec, data: spec.data ?? null };
27
27
  const at = (x, z) => {
28
28
  if (!M.data) return 0; // image not loaded yet: nothing grows, the chunks are placed again once it is
29
- const [sx, sz] = M.size, [cx0, cz0] = M.center || [0, 0];
30
- const u = (x - cx0) / sx + 0.5, v = (z - cz0) / sz + 0.5;
31
- if (u < 0 || u > 1 || v < 0 || v > 1) return M.outside ?? 0;
32
- return grayAt(M, u, v);
29
+ return grayWorld(M, x, z) ?? M.outside ?? 0;
33
30
  };
34
31
  const pending = M.data ? null : loadGray(spec.url).then(g => { Object.assign(M, g); }, err => { throw codedError('vegetation-option', `${label}: densityMap url ${spec.url} did not load (${err?.message ?? err})`); });
35
32
  return { at, pending };
@@ -7,21 +7,38 @@
7
7
  // (engine.use(myPlants, { replaces: 'vegetation-draw' })) and keep everything that plays. A replacement draw part does what this file does:
8
8
  // install(e, ctx) { ctx.track(e.vegetation.view({ species(sp) {...}, change(c, name) {...c.plants[name]...}, ring(c, ring) {...}, show(c, v) {...}, drop(c) {...} })); }
9
9
  // This file never changes placement data; it only reads it.
10
- import { engineOwned } from '../../core/things.js';
10
+ import { engineOwned } from '../../core/scene/things.js';
11
+ import { needMaterial, oneForm } from '../../core/base/validate.js';
11
12
  import * as THREE from 'three';
12
13
  import { fromModel } from './modelGeometry.js';
13
14
  import { applyEffects, windCustom } from '../../render/materials.js';
14
15
  import { neutralMaterial } from '../../render/neutral.js';
15
16
  import { patchMaterial, unpatchMaterial } from '../../render/patches.js';
16
17
  import { EFFECTS, hashText } from '../../render/effects.js';
17
- import { codedError } from '../../core/errorHints.js';
18
+ import { codedError } from '../../core/base/errorHints.js';
19
+ import { isWebGPU } from '../../render/backend.js';
18
20
  import { nearFadePatch } from './nearFade.js';
21
+ import { scatterAttempts } from '../../core/stream/scatter.js';
19
22
 
20
23
  const COLOR = 'vegetationColor'; // the patch name of vegetation.color() on every species' material
21
24
  // The wind patch in engine.vegetation.patches has one amplitude: a shared material cannot carry each species' own (those are define()'s wind option)
22
25
  const SHARED_SWAY = 0.05;
23
26
  const code = v => (typeof v === 'string' ? { glsl: v } : v);
24
27
 
28
+ /**
29
+ * How many instances of a placement to draw at a density. A plant with a collider is placed in full at every quality, so collision and felled ids stay the same world, and low
30
+ * quality thins only its drawing. Why a count and not a filter: ids rise in placement order, so the plants a density keeps are the front of the list, the same ones it kept when
31
+ * it thinned placement, and the instances behind just are not drawn. A blocker that is not drawn still blocks. rule.positions are the game's own and never thin.
32
+ * @internal
33
+ */
34
+ export function drawnPlants(rule, r, density) {
35
+ if (!rule?.collider || rule.positions) return r.n;
36
+ const keep = scatterAttempts(rule, density);
37
+ let n = r.n;
38
+ while (n > 0 && r.ids[n - 1] >= keep) n--;
39
+ return n;
40
+ }
41
+
25
42
  export class VegetationDraw {
26
43
  /** @param {any} e @param {any} v the vegetation data part (engine.vegetation) */
27
44
  constructor(e, v) {
@@ -41,14 +58,11 @@ export class VegetationDraw {
41
58
  /** @internal engine.vegetation.material: every species with no material or model of its own draws it, as given; null gives the neutral default back */
42
59
  get material() { return this._game ?? this._base; }
43
60
  set material(m) {
44
- if (m != null && !m.isMaterial) throw codedError('vegetation-option', `vegetation.material is a three.js material (or null for the neutral default); got ${m}`);
45
- const was = this._game;
61
+ if (m != null) needMaterial('vegetation-option', 'vegetation.material', m, ' (null gives the neutral default back)');
46
62
  this._game = m || null;
47
63
  for (const sp of this.v.list()) {
48
64
  const old = this.kinds.get(sp.name);
49
- if (!old?.shared) continue;
50
- this.species(sp);
51
- if (old.material !== was) old.material.dispose(); // a neutral copy of ours; the game's stays the game's
65
+ if (old?.shared) this.species(sp);
52
66
  }
53
67
  for (const rec of this.meshes.values()) for (const n in rec.ims) { const k = this.kinds.get(n); if (k) rec.ims[n].material = k.material; }
54
68
  }
@@ -78,9 +92,8 @@ export class VegetationDraw {
78
92
 
79
93
  /** Each renderer draws its own form; the one this engine's renderer needs, when missing, is named (else the code would do nothing silently) */
80
94
  _needForm(entry, s) {
81
- const gpu = !!this.engine.renderer?.isWebGPURenderer;
82
- if (!gpu && s.glsl == null) throw codedError('vegetation-option', `vegetation.${entry}() has only a tsl form, which WebGLRenderer cannot draw: give glsl too ({ glsl, tsl })`);
83
- if (gpu && s.tsl == null) throw codedError('vegetation-option', `vegetation.${entry}() has only a glsl form, which WebGPURenderer cannot draw: give tsl too ({ glsl, tsl })`);
95
+ const gpu = isWebGPU(this.engine.renderer);
96
+ if (gpu ? s.tsl == null : s.glsl == null) throw oneForm('vegetation-option', `vegetation.${entry}()`, !!gpu);
84
97
  }
85
98
  _windPatch(amplitude) { return EFFECTS.wind(amplitude, this._sway ? windCustom(this._sway) : undefined); }
86
99
  /** engine.vegetation.patches: what a game's shared material needs to behave like the engine's (the near fade is per species: define({ material }) gets it) */
@@ -108,13 +121,16 @@ export class VegetationDraw {
108
121
  const own = [nf?.patch, this._color].filter(Boolean);
109
122
  const fx = m => o.effects === false ? m : applyEffects(m, { wind, season: 'foliage', engine: e, patches: own.length ? own : undefined });
110
123
  const mdl = o.model && fromModel(o.model, label);
111
- let lod = o.lodGeometry?.isObject3D ? fromModel(o.lodGeometry, label + '.lodGeometry').geometry : o.lodGeometry || null;
124
+ const lodMdl = o.lodGeometry?.isObject3D ? fromModel(o.lodGeometry, label + '.lodGeometry') : null;
125
+ let lod = lodMdl ? lodMdl.geometry : o.lodGeometry || null;
112
126
  if (mdl && lod && !lod.groups.length) { lod = lod.clone(); lod.addGroup(0, Infinity, 0); } // a material array draws nothing without groups
113
127
  const shared = !mdl && !o.material, game = shared ? this._game : null;
114
- this.kinds.set(sp.name, {
115
- geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod, fadeUniforms: game ? null : nf?.uniforms ?? null, shared,
116
- material: game ?? (mdl ? mdl.materials.map(fx) : fx(o.material ?? this._neutral(o))),
117
- });
128
+ const material = game ?? (mdl ? mdl.materials.map(fx) : fx(o.material ?? this._neutral(o)));
129
+ // what was built here and is ours to free (the game's geometry and materials stay the game's); a mesh still drawing the old ones uploads them again
130
+ const made = [...(lodMdl?.materials ?? []), ...(lod && lod !== o.lodGeometry ? [lod] : []), ...(mdl ? [mdl.geometry, ...material] : shared && !game ? [material] : [])];
131
+ const old = this.kinds.get(sp.name);
132
+ this.kinds.set(sp.name, { geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod, fadeUniforms: game ? null : nf?.uniforms ?? null, shared, material, made });
133
+ for (const d of old?.made ?? []) d.dispose();
118
134
  }
119
135
  _neutral(o) {
120
136
  const m = neutralMaterial('vegetation', { vertexColors: true, side: o.doubleSided ? THREE.DoubleSide : THREE.FrontSide });
@@ -147,13 +163,14 @@ export class VegetationDraw {
147
163
  a.set(r.m);
148
164
  if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 + 16);
149
165
  im.instanceMatrix.needsUpdate = true;
166
+ im.count = drawnPlants(sp.rule, r, this.v.host.density);
150
167
  if (c.ring != null) this._level(im, sp, k, c.ring);
151
168
  }
152
169
 
153
170
  /** @internal view hook: the chunk's ring changed (or shadows were switched): draw distance, low-poly swap and shadows of every species there */
154
171
  ring(c, ring) {
155
172
  const rec = this.meshes.get(c); if (!rec) return;
156
- for (const n in rec.ims) { const sp = this.v.get(n), k = this.kinds.get(n); if (sp && k && !sp.nearOnly) this._level(rec.ims[n], sp, k, ring); }
173
+ for (const n in rec.ims) { const sp = this.v.get(n), k = this.kinds.get(n); if (sp && k) this._level(rec.ims[n], sp, k, ring); }
157
174
  }
158
175
  /** @internal view hook: in view or not (ring 1 is always in view, farther chunks by the camera frustum) */
159
176
  show(c, visible) { const rec = this.meshes.get(c); if (rec) rec.group.visible = visible; }
@@ -177,7 +194,7 @@ export class VegetationDraw {
177
194
  im.castShadow = !!this.engine.renderer?.shadowMap?.enabled && sp.castShadow && ring <= sp.shadowRing;
178
195
  }
179
196
  _chunk(c) {
180
- const CH = this.v.host.CHUNK, g = new THREE.Group();
197
+ const CH = this.v.host.chunkSize, g = new THREE.Group();
181
198
  g.userData.budgetTag = 'vegetation';
182
199
  g.position.set(c.cx * CH, 0, c.cz * CH); g.matrixAutoUpdate = false; g.updateMatrix();
183
200
  g.visible = c.inView !== false;
@@ -187,5 +204,9 @@ export class VegetationDraw {
187
204
  return rec;
188
205
  }
189
206
 
190
- dispose() { this._view.remove(); this.kinds.clear(); }
207
+ dispose() {
208
+ this._view.remove();
209
+ for (const k of this.kinds.values()) for (const d of k.made) d.dispose();
210
+ this.kinds.clear(); this._base.dispose();
211
+ }
191
212
  }