threedog 2.2.2 → 2.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 (194) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +22 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +371 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -35,7 +35,7 @@ export function watchOwned(sky) {
35
35
  const list = [];
36
36
  // background: the sky writes it with a backdrop / skybox; with the dome it draws over whatever scene.background holds, so a game that sets one
37
37
  // takes it, and the dome hides (onChange) so the game's background shows; handing it back shows the dome again
38
- list.push(sky._oBg = own('background', 'sky', 'background', () => [scene.background, scene.backgroundIntensity], L.background, [scene]));
38
+ list.push(sky._oBg = own('background', 'sky', 'background', out => (out ? (out[0] = scene.background, out[1] = scene.backgroundIntensity, out.length = 2, out) : [scene.background, scene.backgroundIntensity]), L.background, [scene]));
39
39
  sky._oBg._onChange = o => { if (!sky._backdrop && !sky.skybox && !sky._ownSky && !sky._noSky) sky.dome.visible = o.on; }; // a replaced sky keeps the dome hidden
40
40
  // the reference is the scene as the engine made it, not what is there now: picture code runs before start() (and may run before sky()), and a write
41
41
  // with no reference to differ from would leave the dome drawn over the game's background for good
@@ -45,7 +45,7 @@ export function watchOwned(sky) {
45
45
  sky._oEnv._onChange = o => { if (o.on && sky._env) sky._env.key = null; }; // handed back: the next interval builds it again
46
46
  // the sun: part 'view', so engine.autoView.manual('sunDir') is the one takeover entry. The shadow and the game's lights follow this value, so a sun at a chosen
47
47
  // direction has to survive the frame. sunDir and uSunDir are one vector (Sky.js), so a write to either name is seen here
48
- list.push(sky._oSun = defineOwned(e, { id: 'sky.sunDir', part: 'view', key: 'sunDir', read: () => sky.sunDir.toArray(), levels: L.sunDir, objects: [sky] }));
48
+ list.push(sky._oSun = defineOwned(e, { id: 'sky.sunDir', part: 'view', key: 'sunDir', read: out => { const d = sky.sunDir; return out ? (out[0] = d.x, out[1] = d.y, out[2] = d.z, out.length = 3, out) : d.toArray(); }, levels: L.sunDir, objects: [sky] }));
49
49
  return list;
50
50
  }
51
51
 
@@ -62,7 +62,7 @@ export function makeDome(uniforms, st, extra, engine) {
62
62
  const cl = resolveClouds(st.clouds);
63
63
  const nodes = skyNodes(engine);
64
64
  const dome = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16), nodes ? nodes.domeMaterial(uniforms, st, cl.kind, engine, { layers: extra.layers })
65
- : new THREE.ShaderMaterial({ vertexShader: vert, fragmentShader: domeFragment(cl, extra), uniforms, side: THREE.BackSide, depthWrite: false, depthTest: false }));
65
+ : new THREE.ShaderMaterial({ vertexShader: vert, fragmentShader: domeFragment(cl, extra), uniforms, side: THREE.BackSide, depthWrite: false, depthTest: false, dithering: true }));
66
66
  dome.frustumCulled = false; dome.renderOrder = -1000; dome.userData.budgetTag = 'sky';
67
67
  drawOnly('sky dome (left out: the tracer shows scene.environment and scene.background)', dome);
68
68
  dome.onBeforeRender = (r, sc, cam) => {
@@ -91,7 +91,9 @@ export function loadSkybox(sky, name) {
91
91
 
92
92
  const vert = `varying vec3 vDir;
93
93
  void main(){ vDir = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position = p.xyww; }`;
94
- export const domeFragment = (cl, x) => `uniform vec3 uTop; uniform vec3 uHorizon; uniform vec3 uSunDir; uniform vec3 uSunColor; uniform float uNight;
94
+ export const domeFragment = (cl, x) => `#include <common>
95
+ #include <dithering_pars_fragment>
96
+ uniform vec3 uTop; uniform vec3 uHorizon; uniform vec3 uSunDir; uniform vec3 uSunColor; uniform float uNight;
95
97
  uniform float uSunSize; uniform float uSunGlow; uniform float uSunBrightness; uniform float uMoonBrightness; uniform float uMoonSize; uniform vec3 uMoonColor; uniform float uStars; uniform float uStarCloudDim; uniform float uStarScale; uniform float uSkyCurve;
96
98
  uniform float uTime; uniform float uWeatherCloud; uniform float uCloudCover; uniform float uSkyCloudScale; uniform vec2 uSkyCloudSpeed; uniform vec3 uCloudColor; uniform vec3 uCloudShade;
97
99
  ${CLOUD_UNIFORM_DECL}
@@ -121,4 +123,5 @@ void main(){
121
123
  gl_FragColor = vec4(col, 1.0);
122
124
  #include <tonemapping_fragment>
123
125
  #include <colorspace_fragment>
126
+ #include <dithering_fragment>
124
127
  }`;
@@ -1,7 +1,7 @@
1
1
  // The sky() module definition (split out of Sky.js): install, per-frame update, the fixed scenario time, describe. Time, day, seasons, their
2
2
  // timers and saves are the calendar's (modules/calendar); the sky reads engine.calendar each frame to draw.
3
3
  // Usage and the engine.sky API are documented in Sky.js.
4
- import { Sky } from './Sky.js';
4
+ import { Sky, disposeDome } from './Sky.js';
5
5
  import { resetSignals } from '../../render/effects.js';
6
6
  import { dropOwned } from '../../core/ops/owned.js';
7
7
  import { readParams, keysSchema } from '../../core/base/params.js';
@@ -52,7 +52,7 @@ export function sky(opts = {}) {
52
52
  // a calendar removed mid-game takes its measures with it: the sky takes the signals back at once, or uDaylight / uTimeOfDay would freeze
53
53
  frame(dt) { own(); s.update(); s._envFrame(dt); },
54
54
  // the dome goes too: a sky swapped with replaces must not leave the old dome drawn behind the new one
55
- dispose(e) { resetSignals(e, SKY_SIGNALS); if (s._seasoned || s._covered) resetSignals(e, TINT_SIGNALS); if (s._oSun.on) resetSignals(e, ['uSunDir']); s._shadowOff(); s._swap.remove(); s._envOff(); s._entries.dispose(); dropOwned(s.engine, s._owned); s.dome.removeFromParent(); s.dome.geometry.dispose(); s.dome.material.dispose(); },
55
+ dispose(e) { resetSignals(e, SKY_SIGNALS); if (s._seasoned || s._covered) resetSignals(e, TINT_SIGNALS); if (s._oSun.on) resetSignals(e, ['uSunDir']); s._shadowOff(); s._swap.remove(); s._envOff(); s._entries.dispose(); dropOwned(s.engine, s._owned); disposeDome(s.dome); },
56
56
  // scenario params time / season go to the calendar when there is one (its own applyState); without it time sets the fixed time drawn
57
57
  stateKeys: ['time', 'season'],
58
58
  applyState(e, { time, season }) {
@@ -316,8 +316,9 @@ export function swarm() {
316
316
  const owner = { drop: s => { list = list.filter(o => o !== s); } };
317
317
  let firstLoad = false; // set by the first load or new game: swarms spawned before it are warned about when it empties them
318
318
  ctx.track(e.time.onMove(() => { for (const s of list) s._end(); }));
319
- // onRender and not frame: step(render: false) skips the matrices, only drawn frames write them
320
- ctx.track(e.onRender(() => { for (const s of list) if (s.mesh) writeMesh(s, e.stepBlend); }));
319
+ // onBeforeDraw (or onRender fallback) and not frame: step(render: false) skips the matrices, only drawn frames write them
320
+ const syncMeshes = () => { for (const s of list) if (s.mesh) writeMesh(s, e.stepBlend); };
321
+ ctx.track(e.onBeforeDraw ? e.onBeforeDraw(syncMeshes) : e.onRender(syncMeshes));
321
322
  // one save part for all swarms: a load or new game also empties swarms not in saves, or last round's bullets stay on the field
322
323
  ctx.saves.define('swarm', { notAtomic: 'simulated in bulk each step: one copy per atomic run would cost more than the op', version: 1,
323
324
  save: () => ({ ...pending, ...Object.fromEntries(list.filter(s => s.saved).map(s => [s.name, s._save()])) }), // pending: swarms of the loaded save not made yet stay in the next save
@@ -2,6 +2,14 @@
2
2
  // Why hashed and not an array over the world: a game world has no declared bounds and a bullet may leave the map; the table size depends only on capacity.
3
3
  // Why the lists hang on slots and not rows: swap-remove moves rows, slots stay, so free and spawn keep the cells in O(1) with no rebuild.
4
4
  // Why cx / cz are kept: two cells can share a bucket; comparing them shows each object once, in its own cell, so a query needs no dedupe.
5
+ /** Test row i against (x, z, r2); returns 0 if skipped/outside, 1 if visited, -1 if cb stopped early */
6
+ function visitRow(i, x, z, r2, X, Z, d, gone, cb) {
7
+ if (gone[i]) return 0;
8
+ const dx = X[i] - x, dz = Z[i] - z, d2 = dx * dx + dz * dz;
9
+ if (d2 > r2) return 0;
10
+ return cb(d, i, d2) === false ? -1 : 1;
11
+ }
12
+
5
13
  export class SwarmGrid {
6
14
  /** @param {any} s the swarm @param {number} cell cell size in meters */
7
15
  constructor(s, cell) {
@@ -43,19 +51,16 @@ export class SwarmGrid {
43
51
  // with more cells than objects a row scan is faster; otherwise a wide query would cost by area and not by object count
44
52
  if ((x1 - x0 + 1) * (z1 - z0 + 1) > s._n) {
45
53
  for (let i = 0, n = s._n; i < n; i++) {
46
- if (gone[i]) continue;
47
- const dx = X[i] - x, dz = Z[i] - z, d2 = dx * dx + dz * dz;
48
- if (d2 <= r2) { hits++; if (cb(d, i, d2) === false) return hits; }
54
+ const v = visitRow(i, x, z, r2, X, Z, d, gone, cb);
55
+ if (v) { hits++; if (v < 0) return hits; }
49
56
  }
50
57
  return hits;
51
58
  }
52
59
  for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
53
60
  for (let k = head[this.bucket(cx, cz)]; k >= 0; k = next[k]) {
54
61
  if (this.cx[k] !== cx || this.cz[k] !== cz) continue;
55
- const i = at[k];
56
- if (gone[i]) continue;
57
- const dx = X[i] - x, dz = Z[i] - z, d2 = dx * dx + dz * dz;
58
- if (d2 <= r2) { hits++; if (cb(d, i, d2) === false) return hits; }
62
+ const v = visitRow(at[k], x, z, r2, X, Z, d, gone, cb);
63
+ if (v) { hits++; if (v < 0) return hits; }
59
64
  }
60
65
  }
61
66
  return hits;
@@ -11,7 +11,7 @@ import * as THREE from 'three';
11
11
  import { createTerrain } from './terrainGen.js';
12
12
  import { chunkHandler } from './chunkJob.js';
13
13
  import { TerrainEdits } from './terrainEdit.js';
14
- import { ChunkStream, bookCollision, colliderLag } from '../../core/stream/chunkStream.js';
14
+ import { ChunkStream, bookCollision, colliderLag, defineChunkSettings, syncChunkLevel } from '../../core/stream/chunkStream.js';
15
15
  import { chunkQueries } from './chunkQueries.js';
16
16
  import { reportError } from '../../core/base/errors.js';
17
17
  import { codedError } from '../../core/base/errorHints.js';
@@ -190,16 +190,6 @@ export class ChunkManager {
190
190
  _viewMeters() { return (this._viewChunks - 0.3) * this.generator.CHUNK; }
191
191
  /** The view distance the signal uViewDistance gets with terrain({ viewFog: true }) (meters), else null; never scene.fog itself */
192
192
  get viewFogFar() { return this.viewFog ? this._viewMeters() : null; }
193
- // Why setters: a plain write used to change the number and nothing else (no far plane, no new plants), with no error
194
- /** View distance (in chunks). Writing it moves the camera far plane out too; with terrain({ viewFog: true }) the signal uViewDistance follows (see viewFogFar; the game's fog is its own) */
195
- get viewChunks() { return this._viewChunks; }
196
- set viewChunks(n) {
197
- this._viewChunks = n;
198
- this.engine.viewFar(this._viewMeters() + 150); // chunks in view must not be clipped (unless the game owns camera.far)
199
- }
200
- /** Vegetation density multiplier. Writing it places plants again on the loaded chunks: it thins plants without a collider, blocking plants stand at every density, so collision does not change */
201
- get density() { return this._density; }
202
- set density(d) { this._density = d; this.vgen++; this._regrow(this.plants.baseNames()); this._regrowNear(this.plants.nearNames()); }
203
193
  // plants-only jobs for every loaded chunk (the ground and its collision stay; near-only species: _regrowNear). c.regrow counts the ones not yet
204
194
  // mounted: readyAt is false until they are, so a headless page (core/engine/headlessLoad.js) keeps running loading frames and stateApplied
205
195
  // waits for the new plants, as it did when a species dropped the whole terrain
@@ -274,11 +264,13 @@ export class ChunkManager {
274
264
  if (r.terrain) { if (c.state === 'ready') continue; this._applyTerrain(c, r.terrain); c.ticket?.resolve(true); }
275
265
  else if (c.state !== 'ready') continue;
276
266
  if (r.vgen !== this.vgen) { // placed with an old density or species list: keep the ground, ask for the plants again
277
- if (r.terrain) c.regrow++; else c.pendingDetail = false;
267
+ if (!r.terrain) c.pendingDetail = false;
278
268
  // a regrow stays counted until its plants are in; a new chunk asks for today's species, not the list it left with
279
269
  const names = r.terrain ? this.plants.baseNames() : Object.keys(r.veg).filter(n => this.plants.get(n)); // only species the planter still knows
280
- if (r.terrain || names.length) this._send({ ...this._job(c, false, names), regrow: !!(r.regrow || r.terrain) });
281
- else if (r.regrow) this._regrown(c);
270
+ if (names.length) {
271
+ if (r.terrain) c.regrow++;
272
+ this._send({ ...this._job(c, false, names), regrow: !!(r.regrow || r.terrain) });
273
+ } else if (r.regrow) this._regrown(c);
282
274
  } else {
283
275
  for (const name in r.veg) this._mountPlants(c, name, r.veg[name]);
284
276
  if (r.regrow) this._regrown(c);
@@ -340,20 +332,14 @@ export class ChunkManager {
340
332
 
341
333
  // near-only species are placed when a chunk comes within their ring and dropped past it; the vegetation drawing picks its own LOD (plants.ring)
342
334
  _setLevel(c, ring) {
343
- if (c.level === ring) return;
344
- c.level = ring;
345
335
  const P = this.plants;
346
- for (const sp of P.list()) {
347
- if (!sp.nearOnly) continue;
348
- const has = !!c.plants[sp.name];
336
+ syncChunkLevel(c, ring, P.list(), sp => {
349
337
  // detailDone: this species was already placed here and came back empty; without it the empty result would reset the level and re-ask forever
350
- if (ring <= sp.maxRing && !has && !c.pendingDetail && !c.detailDone.has(sp.name)) {
351
- c.pendingDetail = true;
352
- const names = P.nearNames();
353
- this._send(this._job(c, false, names));
354
- } else if (ring > sp.maxRing + 1 && has) this._unplantNear(c, sp.name);
355
- }
356
- P.ring?.(c, ring);
338
+ if (c.pendingDetail || c.detailDone.has(sp.name)) return;
339
+ c.pendingDetail = true;
340
+ const names = P.list().filter(s => s.nearOnly && ring <= s.maxRing && !c.plants[s.name] && !c.detailDone.has(s.name)).map(s => s.name);
341
+ if (names.length) this._send(this._job(c, false, names)); else c.pendingDetail = false;
342
+ }, sp => this._unplantNear(c, sp.name), (ch, r) => P.ring?.(ch, r));
357
343
  }
358
344
  // A near-only species with a collider is gameplay (it blocks), so its colliders take effect on a tick booked from where the sources stand, not when the
359
345
  // worker answers: a fast and a slow machine block the same spot at the same step. The fallback places it on the main thread when due (the same
@@ -400,3 +386,7 @@ export class ChunkManager {
400
386
  }
401
387
  }
402
388
  Object.assign(ChunkManager.prototype, chunkQueries);
389
+ defineChunkSettings(ChunkManager.prototype, {
390
+ onViewChunks() { this.engine.viewFar(this._viewMeters() + 150); }, // chunks in view must not be clipped (unless the game owns camera.far)
391
+ onDensity() { this.vgen++; this._regrow(this.plants.baseNames()); this._regrowNear(this.plants.nearNames()); },
392
+ });
@@ -173,10 +173,9 @@ export class Triggers {
173
173
  }
174
174
 
175
175
  _defaultWho() {
176
- const e = this.engine;
177
- this._one[0] = e.actorPosition(); // engine.actor: the player by default, or the vehicle / squad member the game handed control to
178
- this._one.length = this._ids.length = 1; this._ids[0] = e.actor;
179
- 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
176
+ const e = this.engine, actors = e.localActors();
177
+ this._one.length = this._ids.length = actors.length;
178
+ for (let i = 0; i < actors.length; i++) { this._ids[i] = actors[i]; this._one[i] = e.actorPosition(actors[i]); }
180
179
  return this._one;
181
180
  }
182
181
 
@@ -268,7 +267,7 @@ export class Triggers {
268
267
  }
269
268
  /** @internal occupied zones exit (who is null; first: 1, after the level, so onExit and its effects run before the other parts restore and whatever they wrote is overwritten by the save), then used / cooldown come from the save; zones the save does not name start fresh */
270
269
  _load(d) {
271
- for (const t of [...this._list]) if (t.inside) this._exit(t, null);
270
+ for (const t of [...this._list]) if (t.inside) try { this._exit(t, null); } catch (err) { reportError(this.engine, err, 'trigger onExit during load'); }
272
271
  const keys = this._keys();
273
272
  this._list.forEach((t, i) => {
274
273
  const s = d?.[keys[i]];
@@ -279,7 +278,7 @@ export class Triggers {
279
278
  _exit(t, who) {
280
279
  // id: who was inside (remembered at enter), so an exit says who left even though the position that left is gone
281
280
  const id = t._id ?? null, all = t._in ? [...t._in.values()] : null;
282
- t.inside = false; t._cool = t.cooldown; t._id = null;
281
+ t.inside = false; t._cool = t.used ? 0 : t.cooldown; t._id = null;
283
282
  if (all) { // occupancy 'each': everyone leaves, each in its own try (the first throw is raised after the last exit has run)
284
283
  t._in.clear();
285
284
  let first, bad = false;
@@ -93,11 +93,13 @@ export class VegetationDraw {
93
93
  set material(m) {
94
94
  if (m != null) needMaterial('vegetation-option', 'vegetation.material', m, ' (null gives the neutral default back)');
95
95
  this._game = m || null;
96
+ const updated = new Set();
96
97
  for (const sp of this.v.list()) {
97
98
  const old = this.kinds.get(sp.name);
98
- if (old?.shared) this.species(sp);
99
+ if (old?.shared) { this.species(sp); updated.add(sp.name); }
99
100
  }
100
101
  for (const [c, rec] of this.meshes) for (const n in rec.ims) {
102
+ if (updated.has(n)) continue;
101
103
  const k = this.kinds.get(n), im = rec.ims[n]; if (!k) continue;
102
104
  im.userData.base = im.material = k.material;
103
105
  if (c.ring != null) this._level(im, this.v.get(n), k, c.ring);
@@ -171,10 +173,21 @@ export class VegetationDraw {
171
173
  const made = [...new Set([...(lodMdl?.materials ?? []), ...(lodMaterial ?? []), ...(lod && lod !== o.lodGeometry ? [lod] : []), ...(mdl ? [mdl.geometry, ...material] : shared && !game ? [material] : [])])];
172
174
  // fade: the game's shared material has none, but a low-poly model of the species has its own
173
175
  const old = this.kinds.get(sp.name);
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) });
176
- for (const d of old?.made ?? []) d.dispose();
177
- this._dropCards(old);
176
+ const next = { geometry: mdl ? mdl.geometry : o.geometry, lodGeometry: lod, lodMaterial, fadeUniforms: game && !lodMaterial ? null : nf?.uniforms ?? null, shared, material, made,
177
+ impostor: this._impostor(sp, mdl, game, bakeOwn) };
178
+ this.kinds.set(sp.name, next);
179
+ if (old) {
180
+ for (const [c, rec] of this.meshes) {
181
+ if (rec.cards) delete rec.cards[sp.name];
182
+ const im = rec.ims[sp.name];
183
+ if (!im) continue;
184
+ im.userData.base = next.material;
185
+ if (c.ring != null) this._level(im, sp, next, c.ring);
186
+ else { im.geometry = next.geometry; im.material = next.material; }
187
+ }
188
+ for (const d of old.made ?? []) d.dispose();
189
+ this._dropCards(old);
190
+ }
178
191
  }
179
192
  /**
180
193
  * 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().
@@ -200,9 +213,26 @@ export class VegetationDraw {
200
213
  if (I.mesh) { I.mesh.removeFromParent(); I.mesh.geometry.dispose(); I.mesh.material.dispose(); }
201
214
  I.bake?.dispose(); I.neutral?.dispose(); I.bakeOwn?.dispose();
202
215
  }
216
+ /** Pre-pack one chunk's impostor card attributes so updateCards() only runs TypedArray.set block copies @internal */
217
+ _packCards(c, rec, name, im) {
218
+ const count = im.count, CH = this.v.host.chunkSize, ox = c.cx * CH, oz = c.cz * CH;
219
+ const a = im.instanceMatrix.array, col = im.instanceColor?.array;
220
+ const center = new Float32Array(count * 3), shape = new Float32Array(count * 3), tint = new Float32Array(count * 3);
221
+ for (let i = 0; i < count; i++) {
222
+ const o = i * 16, j = i * 3;
223
+ // 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
224
+ center[j] = ox + a[o + 12]; center[j + 1] = a[o + 13]; center[j + 2] = oz + a[o + 14];
225
+ shape[j] = Math.atan2(a[o + 8], a[o + 10]); shape[j + 1] = Math.hypot(a[o], a[o + 2]); shape[j + 2] = Math.hypot(a[o + 4], a[o + 5], a[o + 6]);
226
+ if (col) { tint[j] = col[j]; tint[j + 1] = col[j + 1]; tint[j + 2] = col[j + 2]; }
227
+ else { tint[j] = 1; tint[j + 1] = 1; tint[j + 2] = 1; }
228
+ }
229
+ const card = { count, center, shape, tint };
230
+ (rec.cards ??= {})[name] = card;
231
+ return card;
232
+ }
203
233
  /**
204
234
  * @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
235
+ * chunk beyond lodRing (that is the draw saved). Copies pre-packed per-chunk card buffers with TypedArray.set and bounded upload ranges
206
236
  */
207
237
  updateCards() {
208
238
  for (const [name, k] of this.kinds) {
@@ -211,25 +241,30 @@ export class VegetationDraw {
211
241
  I.dirty = false;
212
242
  const far = [];
213
243
  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);
244
+ for (const [c, rec] of this.meshes) {
245
+ const im = rec.ims[name];
246
+ if (im && c.ring > sp.lodRing && c.ring <= sp.maxRing && im.count) {
247
+ const card = rec.cards?.[name]?.count === im.count ? rec.cards[name] : this._packCards(c, rec, name, im);
248
+ far.push(card); n += card.count;
229
249
  }
230
250
  }
251
+ if (!n && !I.mesh) continue;
252
+ if (!I.bake || !I.mesh || I.mesh.geometry.userData.capacity < n) {
253
+ const part = webgpuPart('impostor', `vegetation '${name}' impostor`);
254
+ I.bake ??= part.bake(this.engine.renderer, I.src, I.opts);
255
+ if (!I.mesh || I.mesh.geometry.userData.capacity < n) this._cardMesh(I, part, Math.max(64, 2 ** Math.ceil(Math.log2(n || 1))), sp);
256
+ }
257
+ const g = I.mesh.geometry, aC = g.attributes.aCenter, aS = g.attributes.aShape, aT = g.attributes.aTint;
258
+ const C = aC.array, S = aS.array, T = aT.array;
259
+ let off = 0;
260
+ for (const card of far) {
261
+ C.set(card.center, off); S.set(card.shape, off); T.set(card.tint, off);
262
+ off += card.count * 3;
263
+ }
231
264
  g.instanceCount = n;
232
- for (const at of [g.attributes.aCenter, g.attributes.aShape, g.attributes.aTint]) at.needsUpdate = true;
265
+ if (n > 0) {
266
+ for (const at of [aC, aS, aT]) { at.clearUpdateRanges?.(); at.addUpdateRange?.(0, n * 3); at.needsUpdate = true; }
267
+ }
233
268
  I.mesh.visible = n > 0;
234
269
  }
235
270
  }
@@ -259,18 +294,18 @@ export class VegetationDraw {
259
294
  const r = c.plants?.[name], rec = this.meshes.get(c), old = rec?.ims[name];
260
295
  const I = this.kinds.get(name)?.impostor;
261
296
  if (I) I.dirty = true; // placed, felled or gone: the far cards copy it next frame
262
- if (!r) { if (old) { rec.group.remove(old); old.dispose(); delete rec.ims[name]; } return; }
297
+ if (!r) { if (old) { rec.group.remove(old); old.dispose(); delete rec.ims[name]; } if (rec?.cards) delete rec.cards[name]; return; }
263
298
  const k = this.kinds.get(name), sp = this.v.get(name);
264
299
  if (!k || !sp) return;
265
300
  const t0 = performance.now(); // measure: the 'build' stage of engine.budget.cost (mesh, matrices, culling sphere)
266
- let im = old;
301
+ let im = old, R = rec;
267
302
  if (!old || old.userData.plants !== r || old.userData.base !== k.material) { // new placement (or species defined again): a new mesh
268
303
  im = new THREE.InstancedMesh(k.geometry, k.material, r.n);
269
304
  im.instanceColor = new THREE.InstancedBufferAttribute(r.c, 3);
270
305
  im.matrixAutoUpdate = false; // frustum culled by three against every camera: cullSphere() below
271
306
  im.receiveShadow = sp.receiveShadow;
272
307
  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
273
- const R = rec ?? this._chunk(c);
308
+ R = rec ?? this._chunk(c);
274
309
  if (old) { R.group.remove(old); old.dispose(); }
275
310
  R.group.add(im); im.updateMatrixWorld(true);
276
311
  R.ims[name] = im;
@@ -282,6 +317,7 @@ export class VegetationDraw {
282
317
  if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 + 12);
283
318
  im.instanceMatrix.needsUpdate = true;
284
319
  im.count = drawnPlants(sp.rule, r, this.v.host.density);
320
+ if (I && R) this._packCards(c, R, name, im);
285
321
  cullSphere(im, k);
286
322
  this.engine.budget.cost.end('build', t0);
287
323
  if (c.ring != null) this._level(im, sp, k, c.ring);
@@ -322,7 +358,7 @@ export class VegetationDraw {
322
358
  g.userData.budgetTag = 'vegetation';
323
359
  g.position.set(c.cx * CH, 0, c.cz * CH); g.matrixAutoUpdate = false; g.updateMatrix();
324
360
  this.engine.scene.add(engineOwned('vegetation', g)); g.updateMatrixWorld(true);
325
- const rec = { group: g, ims: {} };
361
+ const rec = { group: g, ims: {}, cards: {} };
326
362
  this.meshes.set(c, rec);
327
363
  return rec;
328
364
  }
@@ -10,7 +10,7 @@
10
10
  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
- import { ChunkStream, bookCollision, collidersNear, ringsReady } from '../../core/stream/chunkStream.js';
13
+ import { ChunkStream, bookCollision, collidersNear, ringsReady, defineChunkSettings, syncChunkLevel } from '../../core/stream/chunkStream.js';
14
14
  import { select } from './densityMap.js';
15
15
 
16
16
  export const GROUND_DEFAULTS = { chunkSize: 32, viewChunks: 3, density: 1, seed: 1 }; // shown by engine.catalog too
@@ -50,23 +50,11 @@ export class GroundChunks {
50
50
  }
51
51
  /** @internal vegetation / settings plumbing */
52
52
  refreshLevels() { for (const c of this.chunks.values()) c.level = -1; }
53
- /** Rings of chunks drawn around each stream source (the settings page's view distance); the next update loads / releases chunks to match */
54
- get viewChunks() { return this._viewChunks; }
55
- set viewChunks(n) { this._viewChunks = n; this.refreshLevels(); }
56
53
  /** Drop every chunk; they are placed again around the stream sources (call it after changing the ground behind the same provider) */
57
54
  rebuild() {
58
55
  this._stream.drop();
59
56
  this.gen++;
60
57
  }
61
- /**
62
- * Vegetation density multiplier: the loaded chunks are placed again in place, each species replacing its own plants and collision circles,
63
- * so trees never go missing in between (dropping the chunks left them without collision until rebuilt)
64
- */
65
- get density() { return this._density; }
66
- set density(d) {
67
- this._density = d;
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);
69
- }
70
58
 
71
59
  // 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
60
  // never grow past the model's edge onto the flat fallback ground around it; with no level (setGround / flat default) it is unbounded
@@ -143,15 +131,7 @@ export class GroundChunks {
143
131
  }
144
132
 
145
133
  _setLevel(c, ring) {
146
- if (c.level === ring) return;
147
- c.level = ring;
148
- for (const sp of this.veg.list()) {
149
- if (!sp.nearOnly) continue;
150
- const has = !!c.plants[sp.name];
151
- if (ring <= sp.maxRing && !has) this._grow(c, sp);
152
- else if (ring > sp.maxRing + 1 && has) this.veg.unmount(c, sp.name);
153
- }
154
- this.veg.ring(c, ring);
134
+ syncChunkLevel(c, ring, this.veg.list(), sp => this._grow(c, sp), sp => this.veg.unmount(c, sp.name), (ch, r) => this.veg.ring(ch, r));
155
135
  }
156
136
 
157
137
  _dispose(c) {
@@ -167,3 +147,9 @@ export class GroundChunks {
167
147
  return ringsReady(this.chunks, this.chunkSize, position, rings, (c, cx, cz) => !this._inArea(cx, cz) || c?.state === 'ready');
168
148
  }
169
149
  }
150
+ defineChunkSettings(GroundChunks.prototype, {
151
+ onViewChunks() { this.refreshLevels(); },
152
+ onDensity() {
153
+ 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);
154
+ },
155
+ });