threedog 1.1.0 → 1.3.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 (370) hide show
  1. package/CHANGELOG.md +893 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +187 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +17 -7
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +8 -7
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +50 -28
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +36 -15
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +47 -4
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +17 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +30 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +24 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +7 -2
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +75 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +10 -9
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +72 -79
  180. package/docs/recipes/63-third-person-start.md +48 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/.threedog/content-index.json +1 -1
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/.threedog/content-index.json +1 -1
  189. package/examples/perf-island/GAMEMAP.md +3 -3
  190. package/examples/perf-island/picture/lights.js +2 -1
  191. package/examples/plain-picture/GAMEMAP.md +1 -1
  192. package/examples/rc2d/GAMEMAP.md +1 -1
  193. package/examples/styletest/.threedog/content-index.json +1 -1
  194. package/examples/styletest/GAMEMAP.md +2 -2
  195. package/examples/styletest/main.js +1 -1
  196. package/examples/techniques/interior-light/README.md +3 -3
  197. package/examples/techniques/interior-light/interiorLight.js +2 -4
  198. package/examples/techniques/interior-light/picture/lights.js +2 -1
  199. package/examples/techniques/modular-building/picture/lights.js +3 -1
  200. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  201. package/examples/techniques/procedural-animation/README.md +1 -1
  202. package/examples/techniques/procedural-animation/main.js +1 -1
  203. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  204. package/examples/world/.threedog/content-index.json +1 -1
  205. package/examples/world/GAMEMAP.md +2 -3
  206. package/examples/world/art/humanoid.js +1 -1
  207. package/examples/world/main.js +6 -3
  208. package/index.d.ts +2 -2
  209. package/llms.txt +101 -0
  210. package/modules/ambience/Ambience.js +21 -5
  211. package/modules/calendar/index.js +9 -5
  212. package/modules/calendar/schedule.js +23 -8
  213. package/modules/camera/FirstPersonCamera.js +3 -1
  214. package/modules/camera/FollowCamera.js +10 -5
  215. package/modules/camera/RtsCamera.js +4 -3
  216. package/modules/camera/common.js +70 -8
  217. package/modules/camera/contract.js +1 -1
  218. package/modules/characters/Character.js +16 -10
  219. package/modules/characters/NPC.js +31 -19
  220. package/modules/characters/assetModel.js +14 -9
  221. package/modules/characters/astar.js +6 -1
  222. package/modules/characters/contract.js +2 -2
  223. package/modules/characters/index.js +34 -22
  224. package/modules/characters/movers/manual.js +1 -1
  225. package/modules/characters/movers/rapier.js +17 -2
  226. package/modules/characters/movers/simple.js +1 -1
  227. package/modules/characters/movers/support.js +16 -7
  228. package/modules/characters/npcAvoid.js +2 -2
  229. package/modules/characters/npcSim.js +3 -2
  230. package/modules/characters/pathAsync.js +24 -8
  231. package/modules/characters/pathJob.js +1 -1
  232. package/modules/characters/player.js +10 -9
  233. package/modules/characters/playerStrings.js +5 -5
  234. package/modules/characters/proceduralRig.js +5 -5
  235. package/modules/characters/useModel.js +6 -0
  236. package/modules/characters/walkTo.js +1 -1
  237. package/modules/collision/Collision.js +29 -18
  238. package/modules/collision/grid.js +22 -4
  239. package/modules/content/index.js +3 -1
  240. package/modules/content/loader.js +1 -1
  241. package/modules/content/models.js +82 -33
  242. package/modules/content/props.js +2 -1
  243. package/modules/content/rules.js +11 -5
  244. package/modules/content/templates.js +3 -3
  245. package/modules/content/words.js +2 -2
  246. package/modules/debug/DebugPanel.js +9 -9
  247. package/modules/flow/index.js +9 -6
  248. package/modules/gameplay/Dialogue.js +34 -20
  249. package/modules/gameplay/Interactions.js +19 -15
  250. package/modules/gameplay/Inventory.js +9 -4
  251. package/modules/gameplay/Quests.js +12 -10
  252. package/modules/gameplay/pickups.js +23 -11
  253. package/modules/grid/index.js +1 -1
  254. package/modules/grid/preview.js +2 -2
  255. package/modules/grid/tiles.js +1 -1
  256. package/modules/hlod/index.js +4 -1
  257. package/modules/hud/index.js +47 -10
  258. package/modules/hud/parts.js +28 -9
  259. package/modules/level/geometry.js +8 -3
  260. package/modules/level/index.js +10 -5
  261. package/modules/level/load.js +4 -2
  262. package/modules/lights/sources.js +1 -1
  263. package/modules/music/Music.js +22 -4
  264. package/modules/nav/index.js +20 -10
  265. package/modules/particles/Particles.js +31 -14
  266. package/modules/particles/effect.js +20 -5
  267. package/modules/particles/lit.js +72 -0
  268. package/modules/photo/Photo.js +72 -28
  269. package/modules/photo/pathTrace.js +106 -0
  270. package/modules/rigid/RigidBodies.js +23 -14
  271. package/modules/rigid/Vehicles.js +3 -13
  272. package/modules/rigid/sync.js +2 -1
  273. package/modules/settings/Settings.js +52 -20
  274. package/modules/settings/apply.js +23 -9
  275. package/modules/settings/sections.js +39 -6
  276. package/modules/settings/strings.js +2 -0
  277. package/modules/settings/view.js +19 -3
  278. package/modules/sky/dome.js +15 -3
  279. package/modules/sky/environment.js +28 -12
  280. package/modules/sky/fog.js +1 -1
  281. package/modules/sky/frame.js +6 -1
  282. package/modules/sky/shader.js +4 -3
  283. package/modules/sky/skyModule.js +8 -4
  284. package/modules/swarm/Swarm.js +1 -1
  285. package/modules/terrain/ChunkManager.js +61 -15
  286. package/modules/terrain/chunkJob.js +2 -2
  287. package/modules/terrain/index.js +20 -5
  288. package/modules/terrain/terrainEdit.js +8 -4
  289. package/modules/terrain/terrainTexture.js +4 -2
  290. package/modules/timeline/Timeline.js +4 -3
  291. package/modules/timeline/Tween.js +3 -0
  292. package/modules/timeline/letterbox.js +1 -0
  293. package/modules/triggers/index.js +36 -17
  294. package/modules/vegetation/Vegetation.js +81 -19
  295. package/modules/vegetation/densityMap.js +13 -8
  296. package/modules/vegetation/draw.js +147 -24
  297. package/modules/vegetation/groundChunks.js +20 -5
  298. package/modules/vegetation/index.js +3 -3
  299. package/modules/vegetation/modelGeometry.js +9 -4
  300. package/modules/water/Water.js +11 -8
  301. package/modules/weather/Weather.js +7 -2
  302. package/modules/weather/shaders.js +25 -5
  303. package/modules/weather/weatherDraw.js +20 -6
  304. package/modules/world/World.js +2 -1
  305. package/modules/world/index.js +2 -2
  306. package/modules/world/persist.js +6 -2
  307. package/modules/world/views.js +15 -2
  308. package/package.json +5 -1
  309. package/presets.js +5 -5
  310. package/render/PostFX.js +102 -42
  311. package/render/backend.js +142 -16
  312. package/render/bindingLimits.js +59 -0
  313. package/render/cascades.js +3 -1
  314. package/render/cascades.tsl.js +2 -0
  315. package/render/daylight.js +7 -1
  316. package/render/detail.js +7 -4
  317. package/render/effects.js +27 -8
  318. package/render/fogLook.js +24 -0
  319. package/render/fuse.js +5 -2
  320. package/render/fx/compareLevel.tsl.js +23 -0
  321. package/render/fx/detail.tsl.js +9 -7
  322. package/render/fx/index.js +9 -2
  323. package/render/fx/library.tsl.js +1 -0
  324. package/render/fx/lightShaft.tsl.js +114 -0
  325. package/render/fx/noise.tsl.js +25 -8
  326. package/render/fx/objectOrigin.tsl.js +39 -10
  327. package/render/fx/particles.tsl.js +23 -6
  328. package/render/fx/patchNodes.tsl.js +17 -12
  329. package/render/fx/pcss.tsl.js +51 -0
  330. package/render/fx/postWebGPU.tsl.js +104 -29
  331. package/render/fx/sky.tsl.js +3 -9
  332. package/render/fxNumbers.js +10 -4
  333. package/render/impostor.tsl.js +107 -0
  334. package/render/lighting.js +33 -1
  335. package/render/lightmap.js +42 -28
  336. package/render/lights.js +19 -3
  337. package/render/materials.js +6 -4
  338. package/render/mergeCommon.js +4 -1
  339. package/render/occlusion.js +14 -4
  340. package/render/patches.js +79 -41
  341. package/render/postRuns.js +32 -0
  342. package/render/postWebGL.js +97 -10
  343. package/render/probes.js +10 -14
  344. package/render/shaderErrors.js +44 -7
  345. package/render/shadowCache.tsl.js +33 -5
  346. package/render/shadows.js +42 -16
  347. package/render/slots.js +8 -5
  348. package/render/vertexInputs.js +52 -0
  349. package/types/core.d.ts +115 -47
  350. package/types/gameplay.d.ts +56 -23
  351. package/types/generated/core/audio/Audio.d.ts +27 -1
  352. package/types/generated/core/base/Random.d.ts +1 -1
  353. package/types/generated/core/input/Input.d.ts +6 -8
  354. package/types/generated/core/input/inputSeat.d.ts +1 -1
  355. package/types/generated/core/inspect/Budget.d.ts +26 -0
  356. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  357. package/types/generated/core/saves/Saves.d.ts +10 -7
  358. package/types/generated/core/saves/session.d.ts +8 -2
  359. package/types/generated/core/scene/Rays.d.ts +1 -3
  360. package/types/generated/core/scene/Views.d.ts +17 -3
  361. package/types/generated/modules/particles/Particles.d.ts +1 -1
  362. package/types/generated/modules/world/World.d.ts +2 -1
  363. package/types/generated/render/PostFX.d.ts +35 -9
  364. package/types/physics.d.ts +796 -764
  365. package/types/pixel.d.ts +1 -1
  366. package/types/tsl.d.ts +62 -1
  367. package/types/world.d.ts +12 -3
  368. package/ui/Focus.js +7 -5
  369. package/ui/Parts.js +1 -1
  370. package/ui/touchPart.js +6 -3
@@ -7,6 +7,8 @@ import { vegetationModel } from '../../core/assets/namedModel.js';
7
7
  import { isModelName } from '../../core/base/util.js';
8
8
  import { DEV, warnMissing, warnOnce } from '../../core/base/validate.js';
9
9
  import { readParams, keysSchema } from '../../core/base/params.js';
10
+ // radius must be finite: an Infinity radius makes the chunk loops below start at -Infinity and never advance
11
+ const AT_PARAMS = keysSchema(['radius', 'species'], {}, { radius: { type: 'number', min: 0, optional: true } });
10
12
  import { reportError } from '../../core/base/errors.js';
11
13
  import { xzOf } from '../../core/base/math.js';
12
14
  import { GroundChunks } from './groundChunks.js';
@@ -14,7 +16,20 @@ import { fadeBand } from './nearFade.js';
14
16
  import { makeDensity, thin } from './densityMap.js';
15
17
  import { coded, codedError } from '../../core/base/errorHints.js';
16
18
  // parameters read by vegetation.define(); keys inside rule (sent to the worker thread)
17
- const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'positions', 'densityMap', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade'];
19
+ const ADD_KEYS = ['geometry', 'model', 'lodGeometry', 'rule', 'positions', 'densityMap', 'wind', 'nearOnly', 'maxRing', 'lodRing', 'castShadow', 'shadowRing', 'receiveShadow', 'material', 'effects', 'doubleSided', 'fade', 'impostor'];
20
+ /**
21
+ * The grass-shadow hint, or null: a species that is grass-scale by its own declaration (nearOnly, or drawn in the nearest ring only: maxRing 1) and
22
+ * casts shadow by the engine default (castShadow ?? !nearOnly, as define() reads it) without the game having chosen: a castShadow or shadowRing
23
+ * written out silences it. Thousands of small plants pay a shadow draw per chunk and cascade for a speckle few see. define() warns with it in dev,
24
+ * content check (tools/content-check/world.mjs) reports it as a hint: one predicate for both
25
+ * @param {string} name @param {any} o the define() / content options @returns {string | null}
26
+ */
27
+ export function grassShadowHint(name, o) {
28
+ const small = o?.nearOnly || o?.maxRing <= 1, casts = o?.castShadow ?? !o?.nearOnly;
29
+ if (!small || !casts || o.castShadow !== undefined || o.shadowRing !== undefined) return null;
30
+ return `vegetation ${name} is grass-scale (${o.nearOnly ? 'nearOnly' : 'maxRing 1'}) and casts shadows by default, a shadow draw per chunk and cascade for little to see: `
31
+ + 'set castShadow: false, or shadowRing: 0 to keep them only in the nearest ring (castShadow: true keeps them and silences this)';
32
+ }
18
33
  const RULE_KEYS = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'scale', 'stretch', 'sink', 'tintJitter', 'tints', 'biomes', 'collider', 'avoidFlat', 'salt'];
19
34
  // rule keys that only filter random attempts: with positions the game already chose every spot, so naming one is a mistake, not a no-op
20
35
  const SCATTER_ONLY = ['perChunk', 'chance', 'minHeight', 'maxHeight', 'maxSlope', 'cluster', 'biomes', 'avoidFlat'];
@@ -36,7 +51,7 @@ function checkPositions(label, list, rule) {
36
51
  // const hit = engine.vegetation.instanceAt(position, { radius: 2, species: '松树' }); // → { species, cx, cz, id, position } or null
37
52
  // engine.vegetation.removeInstance(hit.species, hit.cx, hit.cz, hit.id, { regrowSeconds: 300 }); // grows back after 300 calendar seconds
38
53
  // engine.vegetation.restoreInstance(...) // restore immediately
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.
54
+ // Hiding: the slot goes into c.hidden[name] (the draw part draws it at zero scale, count unchanged) and out of the chunk's collision circles.
40
55
  // Regrowth: the record stores the expiry time (engine.calendar seconds), checked once per second; the clock is saved, so the countdown continues after
41
56
  // reload.
42
57
  const KEY_RE = /^veg:(.*):(-?\d+),(-?\d+):(\d+)$/;
@@ -50,10 +65,22 @@ function slotOf(r, id) {
50
65
  }
51
66
 
52
67
  const REMOVE_KEYS = ['regrowSeconds'];
68
+ // impostor: true / false or { views, size }. The numbers size render targets (views layers of size x size), and content data can carry them,
69
+ // so a 0, NaN or huge value is refused here instead of building an empty or enormous target
70
+ function checkImpostor(label, v) {
71
+ if (v === true || v === false) return;
72
+ const bad = m => { throw codedError('vegetation-option', `${label}: impostor ${m}; write impostor: true or { views: 1..64, size: 16..1024 } (whole numbers)`); };
73
+ if (!v || typeof v !== 'object' || Array.isArray(v)) bad(`is ${JSON.stringify(v)}`);
74
+ readParams(`${label}.impostor`, keysSchema(['views', 'size']), v);
75
+ const int = (k, lo, hi) => { const n = v[k]; if (n !== undefined && !(Number.isInteger(n) && n >= lo && n <= hi)) bad(`${k} is ${JSON.stringify(n)}`); };
76
+ int('views', 1, 64); int('size', 16, 1024);
77
+ }
53
78
 
54
79
  export class Vegetation {
55
80
  constructor(engine, opts = {}, ctx) {
56
81
  this.engine = engine; this.species = new Map();
82
+ /** this instance is over (removed or replaced, or the engine is gone): a late model or image must not write into the world any more */
83
+ this._gone = () => ctx.signal?.aborted || engine.disposed;
57
84
  // where it grows: on terrain chunks when the terrain module is installed (placed in its workers), else on vegetation's own chunks over
58
85
  // whatever provides the ground (a level, a code-built ground, flat). Both hosts keep chunks of one shape, so everything below is shared
59
86
  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)`);
@@ -74,7 +101,7 @@ export class Vegetation {
74
101
  // 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
75
102
  // not in the generic scene walk: a species' materials are patched copies (wind, season) and its geometry may be merged from a model
76
103
  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',
104
+ ctx.saves.define('vegetation', { notAtomic: 'its load redraws the instances it hides: not plain data a rollback restores by itself',
78
105
  save: () => {
79
106
  const removed = {};
80
107
  for (const [ck, m] of this._removed) { for (const [id, until] of m) removed[`veg:${ck}:${id}`] = until; }
@@ -114,18 +141,22 @@ export class Vegetation {
114
141
  * fade near-only species shrink out over a band [start, end] metres from the player instead of popping at the ring edge (default on for
115
142
  * nearOnly, end = maxRing x chunk size; false = hard edge; { start, end } sets the band)
116
143
  * lodRing switch to low-poly beyond this ring count
144
+ * impostor true or { views = 8, size = 128 }: beyond lodRing draw cards baked from this species' own model and materials (one draw for all far
145
+ * chunks, lit live through baked normals, no shadow there). Instead of lodGeometry, not with it. WebGPU only; WebGL draws the mesh
117
146
  * castShadow / shadowRing whether to cast shadows, and within how many rings
118
147
  * material this species' own three.js material (optional; default is engine.vegetation.material); wind, cloud shadows, season tint and the
119
148
  * near fade are added to it (and its shadow sways) unless effects: false
120
149
  */
121
150
  define(name, o) {
122
151
  readParams(`vegetation.define('${name}')`, keysSchema(ADD_KEYS), o);
152
+ const grass = DEV && grassShadowHint(name, o);
153
+ if (grass) warnOnce(grass, 'grass-shadow\0' + name);
123
154
  // a model name ('pine' / ['flower', color]) means what it means in content: resolved through the same vegetationModel (cache, bake, file or
124
155
  // generator), then added as if the geometry / Object3D had been passed. Returns a Promise of the species then; start waits for it like a density image
125
156
  if (isModelName(o.model) || isModelName(o.lodGeometry)) {
126
157
  const p = Promise.all([isModelName(o.model) ? vegetationModel(this.engine, o.model) : { model: o.model }, isModelName(o.lodGeometry) ? vegetationModel(this.engine, o.lodGeometry) : null])
127
158
  .then(([main, low]) => {
128
- if (this.engine.disposed) return null;
159
+ if (this._gone()) return null;
129
160
  const { model: _m, ...rest } = o;
130
161
  return this.define(name, { ...rest, ...(main.model ? { model: main.model } : { geometry: main.geometry ?? o.geometry }), ...(low && { lodGeometry: low.model ?? low.geometry }) });
131
162
  });
@@ -137,6 +168,9 @@ export class Vegetation {
137
168
  if (o.positions != null) checkPositions(`vegetation.define('${name}')`, o.positions, o.rule);
138
169
  const density = o.densityMap != null ? makeDensity(o.densityMap, `vegetation.define('${name}')`) : null;
139
170
  // distance fade band of near-only species (nearFade.js), checked here so a bad band throws at define; the draw part draws it
171
+ // impostor and lodGeometry both say what is drawn beyond lodRing: one owner (docs/plans/2026-11-09-impostors.md)
172
+ if (o.impostor && o.lodGeometry) throw codedError('vegetation-option', `vegetation.define('${name}'): impostor and lodGeometry both say what is drawn beyond lodRing; keep one`);
173
+ if (o.impostor != null) checkImpostor(`vegetation.define('${name}')`, o.impostor);
140
174
  if (o.fade && typeof o.fade === 'object') readParams(`vegetation.define('${name}').fade`, keysSchema(['start', 'end']), o.fade);
141
175
  const maxRing = o.maxRing ?? (o.nearOnly ? 1 : 99);
142
176
  const sp = {
@@ -155,8 +189,8 @@ export class Vegetation {
155
189
  // a density image still loading: this species places nothing until it is in, then every chunk is placed again. The module's init waits
156
190
  // for those added before start, so a game never opens on a bare map; one added later fills in when its image arrives
157
191
  if (density?.pending) {
158
- // the image may arrive after engine.dispose(): then chunks and meshes are gone, so no rebuild
159
- const p = density.pending.then(() => { if (!this.engine.disposed && this.species.get(name) === sp) this.host.rebuild(); });
192
+ // the image may arrive after this instance was removed (or engine.dispose()): the terrain may stay and be another instance's, so no rebuild
193
+ const p = density.pending.then(() => { if (!this._gone() && this.species.get(name) === sp) this.host.rebuild(); });
160
194
  // only species added before init took _pending are awaited by init (a failure fails start); later ones nobody awaits, so report once
161
195
  // (soft: the species just stays empty, gameplay is not frozen for a missing image)
162
196
  if (!this._initDone) this._pending.push(p);
@@ -269,13 +303,15 @@ export class Vegetation {
269
303
  */
270
304
  view(v) {
271
305
  this.views.add(v);
272
- for (const sp of this.species.values()) v.species?.(sp);
273
- for (const c of this.host.chunks.values()) {
274
- if (c.state !== 'ready') continue;
275
- for (const n in c.plants) v.change?.(c, n);
276
- if (c.ring != null) v.ring?.(c, c.ring);
277
- if (c.inView === false) v.show?.(c, false);
278
- }
306
+ try { // a view that throws while the existing data is replayed is not registered: _emit would keep calling it and starve the views after it
307
+ for (const sp of this.species.values()) v.species?.(sp);
308
+ for (const c of this.host.chunks.values()) {
309
+ if (c.state !== 'ready') continue;
310
+ for (const n in c.plants) v.change?.(c, n);
311
+ if (c.ring != null) v.ring?.(c, c.ring);
312
+ if (c.inView === false) v.show?.(c, false);
313
+ }
314
+ } catch (e) { this.views.delete(v); throw e; }
279
315
  return { remove: () => { if (!this.views.delete(v)) return; for (const c of this.host.chunks.values()) if (c.state === 'ready') v.drop?.(c); } };
280
316
  }
281
317
  /** @internal tell every view */
@@ -319,12 +355,25 @@ export class Vegetation {
319
355
  for (const d of due) this.restoreInstance(...d);
320
356
  }
321
357
 
358
+ /**
359
+ * The plant a ray hit, read from the hit itself (no spatial guess): the same { species, cx, cz, id, position } instanceAt returns, so it goes straight to
360
+ * removeInstance / key; null when the hit is not a vegetation draw mesh, or is the far impostor card
361
+ * @param {{ object?: any, instanceId?: number }} hit a raycast hit (engine.pick)
362
+ * @returns {{ species: string, cx: number, cz: number, id: number, position: Vector3 } | null}
363
+ */
364
+ plantOf(hit) {
365
+ const u = hit?.object?.userData, i = hit?.instanceId, id = u?.plants?.ids?.[i];
366
+ if (u?.species == null || id == null) return null;
367
+ const a = u.plants.m, CH = this.host.chunkSize;
368
+ return { species: u.species, cx: u.cx, cz: u.cz, id, position: new Vector3(u.cx * CH + a[i * 16 + 12], a[i * 16 + 13], u.cz * CH + a[i * 16 + 14]) };
369
+ }
370
+
322
371
  /**
323
372
  * Nearest instance within radius meters (default 2) of position (loaded chunks only; species restricts to one kind): { species, cx, cz, id, position } or
324
373
  * null
325
374
  */
326
375
  instanceAt(position, opts = {}) {
327
- readParams('vegetation.instanceAt()', keysSchema(['radius', 'species']), opts);
376
+ readParams('vegetation.instanceAt()', AT_PARAMS, opts);
328
377
  const [x, z] = xzOf(position), { radius = 2, species = null } = typeof opts === 'object' && opts ? opts : {};
329
378
  const T = this.host, CH = T.chunkSize;
330
379
  let best = null, bestD = radius * radius;
@@ -346,24 +395,37 @@ export class Vegetation {
346
395
  }
347
396
 
348
397
  /** @internal chunk plumbing (terrain chunks and ground chunks): one species' placement result r for chunk c (data; the draw parts draw it) */
349
- mount(c, name, r) {
398
+ mount(c, name, r, held = false) {
350
399
  const sp = this.species.get(name);
400
+ if (!sp) return; // a result of a species this instance does not know (a removed instance's job, or one taken back): no plants, no colliders without a draw kind
351
401
  // densityMap thins here, before the colliders are taken, so a dropped plant blocks nothing; survivors keep their stable ids
352
- if (sp?.density) r = thin(r, c.cx * this.host.chunkSize, c.cz * this.host.chunkSize, sp.density.at, sp.rule.salt);
402
+ if (sp.density) r = thin(r, c.cx * this.host.chunkSize, c.cz * this.host.chunkSize, sp.density.at, sp.rule.salt);
353
403
  c.plants ||= {}; c.colliders ||= {}; c.collidersAll ||= {};
354
404
  // 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
355
405
  if (r.n === 0) delete c.plants[name]; else c.plants[name] = r;
356
406
  if (r.n && r.k?.length) c.collidersAll[name] = r.k; else delete c.collidersAll[name]; // original circles (before felled trees are filtered)
407
+ // held: the plants are drawn but their colliders wait for release() (a near-only species whose collision takes effect on a committed tick)
408
+ if (held) (c.held ||= {})[name] = true; else if (c.held) delete c.held[name];
357
409
  this.applyEdits(c, name); // felled trees stay gone after reload; sets the colliders and tells the draw parts
358
410
  }
411
+ /** @internal chunk plumbing: the held colliders of a species take effect */
412
+ release(c, name) { if (c.held?.[name]) { delete c.held[name]; this.applyEdits(c, name); } }
359
413
  /** @internal chunk plumbing: drop a near-only species from a chunk that moved out of its ring */
360
414
  unmount(c, name) {
361
415
  if (!c.plants?.[name]) return;
362
- delete c.plants[name]; delete c.collidersAll?.[name];
416
+ delete c.plants[name]; delete c.collidersAll?.[name]; if (c.held) delete c.held[name];
363
417
  this.applyEdits(c, name);
364
418
  }
419
+ /**
420
+ * @internal the module is removed: on terrain the chunks stay and are not ours, so take back what this instance placed on them (plants, tree
421
+ * colliders, treeToken so physics drops the trunks) through unmount, then let go of the terrain. The own ground chunks go with the module
422
+ */
423
+ detach() {
424
+ if (this._planter) for (const c of this.host.chunks.values()) for (const n in c.plants) this.unmount(c, n);
425
+ this._view?.remove(); this._planter?.remove();
426
+ }
365
427
  /** @internal chunk plumbing: the chunk was released */
366
- drop(c) { this._emit('drop', c); c.plants = {}; c.hidden = null; }
428
+ drop(c) { this._emit('drop', c); c.plants = {}; c.hidden = null; c.held = null; }
367
429
  /** @internal chunk plumbing: the chunk's ring changed; the draw parts pick draw distance, low-poly swap and shadows from it */
368
430
  ring(c, ring) { c.ring = ring; this._emit('ring', c, ring); }
369
431
 
@@ -373,7 +435,7 @@ export class Vegetation {
373
435
  if (r) for (const id of this._removed.get(`${name}:${c.cx},${c.cz}`)?.keys() ?? []) { const s = slotOf(r, id); if (s !== undefined) hid.add(s); }
374
436
  (c.hidden ||= {})[name] = hid.size ? hid : null;
375
437
  // collision circles map one-to-one to instances (instance i = group i of [x, z, r]); drop the hidden ones
376
- const all = r ? c.collidersAll?.[name] : null, before = c.colliders[name];
438
+ const all = r && !c.held?.[name] ? c.collidersAll?.[name] : null, before = c.colliders[name];
377
439
  if (!all) delete c.colliders[name];
378
440
  else if (!hid.size) c.colliders[name] = all;
379
441
  else {
@@ -40,14 +40,8 @@ function roll(id, salt) {
40
40
  return (h >>> 0) / 4294967296;
41
41
  }
42
42
 
43
- /** Placement result r of chunk origin (ox, oz) with only the instances whose roll is under the density at their spot (same shape as r) */
44
- export function thin(r, ox, oz, at, salt) {
45
- if (!r.n) return r;
46
- const keep = [];
47
- for (let i = 0; i < r.n; i++) {
48
- const d = at(ox + r.m[i * 16 + 12], oz + r.m[i * 16 + 14]);
49
- if (d > 0 && roll(r.ids[i], salt) < d) keep.push(i);
50
- }
43
+ /** Placement result r with only the instances at the indices `keep` (same shape as r; r itself when all stay) */
44
+ export function select(r, keep) {
51
45
  if (keep.length === r.n) return r;
52
46
  const n = keep.length, m = new Float32Array(n * 16), c = new Float32Array(n * 3), ids = new Uint32Array(n), hasK = r.k && r.k.length;
53
47
  const k = new Float32Array(hasK ? n * 3 : 0);
@@ -57,3 +51,14 @@ export function thin(r, ox, oz, at, salt) {
57
51
  });
58
52
  return { ...r, m, c, k, ids, n };
59
53
  }
54
+
55
+ /** Placement result r of chunk origin (ox, oz) with only the instances whose roll is under the density at their spot (same shape as r) */
56
+ export function thin(r, ox, oz, at, salt) {
57
+ if (!r.n) return r;
58
+ const keep = [];
59
+ for (let i = 0; i < r.n; i++) {
60
+ const d = at(ox + r.m[i * 16 + 12], oz + r.m[i * 16 + 14]);
61
+ if (d > 0 && roll(r.ids[i], salt) < d) keep.push(i);
62
+ }
63
+ return select(r, keep);
64
+ }
@@ -1,6 +1,7 @@
1
1
  // Vegetation drawing: draws what the vegetation data part placed. One InstancedMesh per species per chunk from the chunk's placement records
2
2
  // (c.plants[name]: m matrices, c colors, ids, n), the species' geometry / low-poly geometry / material (wind sway, season tint, near fade
3
- // patched in), ring LOD (draw distance, low-poly swap, shadow distance) and frustum visibility. Installed by vegetation() as its own module
3
+ // patched in), ring LOD (draw distance, low-poly swap, shadow distance) and frustum visibility (per mesh and per camera, by three: cullSphere). No show() hook: hiding
4
+ // a chunk's group off the main view also took its shadows out of every shadow pass (three skips invisible parents). Installed by vegetation() as its own module
4
5
  // 'vegetationDraw' holding the slot 'vegetation-draw'. Its picture entries are reached through engine.vegetation: material, patches, sway(), color().
5
6
  //
6
7
  // Why a separate module: collision, paths, felling and instanceAt read only the data part, so a game can swap the whole plant picture
@@ -8,15 +9,16 @@
8
9
  // 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
10
  // This file never changes placement data; it only reads it.
10
11
  import { engineOwned } from '../../core/scene/things.js';
11
- import { needMaterial, oneForm } from '../../core/base/validate.js';
12
+ import { drawOnly } from '../../core/scene/drawOnly.js';
13
+ import { needMaterial, oneForm, warnOnce } from '../../core/base/validate.js';
12
14
  import * as THREE from 'three';
13
15
  import { fromModel } from './modelGeometry.js';
14
16
  import { applyEffects, windCustom } from '../../render/materials.js';
15
17
  import { neutralMaterial } from '../../render/neutral.js';
16
- import { patchMaterial, unpatchMaterial } from '../../render/patches.js';
18
+ import { patchMaterial, unpatchMaterial, cloneMaterial } from '../../render/patches.js';
17
19
  import { EFFECTS, hashText } from '../../render/effects.js';
18
20
  import { codedError } from '../../core/base/errorHints.js';
19
- import { isWebGPU } from '../../render/backend.js';
21
+ import { isWebGPU, webgpuPart, onRendererSwap } from '../../render/backend.js';
20
22
  import { nearFadePatch } from './nearFade.js';
21
23
  import { scatterAttempts } from '../../core/stream/scatter.js';
22
24
 
@@ -24,6 +26,14 @@ const COLOR = 'vegetationColor'; // the patch name of vegetation.color() on ev
24
26
  // The wind patch in engine.vegetation.patches has one amplitude: a shared material cannot carry each species' own (those are define()'s wind option)
25
27
  const SHARED_SWAY = 0.05;
26
28
  const code = v => (typeof v === 'string' ? { glsl: v } : v);
29
+ // what applyEffects adds to a species' material (render/effects.js names, the near fade, vegetation.color()): taken off the impostor's bake copy
30
+ const FX_NAMES = ['wind', 'clouds', 'season', 'world', 'detail'];
31
+ /** A copy of a game material without the engine's effect patches (its own patches stay) @param {any} m @param {any[]} own this species' own patches */
32
+ function unpatched(m, own) {
33
+ const c = cloneMaterial(m);
34
+ for (const n of [...FX_NAMES, ...own.map(p => p.name)]) unpatchMaterial(c, n);
35
+ return c;
36
+ }
27
37
 
28
38
  /**
29
39
  * 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
@@ -39,6 +49,23 @@ export function drawnPlants(rule, r, density) {
39
49
  return n;
40
50
  }
41
51
 
52
+ /**
53
+ * The culling sphere of one chunk's plants of one species, so three culls the mesh per camera: the main view skips the chunks it does not see, and
54
+ * each shadow camera (every cascade) draws only the chunks inside its own box. With frustumCulled off every cascade drew every casting chunk and the
55
+ * nearest ring drew behind the camera too: the draw count of a grassy scene, for nothing on screen. Grown by twice the largest plant: the built-in
56
+ * sway moves a vertex by its height x amplitude x wind, within the plant's own height while amplitude x wind stays under 1; the low-poly geometry
57
+ * counts too, as _level swaps it in without a recompute.
58
+ * shortcut: a game's own sway() moving plants farther than their height could clip them at the screen edge; then grow the margin from the sway.
59
+ */
60
+ function cullSphere(im, k) {
61
+ im.boundingSphere = null; im.computeBoundingSphere(); // three: each instance matrix x the geometry's sphere, over im.count
62
+ const a = im.instanceMatrix.array;
63
+ let s2 = 0;
64
+ for (let o = 0; o < im.count * 16; o += 16) s2 = Math.max(s2, a[o] ** 2 + a[o + 1] ** 2 + a[o + 2] ** 2, a[o + 4] ** 2 + a[o + 5] ** 2 + a[o + 6] ** 2, a[o + 8] ** 2 + a[o + 9] ** 2 + a[o + 10] ** 2);
65
+ const radius = g => { if (!g) return 0; if (!g.boundingSphere) g.computeBoundingSphere(); return g.boundingSphere.radius + g.boundingSphere.center.length(); };
66
+ im.boundingSphere.radius += 2 * Math.sqrt(s2) * Math.max(radius(k.geometry), radius(k.lodGeometry));
67
+ }
68
+
42
69
  export class VegetationDraw {
43
70
  /** @param {any} e @param {any} v the vegetation data part (engine.vegetation) */
44
71
  constructor(e, v) {
@@ -53,6 +80,12 @@ export class VegetationDraw {
53
80
  /** @internal chunk record -> { group, ims: { name: InstancedMesh } } */ this.meshes = new Map();
54
81
  this._refreshPatches();
55
82
  this._view = v.view(this);
83
+ /** @internal */ this._swap = onRendererSwap(e, () => {
84
+ if (isWebGPU(e.renderer)) return;
85
+ let any = false;
86
+ for (const [n, k] of this.kinds) if (k.impostor) { this._dropCards(k); k.impostor = null; this._noCards(n); any = true; }
87
+ if (any) for (const c of this.meshes.keys()) if (c.ring != null) this.ring(c, c.ring);
88
+ });
56
89
  }
57
90
 
58
91
  /** @internal engine.vegetation.material: every species with no material or model of its own draws it, as given; null gives the neutral default back */
@@ -64,7 +97,11 @@ export class VegetationDraw {
64
97
  const old = this.kinds.get(sp.name);
65
98
  if (old?.shared) this.species(sp);
66
99
  }
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; }
100
+ for (const [c, rec] of this.meshes) for (const n in rec.ims) {
101
+ const k = this.kinds.get(n), im = rec.ims[n]; if (!k) continue;
102
+ im.userData.base = im.material = k.material;
103
+ if (c.ring != null) this._level(im, this.v.get(n), k, c.ring);
104
+ }
68
105
  }
69
106
 
70
107
  /** @internal engine.vegetation.sway(): the new shape reaches the engine's own species materials; a shared material of the game is the game's to re-patch */
@@ -102,8 +139,8 @@ export class VegetationDraw {
102
139
  _eachOwn(fn) {
103
140
  for (const sp of this.v.list()) {
104
141
  const k = this.kinds.get(sp.name);
105
- if (!k || sp.source.effects === false || k.material === this._game) continue;
106
- for (const m of [k.material].flat()) fn(m, sp);
142
+ if (!k || sp.source.effects === false) continue;
143
+ for (const m of [k.material === this._game ? [] : k.material, k.lodMaterial ?? []].flat()) fn(m, sp); // a low-poly model's materials are the engine's even under the game's shared one
107
144
  }
108
145
  }
109
146
 
@@ -125,12 +162,91 @@ export class VegetationDraw {
125
162
  let lod = lodMdl ? lodMdl.geometry : o.lodGeometry || null;
126
163
  if (mdl && lod && !lod.groups.length) { lod = lod.clone(); lod.addGroup(0, Infinity, 0); } // a material array draws nothing without groups
127
164
  const shared = !mdl && !o.material, game = shared ? this._game : null;
165
+ // the impostor bakes the game's material as given: copy it before fx patches it in place (wind, clouds, season baked in, season then twice)
166
+ const bakeOwn = o.impostor && !mdl && o.material ? unpatched(o.material, own) : null;
128
167
  const material = game ?? (mdl ? mdl.materials.map(fx) : fx(o.material ?? this._neutral(o)));
168
+ // a low-poly model keeps its own parts and materials (its groups index its own list, so the part order of the two models need not match), whatever the main one is made of
169
+ const lodMaterial = lodMdl ? lodMdl.materials.map(fx) : null;
129
170
  // 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] : [])];
171
+ const made = [...new Set([...(lodMdl?.materials ?? []), ...(lodMaterial ?? []), ...(lod && lod !== o.lodGeometry ? [lod] : []), ...(mdl ? [mdl.geometry, ...material] : shared && !game ? [material] : [])])];
172
+ // fade: the game's shared material has none, but a low-poly model of the species has its own
131
173
  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 });
174
+ this.kinds.set(sp.name, { geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod, lodMaterial, fadeUniforms: game && !lodMaterial ? null : nf?.uniforms ?? null, shared, material, made,
175
+ impostor: this._impostor(sp, mdl, game, bakeOwn) });
133
176
  for (const d of old?.made ?? []) d.dispose();
177
+ this._dropCards(old);
178
+ }
179
+ /**
180
+ * Far cards of an impostor species (render/impostor.tsl.js): what to bake from and the one card mesh for all its far chunks, built in updateCards().
181
+ * The bake reads materials without the engine's patches, so wind, cloud shadow and season are not baked in (the card adds the season live):
182
+ * a model's own materials (fromModel patched copies of them), an unpatched copy of a species' own material, the game's shared one as drawn
183
+ */
184
+ _impostor(sp, mdl, game, bakeOwn) {
185
+ const o = sp.source;
186
+ if (!o.impostor) return null;
187
+ if (!isWebGPU(this.engine.renderer)) { bakeOwn?.dispose(); this._noCards(sp.name); return null; }
188
+ const own = [];
189
+ o.model?.traverse?.(n => { if (n.isMesh) own.push(n.material); }); // fromModel's order: one group per mesh
190
+ const neutral = !mdl && !o.material && !game ? this._neutral(o) : null;
191
+ return { opts: o.impostor === true ? {} : o.impostor, src: { geometry: mdl ? mdl.geometry : o.geometry, material: mdl ? own : (bakeOwn ?? game ?? neutral), season: o.effects !== false && !game },
192
+ bake: null, mesh: null, dirty: true, neutral, bakeOwn };
193
+ }
194
+ _noCards(name) {
195
+ warnOnce(`vegetation.define('${name}'): impostor cards need the WebGPU renderer (WebGPURenderer); on WebGLRenderer this species draws its full mesh beyond lodRing too`, 'impostor-webgl\0' + name);
196
+ }
197
+ /** Free a species' far cards (redefined or disposed) */
198
+ _dropCards(k) {
199
+ const I = k?.impostor; if (!I) return;
200
+ if (I.mesh) { I.mesh.removeFromParent(); I.mesh.geometry.dispose(); I.mesh.material.dispose(); }
201
+ I.bake?.dispose(); I.neutral?.dispose(); I.bakeOwn?.dispose();
202
+ }
203
+ /**
204
+ * @internal module frame hook: rebuild the far cards of each impostor species whose chunks changed since the last frame. One mesh per species for every
205
+ * chunk beyond lodRing (that is the draw saved). Reads the chunk meshes' instance arrays, so felled plants (zero scale) and thinned counts carry over
206
+ */
207
+ updateCards() {
208
+ for (const [name, k] of this.kinds) {
209
+ const I = k.impostor, sp = this.v.get(name);
210
+ if (!I?.dirty || !sp) continue;
211
+ I.dirty = false;
212
+ const far = [];
213
+ let n = 0;
214
+ for (const [c, rec] of this.meshes) { const im = rec.ims[name]; if (im && c.ring > sp.lodRing && c.ring <= sp.maxRing && im.count) { far.push([c, im]); n += im.count; } }
215
+ if (!n && !I.mesh) continue;
216
+ const part = webgpuPart('impostor', `vegetation '${name}' impostor`);
217
+ I.bake ??= part.bake(this.engine.renderer, I.src, I.opts);
218
+ if (!I.mesh || I.mesh.geometry.userData.capacity < n) this._cardMesh(I, part, Math.max(64, 2 ** Math.ceil(Math.log2(n || 1))), sp);
219
+ const g = I.mesh.geometry, C = g.attributes.aCenter.array, S = g.attributes.aShape.array, T = g.attributes.aTint.array, CH = this.v.host.chunkSize;
220
+ let j = 0;
221
+ for (const [c, im] of far) {
222
+ const a = im.instanceMatrix.array, col = im.instanceColor?.array;
223
+ for (let i = 0; i < im.count; i++, j++) {
224
+ const o = i * 16;
225
+ // yaw-and-scale matrices (placement turns plants about Y and stretches them up): yaw from column 2, across scale from column 0, up from column 1
226
+ C[j * 3] = c.cx * CH + a[o + 12]; C[j * 3 + 1] = a[o + 13]; C[j * 3 + 2] = c.cz * CH + a[o + 14];
227
+ S[j * 3] = Math.atan2(a[o + 8], a[o + 10]); S[j * 3 + 1] = Math.hypot(a[o], a[o + 2]); S[j * 3 + 2] = Math.hypot(a[o + 4], a[o + 5], a[o + 6]);
228
+ if (col) { T[j * 3] = col[i * 3]; T[j * 3 + 1] = col[i * 3 + 1]; T[j * 3 + 2] = col[i * 3 + 2]; } else T.fill(1, j * 3, j * 3 + 3);
229
+ }
230
+ }
231
+ g.instanceCount = n;
232
+ for (const at of [g.attributes.aCenter, g.attributes.aShape, g.attributes.aTint]) at.needsUpdate = true;
233
+ I.mesh.visible = n > 0;
234
+ }
235
+ }
236
+ _cardMesh(I, part, capacity, sp) {
237
+ const old = I.mesh, q = new THREE.PlaneGeometry(1, 1).translate(0, 0.5, 0), g = new THREE.InstancedBufferGeometry();
238
+ g.index = q.index; for (const a of ['position', 'normal', 'uv']) g.setAttribute(a, q.attributes[a]);
239
+ for (const a of ['aCenter', 'aShape', 'aTint']) g.setAttribute(a, new THREE.InstancedBufferAttribute(new Float32Array(capacity * 3), 3).setUsage(THREE.DynamicDrawUsage));
240
+ g.userData.capacity = capacity;
241
+ const m = new THREE.Mesh(g, old?.material ?? part.cardMaterial(I.src, I.bake));
242
+ // cards span every far chunk, so no per-chunk culling (two triangles a plant); no shadow (a flat card's shadow would turn with the camera)
243
+ m.frustumCulled = false; m.castShadow = false; m.receiveShadow = sp.receiveShadow; m.matrixAutoUpdate = false;
244
+ m.userData.budgetTag = 'vegetation';
245
+ // one 1 m quad at the origin outside the shader (positionNode places every card): a scene copy such as the path tracer leaves it out and says so
246
+ drawOnly('far plants drawn as impostor cards (left out: they are placed in the shader, so the traced photo has no far plants)', m);
247
+ if (old) { old.removeFromParent(); old.geometry.dispose(); }
248
+ this.engine.scene.add(engineOwned('vegetation', m));
249
+ I.mesh = m;
134
250
  }
135
251
  _neutral(o) {
136
252
  const m = neutralMaterial('vegetation', { vertexColors: true, side: o.doubleSided ? THREE.DoubleSide : THREE.FrontSide });
@@ -141,43 +257,46 @@ export class VegetationDraw {
141
257
  /** @internal view hook: c.plants[name] was placed, replaced, thinned or dropped, or which of its instances are felled changed */
142
258
  change(c, name) {
143
259
  const r = c.plants?.[name], rec = this.meshes.get(c), old = rec?.ims[name];
260
+ const I = this.kinds.get(name)?.impostor;
261
+ if (I) I.dirty = true; // placed, felled or gone: the far cards copy it next frame
144
262
  if (!r) { if (old) { rec.group.remove(old); old.dispose(); delete rec.ims[name]; } return; }
145
263
  const k = this.kinds.get(name), sp = this.v.get(name);
146
264
  if (!k || !sp) return;
265
+ const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost (mesh, matrices, culling sphere)
147
266
  let im = old;
148
- if (!old || old.userData.plants !== r || old.material !== k.material) { // new placement (or species defined again): a new mesh
149
- const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost
267
+ if (!old || old.userData.plants !== r || old.userData.base !== k.material) { // new placement (or species defined again): a new mesh
150
268
  im = new THREE.InstancedMesh(k.geometry, k.material, r.n);
151
269
  im.instanceColor = new THREE.InstancedBufferAttribute(r.c, 3);
152
- im.frustumCulled = false; im.matrixAutoUpdate = false;
270
+ im.matrixAutoUpdate = false; // frustum culled by three against every camera: cullSphere() below
153
271
  im.receiveShadow = sp.receiveShadow;
154
- im.userData.plants = r; im.userData.budgetTag = 'vegetation';
272
+ im.userData.plants = r; im.userData.species = name; im.userData.cx = c.cx; im.userData.cz = c.cz; im.userData.base = k.material; im.userData.budgetTag = 'vegetation'; // cx, cz: plantOf reads them
155
273
  const R = rec ?? this._chunk(c);
156
274
  if (old) { R.group.remove(old); old.dispose(); }
157
275
  R.group.add(im); im.updateMatrixWorld(true);
158
276
  R.ims[name] = im;
159
- this.engine.budget.cost.end('build', t0);
160
277
  }
161
- // felled instances draw as a zero matrix (count unchanged, so the other instances keep their slots)
278
+ // felled instances draw at zero scale where they stood (count unchanged, so the other instances keep their slots). Translation and w = 1 stay:
279
+ // an all-zero matrix made three's bounding sphere NaN, and every ray and frustum test then missed the whole chunk
162
280
  const a = im.instanceMatrix.array, hid = c.hidden?.[name];
163
281
  a.set(r.m);
164
- if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 + 16);
282
+ if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 + 12);
165
283
  im.instanceMatrix.needsUpdate = true;
166
284
  im.count = drawnPlants(sp.rule, r, this.v.host.density);
285
+ cullSphere(im, k);
286
+ this.engine.budget.cost.end('build', t0);
167
287
  if (c.ring != null) this._level(im, sp, k, c.ring);
168
288
  }
169
289
 
170
290
  /** @internal view hook: the chunk's ring changed (or shadows were switched): draw distance, low-poly swap and shadows of every species there */
171
291
  ring(c, ring) {
172
292
  const rec = this.meshes.get(c); if (!rec) return;
293
+ this._cardsDirty(rec);
173
294
  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); }
174
295
  }
175
- /** @internal view hook: in view or not (ring 1 is always in view, farther chunks by the camera frustum) */
176
- show(c, visible) { const rec = this.meshes.get(c); if (rec) rec.group.visible = visible; }
177
296
  /** @internal view hook: the chunk was released */
178
297
  drop(c) {
179
298
  const rec = this.meshes.get(c); if (!rec) return;
180
- this.meshes.delete(c);
299
+ this.meshes.delete(c); this._cardsDirty(rec);
181
300
  for (const n in rec.ims) rec.ims[n].dispose();
182
301
  this.engine.scene.remove(rec.group);
183
302
  }
@@ -188,16 +307,20 @@ export class VegetationDraw {
188
307
  for (const k of this.kinds.values()) k.fadeUniforms?.uNearFadeCenter.value.copy(f);
189
308
  }
190
309
 
310
+ _cardsDirty(rec) { for (const n in rec.ims) { const I = this.kinds.get(n)?.impostor; if (I) I.dirty = true; } }
311
+
191
312
  _level(im, sp, k, ring) {
192
- im.visible = ring <= sp.maxRing;
193
- im.geometry = k.lodGeometry && ring > sp.lodRing ? k.lodGeometry : k.geometry;
313
+ // an impostor species beyond lodRing is drawn by its far cards (updateCards), so its chunk mesh hides there, shadow included
314
+ im.visible = ring <= sp.maxRing && !(k.impostor && ring > sp.lodRing);
315
+ const low = k.lodGeometry && ring > sp.lodRing;
316
+ im.geometry = low ? k.lodGeometry : k.geometry;
317
+ im.material = low && k.lodMaterial ? k.lodMaterial : k.material;
194
318
  im.castShadow = !!this.engine.renderer?.shadowMap?.enabled && sp.castShadow && ring <= sp.shadowRing;
195
319
  }
196
320
  _chunk(c) {
197
321
  const CH = this.v.host.chunkSize, g = new THREE.Group();
198
322
  g.userData.budgetTag = 'vegetation';
199
323
  g.position.set(c.cx * CH, 0, c.cz * CH); g.matrixAutoUpdate = false; g.updateMatrix();
200
- g.visible = c.inView !== false;
201
324
  this.engine.scene.add(engineOwned('vegetation', g)); g.updateMatrixWorld(true);
202
325
  const rec = { group: g, ims: {} };
203
326
  this.meshes.set(c, rec);
@@ -205,8 +328,8 @@ export class VegetationDraw {
205
328
  }
206
329
 
207
330
  dispose() {
208
- this._view.remove();
209
- for (const k of this.kinds.values()) for (const d of k.made) d.dispose();
331
+ this._view.remove(); this._swap.remove();
332
+ for (const k of this.kinds.values()) { for (const d of k.made) d.dispose(); this._dropCards(k); }
210
333
  this.kinds.clear(); this._base.dispose();
211
334
  }
212
335
  }
@@ -11,6 +11,7 @@ import { follows } from '../../core/base/follows.js';
11
11
  import * as THREE from 'three';
12
12
  import { makePlacer, makeNoise } from '../../core/stream/scatter.js';
13
13
  import { ChunkStream, bookCollision, collidersNear, ringsReady } from '../../core/stream/chunkStream.js';
14
+ import { select } from './densityMap.js';
14
15
 
15
16
  export const GROUND_DEFAULTS = { chunkSize: 32, viewChunks: 3, density: 1, seed: 1 }; // shown by engine.catalog too
16
17
 
@@ -67,15 +68,29 @@ export class GroundChunks {
67
68
  for (const c of this.chunks.values()) if (c.state === 'ready') for (const sp of this.veg.list()) if (!sp.nearOnly || c.plants[sp.name]) this._grow(c, sp);
68
69
  }
69
70
 
70
- _inArea(cx, cz) {
71
- // no area given: a level that provides the ground bounds it (its walkable meshes), so plants never grow past the model's edge onto the
72
- // flat fallback ground around it; with no level (setGround / flat default) the ground is unbounded and so is the vegetation
71
+ // the rectangle plants may grow in, or null (unbounded). No area given: a level that provides the ground bounds it (its walkable meshes), so plants
72
+ // never grow past the model's edge onto the flat fallback ground around it; with no level (setGround / flat default) it is unbounded
73
+ _rect() {
73
74
  const b = this.area ? null : this.engine.level?.heightfield?.bounds;
74
- const a = this.area ?? (b && !b.isEmpty() ? { min: [b.min.x, b.min.z], max: [b.max.x, b.max.z] } : null);
75
+ return this.area ?? (b && !b.isEmpty() ? { min: [b.min.x, b.min.z], max: [b.max.x, b.max.z] } : null);
76
+ }
77
+ _inArea(cx, cz) {
78
+ const a = this._rect();
75
79
  if (!a) return true;
76
80
  const CH = this.chunkSize;
77
81
  return (cx + 1) * CH > a.min[0] && cx * CH < a.max[0] && (cz + 1) * CH > a.min[1] && cz * CH < a.max[1];
78
82
  }
83
+ // a chunk overlapping the area still holds spots outside it: each plant (and its collider, same index) is tested by its own position
84
+ _clip(c, r) {
85
+ const a = this._rect();
86
+ if (!a || !r.n) return r;
87
+ const CH = this.chunkSize, ox = c.cx * CH, oz = c.cz * CH, keep = [];
88
+ for (let i = 0; i < r.n; i++) {
89
+ const x = ox + r.m[i * 16 + 12], z = oz + r.m[i * 16 + 14];
90
+ if (x >= a.min[0] && x < a.max[0] && z >= a.min[1] && z < a.max[1]) keep.push(i);
91
+ }
92
+ return select(r, keep);
93
+ }
79
94
  _ring(c) { return this._stream.ring(c); }
80
95
 
81
96
  /** @internal module frame hook: follow the ground, queue / release chunks around the sources, build within budget, LOD and culling */
@@ -122,7 +137,7 @@ export class GroundChunks {
122
137
  c.sphere.radius = Math.hypot(CH / 2, CH / 2, (c.hi - c.lo) / 2 + 8);
123
138
  }
124
139
  _grow(c, sp) {
125
- const r = this._place(c.cx, c.cz, sp.rule, this.density);
140
+ const r = this._clip(c, this._place(c.cx, c.cz, sp.rule, this.density));
126
141
  for (let i = 0; i < r.n; i++) { const y = r.m[i * 16 + 13]; if (y < c.lo) c.lo = y; if (y > c.hi) c.hi = y; }
127
142
  this.veg.mount(c, sp.name, r);
128
143
  }
@@ -68,18 +68,18 @@ export function vegetation(opts = {}) {
68
68
  async init(e) {
69
69
  if (own && e.terrain) throw codedError('module-requires', 'vegetation() was installed before terrain(): put terrain() first, vegetation then grows on its chunks');
70
70
  // over a level or a code-built ground these chunks are the only ones: their rows are this module's to offer (on terrain, the terrain's)
71
- if (own) e.settings?.define('viewChunks', own.viewChunks, n => { if (own.viewChunks !== n) own.viewChunks = n; }).define('density', own.density, n => { if (own.density !== n) own.density = n; });
71
+ if (own) e.settings?.define('viewChunks', own.viewChunks, { menu: false, apply: n => { if (own.viewChunks !== n) own.viewChunks = n; } }).define('density', own.density, { menu: false, apply: n => { if (own.density !== n) own.density = n; } }); // the graphics tab draws them
72
72
  await v.whenLoaded(); // densityMap.url images of species added before start
73
73
  },
74
74
  frame(dt, e) { own?.update(e.stream.sources(), e.camera); },
75
75
  fixed(dt) { v.tick(dt); }, skip(dt, e, done) { if (done) v.tick(1); },
76
76
  describe(e, ctx) { if (own) ctx.out.perf.vegetation = { loaded: own.stats.loaded, visible: own.stats.visible, queued: own.stats.queued }; },
77
- dispose(e) { own?.dispose(); v?._view?.remove(); v?._planter?.remove(); } };
77
+ dispose(e) { own?.dispose(); v?.detach(); } };
78
78
  const lookModule = {
79
79
  // the same vegetation({...}) call (its options are the data part's; the draw part reads the species' define() options)
80
80
  name: 'vegetationDraw', skipKind: 'none', type: 'picture', label: 'Vegetation drawing', params: VEG_PARAMS, options: opts, requires: ['vegetation'], provides: ['vegetation-draw'], stage: 'effects',
81
81
  install(e) { e.i18n.add({ 'zh-CN': { 'module.vegetationDraw': '植被外观' }, en: { 'module.vegetationDraw': 'vegetation drawing' } }); drawPart = new VegetationDraw(e, v); return drawPart; },
82
- frame() { drawPart.updateFade(); },
82
+ frame() { drawPart.updateFade(); drawPart.updateCards(); },
83
83
  describe() { return { chunks: drawPart?.meshes.size ?? 0 }; },
84
84
  dispose() { drawPart?.dispose(); drawPart = null; },
85
85
  };