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
package/presets.js CHANGED
@@ -105,4 +105,34 @@ export const presets = Object.freeze({
105
105
  thirdPersonAction: Object.freeze({ distance: 4.5, minDistance: 1.5, maxDistance: 9, height: 1.6, shoulder: 0.5, pitch: 0.25, minPitch: -1.05, maxPitch: 1.2,
106
106
  ground: 'shorten', groundClearance: 0.3, hideTargetNear: 0.9, pointerLock: true }),
107
107
  }),
108
+ /** decals.define(name, { ... }) option bundles */
109
+ decals: Object.freeze({
110
+ /** Bullet holes, slashes and scorch marks: 64-entry ring buffer, 18 s life with a 4 s fade */
111
+ marks: Object.freeze({ size: 0.5, depth: 0.5, opacity: 0.9, lifetime: 18, fade: 4, max: 64 }),
112
+ /** Footprints and tire tracks: compact, softer fade */
113
+ footprints: Object.freeze({ size: 0.45, depth: 0.4, opacity: 0.65, lifetime: 10, fade: 3, max: 48 }),
114
+ /** Persistent ground ring / selection or AoE indicator */
115
+ indicator: Object.freeze({ size: 2.5, depth: 1.2, opacity: 0.85, lifetime: Infinity, fade: 0 }),
116
+ }),
117
+ /** Animator state / layer option bundles (assets.animate, anim.addLayer) */
118
+ animation: Object.freeze({
119
+ /** Upper-body bone-mask layer (spine + arms + head) with quick 0.15 s crossfade */
120
+ upperBody: Object.freeze({ name: 'upper', mask: 'upper', fade: 0.15, weight: 1 }),
121
+ /** Standard 8-directional strafe blend2d ring reading Character's moveX / moveZ */
122
+ eightWay: Object.freeze({
123
+ params: Object.freeze(['moveX', 'moveZ']),
124
+ sync: true,
125
+ blend2d: Object.freeze([
126
+ Object.freeze({ clip: 'Idle', at: Object.freeze([0, 0]) }),
127
+ Object.freeze({ clip: 'Walk_F', at: Object.freeze([0, 1]) }),
128
+ Object.freeze({ clip: 'Walk_B', at: Object.freeze([0, -1]) }),
129
+ Object.freeze({ clip: 'Walk_L', at: Object.freeze([-1, 0]) }),
130
+ Object.freeze({ clip: 'Walk_R', at: Object.freeze([1, 0]) }),
131
+ Object.freeze({ clip: 'Walk_FL', at: Object.freeze([-0.707, 0.707]) }),
132
+ Object.freeze({ clip: 'Walk_FR', at: Object.freeze([0.707, 0.707]) }),
133
+ Object.freeze({ clip: 'Walk_BL', at: Object.freeze([-0.707, -0.707]) }),
134
+ Object.freeze({ clip: 'Walk_BR', at: Object.freeze([0.707, -0.707]) }),
135
+ ]),
136
+ }),
137
+ }),
108
138
  });
package/render/PostFX.js CHANGED
@@ -15,6 +15,7 @@ import { warnOnce } from '../core/base/validate.js';
15
15
  import { reportError } from '../core/base/errors.js';
16
16
  import { readParams, keysSchema } from '../core/base/params.js';
17
17
  import { isWebGPU, webgpuPart, ownMsaa } from './backend.js';
18
+ import { isSmaaPass } from './threeCompat.js';
18
19
  import { MSAA_KEY } from '../core/scene/tier.js';
19
20
  import { defineOwned } from '../core/ops/owned.js';
20
21
  import { watchOwnFrame } from './ownFrame.js';
@@ -92,7 +93,7 @@ const ADD_KEYS = ['name', 'slot', 'order'];
92
93
  // The keys and types of an effect object the game defines ({ name, create | node | fuse, ... }); checked in effectOf before the engine adds its own keys (_auto, output)
93
94
  const EFFECT_SCHEMA = {
94
95
  name: 'string', create: 'function?', node: 'function?', fuse: 'object?', slot: 'string?', order: 'number?', params: 'object?', enabled: 'bool?', update: 'function?',
95
- needsDepth: 'bool?', needsBuffers: 'array?', backend: 'string?', skipOnLowTier: 'bool?', cheaper: 'object?', facts: 'function?', about: 'object?',
96
+ needsDepth: 'bool?', needsBuffers: 'array|function?', backend: 'string?', skipOnLowTier: 'bool?', cheaper: 'object?', facts: 'function?', about: 'object?',
96
97
  };
97
98
 
98
99
  export class PostFX {
@@ -244,11 +245,11 @@ export class PostFX {
244
245
  let rebuild = false;
245
246
  post._change(() => { rebuild = h._apply(changed); }, () => { h._apply(was); }, () => rebuild);
246
247
  },
247
- /** New params on the built part; true when the pass was dropped to be built again (the caller's sync builds it, after the order check) */
248
+ /** New params on the built part; true when the chain needs a rebuild (the caller's sync builds it, after the order check) */
248
249
  _apply(p) {
249
250
  Object.assign(h.params, p);
250
251
  h._swaps = undefined; // the order rule's probe of a pass never built yet was made from the old params
251
- if (post._be.set?.(post, h, p)) return false; // WebGPU: live uniforms, or a rebuild of the node graph
252
+ if (post._be.set) return post._be.set(post, h, p); // WebGPU: false when live uniforms sufficed, true when the node graph must rebuild
252
253
  if (effect.fuse) { post._be.refresh(post, h); return false; }
253
254
  if (!h._impl) return false;
254
255
  if (effect.update) { effect.update(h._impl, h.params); return false; }
@@ -259,7 +260,7 @@ export class PostFX {
259
260
  h._removed = true;
260
261
  follow?.remove(); follow = null; point.release('game');
261
262
  post._change(() => {
262
- freeImpl(h);
263
+ freeImpl(h, true);
263
264
  post._list = post._list.filter(e => e !== h);
264
265
  if (!post._kept.has(h.name)) post._seq.delete(h.name); // removed for good: a later effect of that name starts at the end (plugins keep theirs)
265
266
  const i = post._plain.indexOf(h._entry); if (i >= 0) post._plain.splice(i, 1);
@@ -269,7 +270,7 @@ export class PostFX {
269
270
  // a settings restriction or a hold ending turns it on or off here; a rebuild that throws leaves it as it was
270
271
  follow = point.watch(() => { const was = on, now = !!point.value(); if (now !== was) this._change(() => { on = now; }, () => { on = was; }); });
271
272
  // a create() that throws or an order that breaks depth leaves no half-added effect behind
272
- try { this._change(() => this._list.push(h), () => { freeImpl(h); this._list = this._list.filter(e => e !== h); }); }
273
+ try { this._change(() => this._list.push(h), () => { freeImpl(h, true); this._list = this._list.filter(e => e !== h); }); }
273
274
  catch (err) { follow?.remove(); follow = null; if (!this._kept.has(h.name)) this._seq.delete(h.name); throw err; }
274
275
  this.engine._picture?.added('post effect', h, h.name); // dev: a picture part removed with this still on is reported (core/inspect/pictureWriters.js)
275
276
  this.engine.events.emit('post:add', h.name); // the settings rows follow an effect by its role, so one added after them still gets the player's choice
@@ -309,7 +310,11 @@ export class PostFX {
309
310
  */
310
311
  _antialiasNow() {
311
312
  const samples = this._be.samples(this);
312
- return { samples, replacedBy: this._aa && !samples ? this._list.find(e => e.enabled && e._def.needsBuffers?.includes('velocity'))?.name ?? null : null };
313
+ return { samples, replacedBy: this._aa && !samples ? this._list.find(e => {
314
+ if (!e.enabled) return false;
315
+ const nb = e._def.needsBuffers;
316
+ return (typeof nb === 'function' ? nb(e.params) : nb)?.includes('velocity');
317
+ })?.name ?? null : null };
313
318
  }
314
319
  /**
315
320
  * The shared point of an effect's switch ('post.<name>.enabled'), made on first asking. It outlives the effect (the registry has no delete) and may come before it: settings installs before
@@ -357,12 +362,12 @@ export class PostFX {
357
362
  _place(name, keep = false) { if (keep) this._kept.add(name); if (!this._seq.has(name)) this._seq.set(name, this._seqN++); return this._seq.get(name); }
358
363
  /** @internal */
359
364
  _size() { return this.engine.renderer.getSize(new THREE.Vector2()).multiplyScalar(this.engine.renderer.getPixelRatio()); }
360
- /** Apply a list change, rebuild the chain, and undo the change when the rebuild throws (then rethrow) @internal */
361
365
  /**
362
366
  * The one gate for every change to the effect list or to a pass's swap / depth behaviour (add, remove, on / off, a slot move, set): apply, then the
363
367
  * depth-order rule over the candidate chain (always, also while the game owns the chain or nothing is built), then the rebuild. A refusal undoes
364
368
  * before anything is built; apply is inside the same try, so a throw from apply itself (an effect's update() half-done) is undone too. rebuild() says
365
369
  * whether this change needs the chain built again (a set() through update() in place does not).
370
+ * @internal
366
371
  * @param {() => void} apply @param {() => void} undo @param {() => boolean} [rebuild]
367
372
  */
368
373
  _change(apply, undo, rebuild = () => true) {
@@ -381,7 +386,7 @@ export class PostFX {
381
386
  * @internal
382
387
  */
383
388
  dispose() {
384
- for (const e of this._list) freeImpl(e);
389
+ for (const e of this._list) freeImpl(e, true);
385
390
  this._be.dispose(this);
386
391
  }
387
392
  /**
@@ -424,7 +429,7 @@ export class PostFX {
424
429
  _setBackend() {
425
430
  this._fellBack = !isWebGPU(this.engine.renderer);
426
431
  this._be.dispose(this);
427
- for (const e of this._list) freeImpl(e);
432
+ for (const e of this._list) freeImpl(e, true);
428
433
  this._be = backendFor(this.engine.renderer);
429
434
  this._ownAA = ownMsaa(this.engine.renderer);
430
435
  this._be.init(this);
@@ -437,11 +442,6 @@ export class PostFX {
437
442
  }
438
443
  }
439
444
 
440
- /**
441
- * Drop what an effect built. A plain Pass the game handed in is the game's object: like three's composer.removePass it is not disposed. Only that case: on WebGPU
442
- * _impl is the engine's record of the nodes it built (bloom's mip targets), and skipping it leaked them on every off / on
443
- * @param {any} h
444
- */
445
445
  /**
446
446
  * Both ways a param value comes in (the effect's params at add, handle.set later) go through here: NaN or Infinity in a uniform turns the whole frame
447
447
  * black or white with no word, so it is refused by name. A finite value stays the game's, negative and huge included: no clamp (a negative vignette brightens).
@@ -452,8 +452,13 @@ function finiteParams(name, p, where) {
452
452
  if (bad.length) throw codedError('post-effect', `post effect '${name}': ${where} takes finite numbers; got ${bad.map(([k, v]) => `${k}: ${v}`).join(', ')}`);
453
453
  }
454
454
 
455
- function freeImpl(h) {
456
- if (h._impl !== h._def._pass) h._impl?.dispose?.();
455
+ /**
456
+ * Drop what an effect built. A plain Pass the game handed in is the game's object: like three's composer.removePass it is not disposed. Only that case: on WebGPU
457
+ * _impl is the engine's record of the nodes it built (bloom's mip targets), and skipping it leaked them on every off / on.
458
+ * @param {any} h @param {boolean} [final] true on final teardown (remove / dispose / backend swap) so effects with cross-rebuild state release it synchronously
459
+ */
460
+ function freeImpl(h, final = false) {
461
+ if (h._impl !== h._def._pass) h._impl?.dispose?.(final);
457
462
  h._impl = null;
458
463
  }
459
464
 
@@ -511,7 +516,7 @@ function effectOf(post, x, { name, slot, order }) {
511
516
  const mn = x.material?.name, cls = (typeof x.name === 'string' && x.name) || (mn && mn !== 'unspecified' ? mn : 'pass'), n = next();
512
517
  // a known display-conversion shader (three's GammaCorrectionShader / OutputShader as a ShaderPass) is encoded a second time by the engine's output stage
513
518
  if (/^(GammaCorrection|Output)Shader$/.test(mn ?? '') && slot !== 'tone') warnOnce(OUTPUT_TWICE(cls));
514
- const s = drawsScene(eng, x) ? 'scene' : /FXAA|SMAA|TAA/i.test(cls) || x._edgesRT ? 'final' : post._plain.some(e => e.output) ? 'ldr' : 'hdr';
519
+ const s = drawsScene(eng, x) ? 'scene' : /FXAA|SMAA|TAA/i.test(cls) || isSmaaPass(x) ? 'final' : post._plain.some(e => e.output) ? 'ldr' : 'hdr';
515
520
  // _pass: the game's own object, not disposed when the effect is removed (three's removePass habit; remove() in _add).
516
521
  // _auto: hdr / ldr follows where the game's OutputPass sits (reslot above), unless the game named the slot
517
522
  return pick({ name: `${cls}#${n}`, slot: s, order: 1000 + n, create: () => x, _pass: x, _auto: slot == null && (s === 'hdr' || s === 'ldr') });
@@ -522,3 +527,5 @@ function effectOf(post, x, { name, slot, order }) {
522
527
  throw codedError('post-effect', 'engine.post.add(x): x is a three.js Pass (has render(); WebGL), a node function (input, ctx) => node (WebGPU), ' +
523
528
  "or an effect { name: 'myEffect', create: ctx => pass, node: (input, ctx) => node } / { name, fuse: { glsl } } (both renderers, see PostEffect)");
524
529
  }
530
+
531
+ export const handRolled = [{ kind: 'post', seen: 'an EffectComposer or post pass of its own', use: 'engine.post.add(pass) with @threedog/post-effects (bloom, ao, lut, outline, dof)', code: /\bnew\s+(?:THREE\.)?(?:EffectComposer|UnrealBloomPass|RenderPass|OutputPass)\b/, quiet: /\bpost\.add\b/, docRef: 'recipes/52-around-the-picture.md#post-effect-chain' }];
package/render/backend.js CHANGED
@@ -13,6 +13,16 @@ import { notePatch, patchOn } from '../core/scene/threePatches.js';
13
13
  import { isShown } from '../core/base/util.js';
14
14
  import { checkVertexInputs } from './vertexInputs.js';
15
15
  import { checkBindingLimits } from './bindingLimits.js';
16
+ import { nodeFrameOf, startRendererAnimation, canvasViewportOf, readScissorState } from './threeCompat.js';
17
+
18
+ /** Page-wide caches and borrow-stack state kept in one mutable container (zero top-level lets) */
19
+ const STATE = {
20
+ probedName: /** @type {string | null} */ (null),
21
+ depth: 0,
22
+ math: /** @type {{ Vector4: any, Color: any } | null} */ (null),
23
+ cv: /** @type {any} */ (null),
24
+ deviceFrom: /** @type {any} */ (null),
25
+ };
16
26
 
17
27
  /** Samples of the MSAA the post chain's targets use, on both renderers */
18
28
  export const MSAA_SAMPLES = 4;
@@ -183,16 +193,38 @@ export function holdShadowRedraw(r, scene) {
183
193
  return () => setShadowUpdate(r, scene, { auto: was });
184
194
  }
185
195
 
186
- /** Whether a shadow redraw is already requested for the next render @param {any} r @param {any} scene @returns {boolean} */
187
- export function shadowUpdatePending(r, scene) {
188
- if (!isWebGPU(r) && r.shadowMap.needsUpdate) return true;
189
- for (const o of shadowLights(scene)) {
190
- if (!isWebGPU(r)) { if (o.castShadow && o.shadow.needsUpdate) return true; continue; }
191
- // with cascades the light's own map is never drawn, so its needsUpdate is never cleared: only the cascades' flags count
192
- const c = cascadeShadows(o);
193
- if ((c.length ? c : [o.shadow]).some(s => s.needsUpdate)) return true;
196
+ /**
197
+ * Request a shadow redraw on the next render for one light (and any extra / cascade lights) without waking other throttled shadow lights.
198
+ * @internal
199
+ * @param {any} r @param {any} light @param {any[]} [extra]
200
+ */
201
+ export function redrawLightShadow(r, light, extra = []) {
202
+ if (!isWebGPU(r) && !r.shadowMap.autoUpdate) r.shadowMap.needsUpdate = true;
203
+ for (const s of [light.shadow, ...cascadeShadows(light), ...extra.map(l => l.shadow)]) if (s) s.needsUpdate = true;
204
+ }
205
+
206
+ /**
207
+ * Whether a shadow redraw is already pending for one light (or its cascade lights).
208
+ * @internal
209
+ * @param {any} r @param {any} light @param {any[]} [extra] @returns {boolean}
210
+ */
211
+ export function lightShadowPending(r, light, extra = []) {
212
+ if (!isWebGPU(r)) {
213
+ if (r.shadowMap.needsUpdate) return true;
214
+ return [light, ...extra].some(l => l.castShadow && l.shadow?.needsUpdate);
194
215
  }
195
- return false;
216
+ const c = cascadeShadows(light);
217
+ return (c.length ? c : [light.shadow]).some(s => s?.needsUpdate);
218
+ }
219
+
220
+ /**
221
+ * Whether `to` moved farther than one quarter of `radius` from `from` (early redraw trigger for shadow boxes and cascades).
222
+ * @internal
223
+ * @param {{ x: number, y: number, z: number }} from @param {{ x: number, y: number, z: number }} to @param {number} radius @returns {boolean}
224
+ */
225
+ export function leftQuarter(from, to, radius) {
226
+ const dx = to.x - from.x, dy = to.y - from.y, dz = to.z - from.z;
227
+ return dx * dx + dy * dy + dz * dz > (radius / 4) ** 2;
196
228
  }
197
229
 
198
230
  /**
@@ -267,7 +299,6 @@ function tierOf(name) {
267
299
  } catch (e) { warnOnce(`[backend] the device tier could not be detected (${e?.message ?? e}); assuming a high-end device`); } // said once: a wrong guess changes every tier-following default
268
300
  return 'high';
269
301
  }
270
- let probedName = /** @type {string | null} */ (null);
271
302
  /**
272
303
  * The tier before the engine builds its renderer, read from a throwaway 1x1 WebGL context (made once a page, then released). Why: the
273
304
  * canvas's own MSAA (antialias) is fixed when its context is created, and the default MSAA follows the tier; with the tier known first, an
@@ -276,12 +307,12 @@ let probedName = /** @type {string | null} */ (null);
276
307
  */
277
308
  export function tierBeforeRenderer() {
278
309
  return tierOf(() => {
279
- if (probedName === null) {
310
+ if (STATE.probedName === null) {
280
311
  const c = document.createElement('canvas'), gl = c.getContext('webgl2') ?? c.getContext('webgl');
281
- probedName = glName(gl);
312
+ STATE.probedName = glName(gl);
282
313
  gl?.getExtension('WEBGL_lose_context')?.loseContext();
283
314
  }
284
- return probedName;
315
+ return STATE.probedName;
285
316
  });
286
317
  }
287
318
  /** Whether r draws to its canvas with MSAA of its own (WebGL: the context's antialias; WebGPU: renderer.samples), both fixed at creation @param {any} r */
@@ -309,11 +340,11 @@ const drawnIn = new WeakMap();
309
340
  * @param {any} r
310
341
  */
311
342
  export function freshFrame(r) {
312
- const f = isWebGPU(r) ? r._nodes?.nodeFrame : null; // _nodes exists after init(); before it nothing has been drawn
343
+ const f = isWebGPU(r) ? nodeFrameOf(r) : null; // available after init(); before it nothing has been drawn
313
344
  if (!f) return;
314
345
  // three's first render() starts that tick, and starting it runs one tick at once: left to render(), the id moves inside the first draw, after the
315
346
  // line below noted it, so the next draw took the id for new and its scene pass, already done in that id, showed the first draw's picture again
316
- r._animation.start();
347
+ startRendererAnimation(r);
317
348
  if (drawnIn.get(r) === f.frameId) { f.update(); r.info.frame = f.frameId; }
318
349
  drawnIn.set(r, f.frameId);
319
350
  }
@@ -337,11 +368,8 @@ export function renderOnce(r, scene, camera, target = null) {
337
368
  // What a task draws into (its own targets, materials, the layers of its own objects) stays the task's to make and free.
338
369
  /** One saved state per nesting depth, reused: borrows run every frame (auto exposure, soft particles, onRender hooks), so the saved vectors are not made anew each time */
339
370
  const held = [];
340
- let depth = 0;
341
- /** three's Vector4 and Color, handed in by core/engine/Engine.js (it imports 'three'; three/webgpu shares the same three.core.js classes) */
342
- let M = /** @type {{ Vector4: any, Color: any } | null} */ (null), _cv = /** @type {any} */ (null);
343
371
  /** @param {{ Vector4: any, Color: any }} classes */
344
- export function mathClasses({ Vector4, Color }) { M = { Vector4, Color }; _cv = new Vector4(); }
372
+ export function mathClasses({ Vector4, Color }) { STATE.math = { Vector4, Color }; STATE.cv = new Vector4(); }
345
373
  /**
346
374
  * Save the renderer state a borrow may change. Pair it with releaseRenderer(s, putBack) in a finally (borrowRenderer does both).
347
375
  * Saved: the target with its cube face and mip level, viewport, scissor and scissor test, clear color and alpha, autoClear (and its color / depth /
@@ -355,9 +383,9 @@ export function mathClasses({ Vector4, Color }) { M = { Vector4, Color }; _cv =
355
383
  * @param {any} r @param {{ scene?: any, camera?: any, clean?: boolean }} [o] @returns {any}
356
384
  */
357
385
  export function holdRenderer(r, { scene = null, camera = null, clean = false } = {}) {
358
- const V = /** @type {any} */ (M).Vector4; // null only when the engine core was never loaded: nothing can hand this file a renderer then
359
- const s = held[depth] ??= { viewport: new V(), scissor: new V(), color: new (/** @type {any} */ (M).Color)(), current: new V(), box: new V() };
360
- s.depth = depth++; s.r = r; s.scene = scene; s.camera = camera;
386
+ const V = /** @type {any} */ (STATE.math).Vector4; // null only when the engine core was never loaded: nothing can hand this file a renderer then
387
+ const s = held[STATE.depth] ??= { viewport: new V(), scissor: new V(), color: new (/** @type {any} */ (STATE.math).Color)(), current: new V(), box: new V() };
388
+ s.depth = STATE.depth++; s.r = r; s.scene = scene; s.camera = camera;
361
389
  s.target = r.getRenderTarget(); s.face = r.getActiveCubeFace(); s.mip = r.getActiveMipmapLevel();
362
390
  r.getViewport(s.viewport); r.getScissor(s.scissor); s.scissorTest = r.getScissorTest();
363
391
  r.getClearColor(s.color); s.alpha = r.getClearAlpha();
@@ -366,12 +394,11 @@ export function holdRenderer(r, { scene = null, camera = null, clean = false } =
366
394
  s.gpu = isWebGPU(r);
367
395
  if (s.gpu) {
368
396
  s.mrt = r.getMRT(); s.objectFn = r.getRenderObjectFunction(); s.opaque = r.opaque; s.transparent = r.transparent;
369
- // Vector4.copy (getViewport) drops the depth range, and setViewport(vector) puts 0..1 back: read from the canvas target (no public getter)
370
- const v = r.getCanvasTarget?.()._viewport; s.minDepth = v?.minDepth ?? 0; s.maxDepth = v?.maxDepth ?? 1;
397
+ // Vector4.copy (getViewport) drops the depth range, and setViewport(vector) puts 0..1 back: read via threeCompat (no public getter)
398
+ const v = canvasViewportOf(r); s.minDepth = v?.minDepth ?? 0; s.maxDepth = v?.maxDepth ?? 1;
371
399
  } else {
372
400
  r.getCurrentViewport(s.current);
373
- const gl = r.getContext(), b = gl.getParameter(gl.SCISSOR_BOX); // three keeps the drawing scissor nowhere readable
374
- if (b) s.box.set(b[0], b[1], b[2], b[3]); s.boxTest = gl.isEnabled(gl.SCISSOR_TEST); // b is null on a lost context
401
+ s.boxTest = readScissorState(r, s.box);
375
402
  }
376
403
  if (scene) { s.override = scene.overrideMaterial; s.background = scene.background; s.bgNode = scene.backgroundNode; s.fog = scene.fog; s.fogNode = scene.fogNode; }
377
404
  if (camera) s.layers = camera.layers.mask;
@@ -387,7 +414,7 @@ export function holdRenderer(r, { scene = null, camera = null, clean = false } =
387
414
  * @param {any} s @param {boolean} [putBack]
388
415
  */
389
416
  export function releaseRenderer(s, putBack = true) {
390
- depth = s.depth;
417
+ STATE.depth = s.depth;
391
418
  const { r, scene, camera } = s;
392
419
  if (putBack) putBackState(s, r, scene, camera);
393
420
  s.r = s.scene = s.camera = s.target = s.mrt = s.objectFn = s.override = s.background = s.bgNode = s.fog = s.fogNode = null; // a slot keeps no scene alive between borrows
@@ -421,7 +448,7 @@ function putBackState(s, r, scene, camera) {
421
448
  if (s.gpu) return; // WebGPURenderer draws a target with the target's own viewport: the set values above are all it keeps
422
449
  // the drawing viewport differs from the target's own only when setViewport ran after the bind: running it again gives the same rounding;
423
450
  // otherwise (an ArrayCamera's sub-viewport left mid-render) only the GL viewport can be put back
424
- if (!r.getCurrentViewport(_cv).equals(s.current)) { r.setViewport(v); if (!r.getCurrentViewport(_cv).equals(s.current)) r.state.viewport(s.current); }
451
+ if (!r.getCurrentViewport(STATE.cv).equals(s.current)) { r.setViewport(v); if (!r.getCurrentViewport(STATE.cv).equals(s.current)) r.state.viewport(s.current); }
425
452
  r.state.scissor(s.box); r.state.setScissorTest(s.boxTest); // three's GL state cache: no GL call when already equal
426
453
  }
427
454
 
@@ -471,6 +498,21 @@ export function rebuildShadow(light) { light.dispatchEvent({ type: 'dispose' });
471
498
  /** A text that changes when the camera's projection does, for "did it change" checks @param {any} cam @returns {string} */
472
499
  export const projectionKey = cam => (cam.isPerspectiveCamera ? `${cam.fov},${cam.aspect},${cam.near},${cam.far},${cam.zoom}` : `${cam.left},${cam.right},${cam.top},${cam.bottom},${cam.near},${cam.far},${cam.zoom}`);
473
500
 
501
+ /**
502
+ * Zero-allocation numeric check for whether `cam`'s projection changed since the last call that wrote into `cache`.
503
+ * @param {any} cam @param {any} cache @returns {boolean}
504
+ */
505
+ export function syncProjection(cam, cache) {
506
+ if (cam.isPerspectiveCamera) {
507
+ if (cache.p === true && cache.lens === cam.fov && cache.aspect === cam.aspect && cache.near === cam.near && cache.far === cam.far && cache.zoom === cam.zoom) return false;
508
+ cache.p = true; cache.lens = cam.fov; cache.aspect = cam.aspect; cache.near = cam.near; cache.far = cam.far; cache.zoom = cam.zoom;
509
+ return true;
510
+ }
511
+ if (cache.p === false && cache.left === cam.left && cache.right === cam.right && cache.top === cam.top && cache.bottom === cam.bottom && cache.near === cam.near && cache.far === cam.far && cache.zoom === cam.zoom) return false;
512
+ cache.p = false; cache.left = cam.left; cache.right = cam.right; cache.top = cam.top; cache.bottom = cam.bottom; cache.near = cam.near; cache.far = cam.far; cache.zoom = cam.zoom;
513
+ return true;
514
+ }
515
+
474
516
  // ---------- the WebGPU route (createEngine({ renderer: 'webgpu' }); docs/plans/2026-11-03-webgpu-phase2.md section 1) ----------
475
517
 
476
518
  // One registration entry for everything threedog/tsl brings (the three/webgpu classes and each node-side part). Why one table here: before,
@@ -534,16 +576,15 @@ export async function whyNoWebGPU(limits, powerPreference) {
534
576
  if (!adapter) return 'requestAdapter() returned no adapter';
535
577
  // WebGPU hands out its default limits unless a higher one is asked for, whatever the hardware can do; asking what this adapter supports costs nothing and lifts each where it can
536
578
  if (limits) for (const k of ADAPTER_LIMITS) limits[k] ??= adapter.limits[k];
537
- if (deviceFrom === gpu) return null;
579
+ if (STATE.deviceFrom === gpu) return null;
538
580
  try { (await adapter.requestDevice()).destroy?.(); } catch (err) { return `requestDevice() failed: ${err?.message ?? err}`; }
539
- deviceFrom = gpu;
581
+ STATE.deviceFrom = gpu;
540
582
  return null;
541
583
  }
542
584
  // The defaults a game's picture can pass, asked for at the adapter's own value in the one place the engine requests a device (a game's own renderer keeps the game's limits):
543
585
  // the post chain's merged scene targets pass 32 bytes per pixel (render/fx/postWebGPU.tsl.js); a material with several texture layers, plus the lights' shadow maps, passes
544
586
  // 16 textures and samplers per stage; voxelGI's triangle buffer (three's VXGIVolume, about 200 bytes a triangle) passes a 256 MB buffer and a 128 MB storage binding
545
587
  const ADAPTER_LIMITS = ['maxColorAttachmentBytesPerSample', 'maxColorAttachments', 'maxSampledTexturesPerShaderStage', 'maxSamplersPerShaderStage', 'maxBufferSize', 'maxStorageBufferBindingSize'];
546
- let deviceFrom = null; // the navigator.gpu that gave a device (a page's stand-in for it is another object, so it is asked again)
547
588
 
548
589
  /** Each material on a scene object, once @param {any} scene @param {(m: any, o: any) => void} fn */
549
590
  function eachMaterial(scene, fn) {
@@ -29,7 +29,7 @@ import { sceneVisitor } from '../core/scene/sceneDelta.js';
29
29
  import { engineOwned } from '../core/scene/things.js';
30
30
  import { drawOnly } from '../core/scene/drawOnly.js';
31
31
  import { codedError } from '../core/base/errorHints.js';
32
- import { setShadowUpdate, shadowUpdatePending, shadowsOn, isWebGPU, webgpuPart, projectionKey } from './backend.js';
32
+ import { redrawLightShadow, lightShadowPending, leftQuarter, shadowsOn, isWebGPU, webgpuPart, syncProjection } from './backend.js';
33
33
 
34
34
  export const CASCADE_SPLITS = ['practical', 'uniform', 'logarithmic'];
35
35
  /** Fields of a cascade set besides its count; both entries start from these */
@@ -100,7 +100,7 @@ class LightCSM extends CSM {
100
100
  this.engine = e;
101
101
  this.light = light;
102
102
  this.at = new THREE.Vector3(Infinity, 0, 0); // camera position at the last placement
103
- this.proj = '';
103
+ this._proj = {};
104
104
  /** what entered the scene since the last frame (view.walks: how many full walks ran; tests read it) */
105
105
  this.view = sceneVisitor(e.scene, { enter: o => { if (!o.isMesh) return; const ms = o.material; if (Array.isArray(ms)) for (const m of ms) this.fit(m); else if (ms) this.fit(ms); } });
106
106
  const sc = light.shadow.camera;
@@ -131,14 +131,25 @@ class LightCSM extends CSM {
131
131
  this._getExtendedBreaks(U.CSM_cascades.value);
132
132
  U.cameraNear.value = this.camera.near; U.shadowFar.value = Math.min(this.camera.far, this.maxFar);
133
133
  }
134
- /** The light's shadow values reach the extra lights: what is written on the light is the one source */
134
+ /** The light's shadow values reach the extra lights: bias and normalBias scale with each cascade's frustum width ratio (capped at 8x) */
135
135
  shadowParams() {
136
- const s = this.light.shadow;
136
+ const s = this.light.shadow, lights = this.lights;
137
137
  this.shadowMapSize = s.mapSize.x; // the placement snaps to this texel size
138
- for (const l of this.lights) if (l !== this.light) {
139
- Object.assign(l.shadow, { bias: s.bias, normalBias: s.normalBias, radius: s.radius, blurSamples: s.blurSamples, intensity: s.intensity, autoUpdate: s.autoUpdate });
140
- if (s.needsUpdate) l.shadow.needsUpdate = true; // a budget asks on the light handed in; every cascade redraws with it
141
- if (l.shadow.mapSize.x !== s.mapSize.x) { l.shadow.mapSize.copy(s.mapSize); l.shadow.map?.dispose(); l.shadow.map = null; }
138
+ const c0 = lights[0]?.shadow?.camera, w0 = c0 ? Math.abs(c0.right - c0.left) : 0;
139
+ for (let i = 0; i < lights.length; i++) {
140
+ const l = lights[i];
141
+ if (l === this.light) continue;
142
+ const ls = l.shadow, sc = ls.camera;
143
+ const wi = sc ? Math.abs(sc.right - sc.left) : 0;
144
+ const k = w0 > 1e-6 && wi > 1e-6 ? Math.min(8, Math.max(1, wi / w0)) : Math.min(8, i + 1);
145
+ ls.bias = s.bias * k;
146
+ ls.normalBias = s.normalBias * k;
147
+ ls.radius = s.radius;
148
+ ls.blurSamples = s.blurSamples;
149
+ ls.intensity = s.intensity;
150
+ ls.autoUpdate = s.autoUpdate;
151
+ if (s.needsUpdate) ls.needsUpdate = true; // a budget asks on the light handed in; every cascade redraws with it
152
+ if (ls.mapSize.x !== s.mapSize.x || ls.mapSize.y !== s.mapSize.y) { ls.mapSize.copy(s.mapSize); ls.map?.dispose(); ls.map = null; }
142
153
  }
143
154
  }
144
155
  /**
@@ -148,10 +159,10 @@ class LightCSM extends CSM {
148
159
  frame(lightDir, updateEvery) {
149
160
  const e = this.engine, cam = e.camera, light = this.light;
150
161
  this.view.sync();
151
- this.shadowParams();
152
- const proj = projectionKey(cam);
162
+ const projChanged = syncProjection(cam, this._proj);
153
163
  let force = false;
154
- if (this.camera !== cam || proj !== this.proj) { this.camera = cam; this.proj = proj; this.updateFrustums(); force = true; }
164
+ if (this.camera !== cam || projChanged) { this.camera = cam; this.updateFrustums(); force = true; }
165
+ this.shadowParams();
155
166
  this.lightDirection.copy(lightDir).negate(); // CSM points from the light into the scene
156
167
  // with no shadow on the light the extra lights would only add light (the patch's bands need the shadow lights): hide them
157
168
  const show = light.visible && light.castShadow && !!light.parent && shadowsOn(e);
@@ -160,9 +171,9 @@ class LightCSM extends CSM {
160
171
  _cam.setFromMatrixPosition(cam.matrixWorld); // world: a camera on a rig keeps a small local position while it travels
161
172
  // not updating every frame: also place early when the camera left a quarter of the nearest cascade (teleport, fast travel)
162
173
  const near = this.breaks[0] * Math.min(cam.far, this.maxFar);
163
- if (updateEvery <= 1 || shadowUpdatePending(e.renderer, e.scene) || force || this.at.distanceToSquared(_cam) > (near / 4) ** 2) {
174
+ if (updateEvery <= 1 || lightShadowPending(e.renderer, light, this.lights) || force || leftQuarter(this.at, _cam, near)) {
164
175
  this.update(); this.at.copy(_cam);
165
- if (updateEvery > 1) setShadowUpdate(e.renderer, e.scene, { now: true });
176
+ if (updateEvery > 1) redrawLightShadow(e.renderer, light, this.lights);
166
177
  }
167
178
  }
168
179
  /** Switch off: extra lights out, the 'csm' patch off every material it went on */
@@ -198,5 +209,5 @@ export function dropCascades(e) {
198
209
  const sc = c.light.shadow.camera;
199
210
  Object.assign(sc, c._box); sc.updateProjectionMatrix();
200
211
  e._cascades = null;
201
- setShadowUpdate(e.renderer, e.scene, { now: true });
212
+ redrawLightShadow(e.renderer, c.light);
202
213
  }
@@ -14,7 +14,8 @@
14
14
  // built first and would keep drawing the old one.
15
15
  import { Object3D } from 'three/webgpu';
16
16
  import { CSMShadowNode } from 'three/addons/csm/CSMShadowNode.js';
17
- import { setShadowUpdate, shadowUpdatePending, registerWebGPUPart, rebuildShadow, projectionKey } from './backend.js';
17
+ import { redrawLightShadow, lightShadowPending, leftQuarter, registerWebGPUPart, rebuildShadow, syncProjection } from './backend.js';
18
+ import { initCascadeShadowNode, cascadeShadowNodesOf } from './threeCompat.js';
18
19
 
19
20
  class CascadeNode extends CSMShadowNode {
20
21
  /** @param {any} e @param {any} light @param {any} S the cascade fields */
@@ -25,17 +26,17 @@ class CascadeNode extends CSMShadowNode {
25
26
  this.fade = S.fade;
26
27
  this._engine = e; // underscore names: three walks a node's public fields looking for child nodes
27
28
  this._at = { x: Infinity, y: 0, z: 0 }; // camera position at the last early update
29
+ this._pos = { x: 0, y: 0, z: 0 };
28
30
  this._aim = new Object3D(); // the light's target in world space, for three's node (updateBefore)
29
- this._proj = '';
31
+ this._proj = {};
30
32
  const sc = light.shadow.camera;
31
33
  Object.assign(sc, { near: 1, far: S.lightMargin + 2 * S.maxFar }); sc.updateProjectionMatrix();
32
34
  light.shadow.shadowNode = this;
33
35
  rebuildShadow(light);
34
36
  }
35
37
  setup(builder) {
36
- // _init is the node's own first-build step (cascade stand-in lights, frustums); run it with the engine camera instead of builder.camera
37
- // (private to three, so not in @types/three)
38
- if (this.camera === null) /** @type {any} */ (this)._init({ camera: this._engine.camera, renderer: builder.renderer });
38
+ // initCascadeShadowNode runs three's first-build step (cascade stand-in lights, frustums) with engine.camera instead of builder.camera
39
+ if (this.camera === null) initCascadeShadowNode(this, this._engine.camera, builder.renderer);
39
40
  // the game's filter (pcss from threedog/tsl, or its own) reaches every cascade: three's LightShadow.copy, which made them, leaves filterNode out
40
41
  for (const l of this.lights) l.shadow.filterNode = /** @type {any} */ (this.light).shadow.filterNode;
41
42
  return super.setup(builder);
@@ -53,15 +54,24 @@ class CascadeNode extends CSMShadowNode {
53
54
  }
54
55
  fit() {}
55
56
  gameMaterials() { return []; }
56
- /** The light's shadow values reach the cascades (the node itself scales bias by cascade: bias x (i + 1), kept) */
57
+ /** The light's shadow values reach the cascades: bias and normalBias scale with each cascade's frustum width ratio (capped at 8x, aligned with WebGL) */
57
58
  shadowParams() {
58
- const s = /** @type {any} */ (this.light).shadow;
59
- this.lights.forEach((l, i) => {
60
- Object.assign(l.shadow, { bias: s.bias * (i + 1), normalBias: s.normalBias, radius: s.radius, blurSamples: s.blurSamples, intensity: s.intensity, autoUpdate: s.autoUpdate });
61
- l.shadow.mapSize.copy(s.mapSize);
62
- if (s.needsUpdate) l.shadow.needsUpdate = true; // a budget asks on the light handed in; every cascade redraws with it
63
- });
64
- if (this.lights.length) s.needsUpdate = false; // with cascades the light's own map is never drawn, so nothing else clears it
59
+ const s = /** @type {any} */ (this.light).shadow, lights = this.lights;
60
+ const c0 = lights[0]?.shadow?.camera, w0 = c0 ? Math.abs(c0.right - c0.left) : 0;
61
+ for (let i = 0; i < lights.length; i++) {
62
+ const ls = lights[i].shadow, sc = ls.camera;
63
+ const wi = sc ? Math.abs(sc.right - sc.left) : 0;
64
+ const k = i === 0 ? 1 : (w0 > 1e-6 && wi > 1e-6 ? Math.min(8, Math.max(1, wi / w0)) : Math.min(8, i + 1));
65
+ ls.bias = s.bias * k;
66
+ ls.normalBias = s.normalBias * k;
67
+ ls.radius = s.radius;
68
+ ls.blurSamples = s.blurSamples;
69
+ ls.intensity = s.intensity;
70
+ ls.autoUpdate = s.autoUpdate;
71
+ ls.mapSize.copy(s.mapSize);
72
+ if (s.needsUpdate) ls.needsUpdate = true; // a budget asks on the light handed in; every cascade redraws with it
73
+ }
74
+ if (lights.length) s.needsUpdate = false; // with cascades the light's own map is never drawn, so nothing else clears it
65
75
  }
66
76
  /**
67
77
  * Per frame: follow a new camera / projection, update early after a jump. The node reads the light's direction itself, so the first argument (the WebGL
@@ -69,23 +79,24 @@ class CascadeNode extends CSMShadowNode {
69
79
  */
70
80
  frame(_, updateEvery) {
71
81
  const e = this._engine, cam = e.camera;
72
- this.shadowParams();
73
- if (this.camera === null) return; // not built yet: setup() takes engine.camera
74
- const proj = projectionKey(cam);
82
+ if (this.camera === null) { this.shadowParams(); return; } // not built yet: setup() takes engine.camera
83
+ const projChanged = syncProjection(cam, this._proj);
75
84
  let force = false;
76
- if (this.camera !== cam || proj !== this._proj) { this.camera = cam; this._proj = proj; this.updateFrustums(); force = true; }
85
+ if (this.camera !== cam || projChanged) { this.camera = cam; this.updateFrustums(); force = true; }
86
+ this.shadowParams();
77
87
  cam.updateMatrixWorld();
78
88
  if (updateEvery <= 1) return;
79
89
  // not updating every frame: also update early when the camera left a quarter of the nearest cascade (teleport, fast travel)
80
- const near = this.breaks[0] * Math.min(cam.far, this.maxFar), w = cam.matrixWorld.elements, p = { x: w[12], y: w[13], z: w[14] }, d = (p.x - this._at.x) ** 2 + (p.y - this._at.y) ** 2 + (p.z - this._at.z) ** 2;
81
- if (force || d > (near / 4) ** 2) { setShadowUpdate(e.renderer, e.scene, { now: true }); this._at = p; }
82
- else if (shadowUpdatePending(e.renderer, e.scene)) this._at = p;
90
+ const near = this.breaks[0] * Math.min(cam.far, this.maxFar), w = cam.matrixWorld.elements, p = this._pos;
91
+ p.x = w[12]; p.y = w[13]; p.z = w[14];
92
+ if (force || leftQuarter(this._at, p, near)) { redrawLightShadow(e.renderer, this.light); this._at.x = p.x; this._at.y = p.y; this._at.z = p.z; }
93
+ else if (lightShadowPending(e.renderer, this.light)) { this._at.x = p.x; this._at.y = p.y; this._at.z = p.z; }
83
94
  }
84
95
  /** Switch off: the cascade lights and maps go, the light gets its plain shadow back */
85
96
  drop() {
86
97
  const light = /** @type {any} */ (this.light);
87
98
  delete light.shadow.shadowNode; // three tests `!== undefined`: null would count as a node
88
- for (const n of /** @type {any} */ (this)._shadowNodes) n.dispose(); // the node's own dispose() leaves the cascade maps on the GPU (private field)
99
+ for (const n of cascadeShadowNodesOf(this)) n.dispose(); // the node's own dispose() leaves the cascade maps on the GPU
89
100
  this.dispose();
90
101
  rebuildShadow(light);
91
102
  }
package/render/fogLook.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { warnOnce } from '../core/base/validate.js';
6
6
  import { coded } from '../core/base/errorHints.js';
7
7
  import { isWebGPU } from './backend.js';
8
+ import { fogNodeColorInput } from './threeCompat.js';
8
9
 
9
10
  /**
10
11
  * The fog the renderer draws: on WebGPURenderer scene.fogNode when set, else scene.fog; on WebGLRenderer scene.fog only. A fogNode comes back as
@@ -17,7 +18,7 @@ import { isWebGPU } from './backend.js';
17
18
  export function fogLook(scene, renderer) {
18
19
  const n = isWebGPU(renderer) && scene.fogNode;
19
20
  if (!n) return scene.fog || null;
20
- const c = n.rawInputs?.[0], v = c?.isColor ? c : c?.value;
21
+ const c = fogNodeColorInput(n), v = c?.isColor ? c : c?.value;
21
22
  if (v?.isColor) return { color: v, isNode: true };
22
23
  warnOnce(coded('fog-fallback', 'scene.fogNode: its color is not a THREE.Color, color(..) or uniform(Color) (as in fog(color(0xaabbcc), factor)), so the sky dome\'s fog band, the water\'s grazing colour and the horizon check cannot match your fog and leave it out'), 'fog-node-unread');
23
24
  return { color: null, isNode: true };
@@ -9,4 +9,4 @@ export { detailNoise, detailBump } from './detail.tsl.js';
9
9
  export { wrapDiffuse, shadowTint, rim } from './lighting.tsl.js';
10
10
  export { celLighting } from './cel.tsl.js';
11
11
  export { pcss } from './pcss.tsl.js';
12
- export { waterWave, waterSurface, waterFresnel } from './water.tsl.js';
12
+ export { waterWave, waterRipple, waterSurface, waterFresnel } from './water.tsl.js';