@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -4,7 +4,6 @@ import {
4
4
  type Camera,
5
5
  type DirectionalLight,
6
6
  FrontSide,
7
- Frustum,
8
7
  type InstancedMesh,
9
8
  type Material,
10
9
  Matrix4,
@@ -53,8 +52,10 @@ import {
53
52
  ShadowBaseNode,
54
53
  type UniformNode,
55
54
  } from "three/webgpu";
55
+ import { readLaunchFlag } from "../debug.js";
56
56
  import { shadowRedrawGpuMs } from "../render-pass-budget.js";
57
57
  import { DEFAULT_TARGET_FPS } from "../target-fps.js";
58
+ import { frustumPlanes } from "../world-gpu-types.js";
58
59
  import { isLeafReceiver } from "./soft-shadow.js";
59
60
  import {
60
61
  COST_SMOOTHING,
@@ -196,7 +197,6 @@ const _forward = new Vector3();
196
197
  /** A level's own light frustum, read once per level render and handed to its dispatch. */
197
198
  const _shadowProjection = new Matrix4();
198
199
  const _oldWorld = new Matrix4();
199
- const _shadowFrustum = new Frustum();
200
200
  const _shadowPlanes = new Float32Array(24);
201
201
  /** The depth row a level's map was drawn under, and the one this frame proposes: uploaded float32. */
202
202
  const _drawnDepth = new Float32Array(4);
@@ -214,8 +214,11 @@ interface IRenderingShadowNode {
214
214
 
215
215
  /** The slot the native bridge fills with its command sink on a core shadow node. */
216
216
  const COMMAND_KEY = Symbol.for("threenative.virtualShadowCommand");
217
+ /** The owned engine runs the clipmap and never calls updateBefore: it answers `settled` here each world render. */
218
+ const ENGINE_SETTLED_KEY = Symbol.for("threenative.virtualShadowSettled");
217
219
  interface ICommandSlot {
218
220
  [COMMAND_KEY]?: (value: object) => void;
221
+ [ENGINE_SETTLED_KEY]?: boolean;
219
222
  }
220
223
 
221
224
  /**
@@ -303,6 +306,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
303
306
 
304
307
  /** Every map is present and no requested/delayed invalidation remains. */
305
308
  get settled(): boolean {
309
+ const engine = (this as ICommandSlot)[ENGINE_SETTLED_KEY];
310
+ if (engine !== undefined) return engine;
306
311
  return (
307
312
  this.#initialised &&
308
313
  this.#levels.length > 0 &&
@@ -1704,15 +1709,8 @@ export class VirtualShadowNode extends ShadowBaseNode {
1704
1709
  shadow.camera.projectionMatrix,
1705
1710
  shadow.camera.matrixWorldInverse,
1706
1711
  );
1707
- _shadowFrustum.setFromProjectionMatrix(_shadowProjection);
1708
1712
  const planes = _shadowPlanes;
1709
- for (const [at, plane] of _shadowFrustum.planes.entries()) {
1710
- const offset = at * 4;
1711
- planes[offset] = plane.normal.x;
1712
- planes[offset + 1] = plane.normal.y;
1713
- planes[offset + 2] = plane.normal.z;
1714
- planes[offset + 3] = plane.constant;
1715
- }
1713
+ frustumPlanes(_shadowProjection, planes);
1716
1714
  // Every compute leaves the one node frame every node shares with its fields at their bare
1717
1715
  // defaults — `scene` among them, which `Nodes.getNodeFrame()` sets with no arguments
1718
1716
  // (three.webgpu.js:56215, reached from `Renderer.compute` at 62235) and nothing puts back; the
@@ -2177,13 +2175,19 @@ export class VirtualShadowNode extends ShadowBaseNode {
2177
2175
  if (builder.renderer.shadowMap.enabled === false) return null;
2178
2176
  // Read once, like tnShadowStats. Build no diagnostic nodes unless the URL switch is on.
2179
2177
  if (this.#levelsRequested === undefined) {
2180
- const search = globalThis.location?.search ?? "";
2181
- this.#levelsRequested = /[?&]tnShadowLevels=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(search);
2178
+ // One read of the URL for both switches: setup runs once, before the shader graph exists.
2179
+ const search = globalThis.location?.search;
2180
+ // Query only, as it always was: no environment variable and no global named these switches.
2181
+ this.#levelsRequested = readLaunchFlag(
2182
+ { environment: "", query: "tnShadowLevels" },
2183
+ "on",
2184
+ search,
2185
+ );
2182
2186
  // Counter runs: a fixed refreshStep, since the adaptive step follows measured render cost and
2183
2187
  // two runs of one route would move their windows at different ticks. Set once, before a frame.
2184
2188
  if (
2185
2189
  this.#adaptiveRefreshGiven === undefined &&
2186
- /[?&]tnAdaptiveRefresh=(?:0|false)(?:&|$)/u.test(search)
2190
+ readLaunchFlag({ environment: "", query: "tnAdaptiveRefresh" }, "off", search)
2187
2191
  ) {
2188
2192
  (this.options as { adaptiveRefresh: boolean }).adaptiveRefresh = false;
2189
2193
  }
@@ -2847,9 +2851,7 @@ export class VirtualShadowNode extends ShadowBaseNode {
2847
2851
 
2848
2852
  /** Whether `?tnShadowStats=1` is on this launch's URL, read once. */
2849
2853
  #statsWalkRequested(): boolean {
2850
- this.#statsRequested ??= /[?&]tnShadowStats=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(
2851
- globalThis.location?.search ?? "",
2852
- );
2854
+ this.#statsRequested ??= readLaunchFlag({ environment: "", query: "tnShadowStats" });
2853
2855
  return this.#statsRequested;
2854
2856
  }
2855
2857
 
@@ -37,9 +37,11 @@ import {
37
37
  mat3,
38
38
  mat4,
39
39
  max,
40
+ min,
40
41
  modelWorldMatrix,
41
42
  normalize,
42
43
  positionGeometry,
44
+ renderGroup,
43
45
  screenCoordinate,
44
46
  select,
45
47
  sin,
@@ -63,6 +65,7 @@ import {
63
65
  type NodeBuilder,
64
66
  type NodeMaterial,
65
67
  } from "three/webgpu";
68
+ import { readLaunchFlag } from "../debug.js";
66
69
  import { IMPOSTOR_VIEW_GRID, type WorldImpostorAtlas } from "./world-impostor.js";
67
70
 
68
71
  type InstanceMatrixFn = () => Node<"mat4">;
@@ -146,6 +149,19 @@ const GEOMETRY_MAPS = [
146
149
  "transmissionMap",
147
150
  ] as const;
148
151
 
152
+ /**
153
+ * The node twins of those maps: a source's surface nodes describe its own mesh (a crown's ao and
154
+ * emissive sample its texture through `attribute("uv")`), which the quad does not have. Its scalar
155
+ * roughness and metalness stay; colour, normal, coverage and the cutout are the atlas's own nodes.
156
+ */
157
+ const SURFACE_NODES = [
158
+ "aoNode",
159
+ "emissiveNode",
160
+ "roughnessNode",
161
+ "metalnessNode",
162
+ "maskNode",
163
+ ] as const;
164
+
149
165
  /** One `mat4` node per CPU instance-matrix attribute, derived once and kept live with its source. */
150
166
  const INSTANCE_COLUMNS = new WeakMap<InstancedBufferAttribute, InstancedInterleavedBuffer>();
151
167
 
@@ -157,6 +173,13 @@ export interface IImpostorSurfaceOptions {
157
173
  readonly center: Vector3;
158
174
  /** The baked bounds' radius in asset-local space. */
159
175
  readonly radius: number;
176
+ /**
177
+ * The baked box's half size per asset-local axis (`impostorBounds`). With it the quad fits the
178
+ * box's projection instead of the bounding sphere: a spruce is a quarter of its sphere's square,
179
+ * and every fragment outside it ran the whole lit shader only to be discarded. Omitted, the quad
180
+ * is the sphere's square.
181
+ */
182
+ readonly halfExtents?: Vector3;
160
183
  /** The dominant source material; its class, roughness and metalness set the lit surface. */
161
184
  readonly source: Material;
162
185
  /** The source's own cutoff, or the scatter default. Kept positive for the shadow alpha caster. */
@@ -420,6 +443,7 @@ export class WorldImpostorSurface {
420
443
  throw new Error("WorldImpostorSurface requires a baked atlas.");
421
444
  const material = cloneLitMaterial(options.source);
422
445
  for (const key of GEOMETRY_MAPS) Reflect.set(material, key, null);
446
+ for (const key of SURFACE_NODES) Reflect.set(material, key, null);
423
447
  // Albedo and coverage are baked into the atlas; a vertex-colour attribute the quad does not
424
448
  // have, an opacity multiplier or an opacity node would apply the source's own colour and
425
449
  // coverage a second time on top of the baked one.
@@ -441,6 +465,8 @@ export class WorldImpostorSurface {
441
465
 
442
466
  const centerUniform = uniform(center);
443
467
  const radiusUniform = uniform(radius);
468
+ const halfUniform =
469
+ options.halfExtents === undefined ? undefined : uniform(options.halfExtents.clone());
444
470
  const cull = options.cull === true;
445
471
  const name = `WorldImpostorSurface${surfaceId}`;
446
472
  surfaceId += 1;
@@ -465,7 +491,22 @@ export class WorldImpostorSurface {
465
491
  const dAsset = normalize(asMat3(view).inverse().mul(eyeView));
466
492
  const basis = frameBasisNode(dAsset);
467
493
  const corner = positionGeometry.xy;
468
- const rel = basis.right.mul(corner.x).add(basis.up.mul(corner.y)).mul(radiusUniform);
494
+ // `impostorQuadExtents` on the GPU: the box's footprint circle across, its projection on `up`
495
+ // down, each with the slack a neighbouring frame's blend reaches, never past the sphere.
496
+ const extent = halfUniform
497
+ ? vec2(
498
+ min(radiusUniform, length(halfUniform.xz).mul(QUAD_ACROSS_SLACK)),
499
+ min(
500
+ radiusUniform,
501
+ abs(basis.up.x)
502
+ .mul(halfUniform.x)
503
+ .add(abs(basis.up.y).mul(halfUniform.y))
504
+ .add(abs(basis.up.z).mul(halfUniform.z))
505
+ .mul(QUAD_UP_SLACK),
506
+ ),
507
+ )
508
+ : vec2(radiusUniform, radiusUniform);
509
+ const rel = basis.right.mul(corner.x.mul(extent.x)).add(basis.up.mul(corner.y.mul(extent.y)));
469
510
  // A main-pass horizontal-distance gate: when the instance centre is past the asset's own cull
470
511
  // the quad collapses to a point, which the rasteriser drops. The cull is a per-instance
471
512
  // attribute, so one surface serves every canonical asset over this atlas each at its own
@@ -509,6 +550,9 @@ export class WorldImpostorSurface {
509
550
  transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder)),
510
551
  )();
511
552
  material.positionNode = positionNode;
553
+ // A source's shadow position (a wind-swept crown casts its rest pose) would bypass the billboard
554
+ // above in the shadow draw: the quad must cast through its own positionNode.
555
+ material.castShadowPositionNode = null;
512
556
 
513
557
  const geometry = new BufferGeometry();
514
558
  geometry.setAttribute(
@@ -632,7 +676,17 @@ function buildFragmentNodes(
632
676
  const uvs: Node<"vec2">[] = [];
633
677
  const colors: Node<"vec4">[] = [];
634
678
  const normals: Node<"vec4">[] = [];
635
- for (let index = 0; index < 3; index += 1) {
679
+ // One march, on the frame the blend weighs most; the other two read the same surface point from
680
+ // their own view. Three marches were the far band's cost (PRD-866 AC-3).
681
+ const [wa, wb, wc] = weights as [Node<"float">, Node<"float">, Node<"float">];
682
+ const pickA = wa.greaterThanEqual(wb).and(wa.greaterThanEqual(wc));
683
+ const pickB = wb.greaterThanEqual(wc);
684
+ const [xa, xb, xc] = cellX as [Node<"float">, Node<"float">, Node<"float">];
685
+ const [ya, yb, yc] = cellY as [Node<"float">, Node<"float">, Node<"float">];
686
+ cellX.push(select(pickA, xa, select(pickB, xb, xc)));
687
+ cellY.push(select(pickA, ya, select(pickB, yb, yc)));
688
+ let marched: Node<"vec4"> | undefined;
689
+ for (let index = 3; index < 4; index += 1) {
636
690
  const direction = octahedralViewNode(
637
691
  cellX[index] as Node<"float">,
638
692
  cellY[index] as Node<"float">,
@@ -666,6 +720,7 @@ function buildFragmentNodes(
666
720
  const hit = Fn(() => {
667
721
  const found = float(0).toVar();
668
722
  const hitUv = vec2(2).toVar();
723
+ const hitT = float(0).toVar();
669
724
  const previousGap = float(0).toVar();
670
725
  const previousAlpha = float(0).toVar();
671
726
  const previousT = radiusUniform.toVar();
@@ -751,6 +806,7 @@ function buildFragmentNodes(
751
806
  ),
752
807
  () => {
753
808
  hitUv.assign(u);
809
+ hitT.assign(front.add(back).mul(0.5));
754
810
  found.assign(1);
755
811
  },
756
812
  );
@@ -764,11 +820,29 @@ function buildFragmentNodes(
764
820
  Break();
765
821
  });
766
822
  });
767
- return vec3(hitUv, found);
823
+ return vec4(hitUv, found, hitT);
768
824
  })();
769
- uvs.push(hit.xy);
770
- colors.push(colorMap.depth(layer).sample(hit.xy).mul(hit.z).toVar() as Node<"vec4">);
771
- normals.push(normalMap.depth(layer).sample(hit.xy).mul(hit.z).toVar() as Node<"vec4">);
825
+ marched = hit;
826
+ }
827
+
828
+ const surface = marched as Node<"vec4">;
829
+ const rayOut = normalize(select(orthographicNode(), dirVarying, dirVarying.sub(relVarying)));
830
+ const hitPoint = relVarying.add(rayOut.mul(surface.w));
831
+ for (let index = 0; index < 3; index += 1) {
832
+ const basis = frameBasisNode(
833
+ octahedralViewNode(cellX[index] as Node<"float">, cellY[index] as Node<"float">, grid),
834
+ );
835
+ const layer = (cellY[index] as Node<"float">)
836
+ .mul(grid)
837
+ .add(cellX[index] as Node<"float">)
838
+ .toInt();
839
+ const uv = vec2(dot(hitPoint, basis.right), dot(hitPoint, basis.up).negate())
840
+ .div(radiusUniform)
841
+ .mul(0.5)
842
+ .add(0.5);
843
+ uvs.push(uv);
844
+ colors.push(colorMap.depth(layer).sample(uv).mul(surface.z).toVar() as Node<"vec4">);
845
+ normals.push(normalMap.depth(layer).sample(uv).mul(surface.z).toVar() as Node<"vec4">);
772
846
  }
773
847
 
774
848
  const [w0, w1, w2] = weights as [Node<"float">, Node<"float">, Node<"float">];
@@ -787,6 +861,37 @@ function buildFragmentNodes(
787
861
  };
788
862
  }
789
863
 
864
+ /**
865
+ * Slack on the fitted quad. Across: a frame blended in from a neighbouring azimuth reprojects the
866
+ * footprint up to `1 / cos(45 deg)` wider, but its weight there is small, so a quarter covers it.
867
+ * Down: elevation neighbours shift the projection a little. Both stay inside the sphere's square.
868
+ */
869
+ const QUAD_ACROSS_SLACK = 1.25;
870
+ const QUAD_UP_SLACK = 1.1;
871
+
872
+ /**
873
+ * The quad's half width and half height for a view `direction` (asset space, toward the eye), as
874
+ * the surface's vertex shader computes them: the box footprint's circle across (any azimuth), the
875
+ * box's projection on the frame's `up` down, each with its slack and capped by the sphere radius.
876
+ */
877
+ export function impostorQuadExtents(
878
+ direction: Vector3,
879
+ halfExtents: Vector3,
880
+ radius: number,
881
+ ): { readonly across: number; readonly up: number } {
882
+ const { up } = impostorFrameBasis(direction);
883
+ return {
884
+ across: Math.min(radius, Math.hypot(halfExtents.x, halfExtents.z) * QUAD_ACROSS_SLACK),
885
+ up: Math.min(
886
+ radius,
887
+ (Math.abs(up.x) * halfExtents.x +
888
+ Math.abs(up.y) * halfExtents.y +
889
+ Math.abs(up.z) * halfExtents.z) *
890
+ QUAD_UP_SLACK,
891
+ ),
892
+ };
893
+ }
894
+
790
895
  /**
791
896
  * The frame basis the baker's orthographic camera actually built for `direction`: the three
792
897
  * endpoints of a view's own `lookAt`, so the sampler's projection and the bake share one basis.
@@ -864,6 +969,82 @@ export function advanceTemporalLod(
864
969
  state.alpha = window > 0 ? Math.min(1, Math.max(0, (now - lag - state.fromTime) / window)) : 1;
865
970
  }
866
971
 
972
+ /**
973
+ * The distance past which `level`'s gate discards every fragment at the worst per-instance random
974
+ * draw: `worldLodMaterial`'s fade-out mix reaches 1 at `gate + 0.75 * span` (0.5 of the ramp plus
975
+ * the 0.25 random swing). `undefined` for the last level, which has no coarser level to fade into.
976
+ */
977
+ export function lodFadedPast(
978
+ distances: readonly number[],
979
+ level: number,
980
+ width: number,
981
+ ): number | undefined {
982
+ const gate = level + 1;
983
+ const at = distances[gate];
984
+ if (at === undefined) return undefined;
985
+ let span = Math.min(at * width, (at - (distances[gate - 1] as number)) * width);
986
+ const next = distances[gate + 1];
987
+ if (next !== undefined) span = Math.min(span, (next - at) * width);
988
+ return at + 0.75 * span;
989
+ }
990
+
991
+ // `?lodCollapse=1` (TN_LOD_COLLAPSE, `__tnLodCollapse`) is read once per page; while it is on,
992
+ // `globalThis.__tnLodCollapse = false` turns the collapse off live for a paired A/B.
993
+ let lodCollapseArmed: boolean | undefined;
994
+ // Render group, as the LOD clock: an object-group uniform freezes on settled static batches.
995
+ const makeLodCollapseSwitch = () => uniform(1).setGroup(renderGroup);
996
+ let lodCollapseSwitch: ReturnType<typeof makeLodCollapseSwitch> | undefined;
997
+ function lodCollapseNode(): ReturnType<typeof makeLodCollapseSwitch> | undefined {
998
+ lodCollapseArmed ??= readLaunchFlag({
999
+ environment: "TN_LOD_COLLAPSE",
1000
+ query: "lodCollapse",
1001
+ global: "__tnLodCollapse",
1002
+ });
1003
+ if (!lodCollapseArmed) return undefined;
1004
+ lodCollapseSwitch ??= makeLodCollapseSwitch();
1005
+ return lodCollapseSwitch;
1006
+ }
1007
+
1008
+ /** Per frame: follow `globalThis.__tnLodCollapse` when the collapse was armed at boot. */
1009
+ export function syncLodCollapse(): void {
1010
+ if (lodCollapseSwitch === undefined) return;
1011
+ const live: unknown = Reflect.get(globalThis, "__tnLodCollapse");
1012
+ if (typeof live === "boolean") lodCollapseSwitch.value = live ? 1 : 0;
1013
+ }
1014
+
1015
+ /**
1016
+ * Collapse to one point the vertices of an instance whose every fragment the LOD gate discards:
1017
+ * past `past` from every eye the masks read, and not held whole by its published range or a swap.
1018
+ */
1019
+ function collapseFadedVertices(
1020
+ material: NodeMaterial,
1021
+ on: Node<"float">,
1022
+ gate: {
1023
+ readonly past: Node<"float">;
1024
+ readonly distances: readonly Node<"float">[];
1025
+ readonly lod: Node<"float">;
1026
+ readonly publishedRanges: boolean;
1027
+ readonly clock: Node<"float"> | undefined;
1028
+ },
1029
+ ): void {
1030
+ let faded = on.greaterThan(0.5);
1031
+ for (const distance of gate.distances) faded = faded.and(distance.greaterThanEqual(gate.past));
1032
+ if (gate.publishedRanges) {
1033
+ // A record whole at this level (`.y <= lod`) or still holding it after a swap draws anyway.
1034
+ const range = attribute("tnPublishedLodRange", "vec4") as Node<"vec4">;
1035
+ faded = faded.and(range.y.greaterThan(gate.lod));
1036
+ if (gate.clock !== undefined)
1037
+ faded = faded.and(
1038
+ range.z
1039
+ .lessThan(0)
1040
+ .or(gate.clock.sub(range.w).div(LOD_TEMPORAL_LAG).greaterThanEqual(1))
1041
+ .or(range.z.sub(gate.lod).abs().greaterThanEqual(0.5)),
1042
+ );
1043
+ }
1044
+ const position = (material.positionNode ?? positionGeometry) as Node<"vec3">;
1045
+ material.positionNode = select(faded, vec3(0, 0, 0), position);
1046
+ }
1047
+
867
1048
  /** Complementary LOD masks over the caller's distance bands, shared by colour and shadow passes. */
868
1049
  export function worldLodMaterial(
869
1050
  source: Material,
@@ -892,9 +1073,11 @@ export function worldLodMaterial(
892
1073
  .mul(vec4(0, 0, 0, 1)).xyz,
893
1074
  )();
894
1075
  // Quantise recovered roots so part-local float rounding cannot change the instance hash.
895
- const origin = varying(floor(root.mul(16).add(0.5)).div(16));
896
- const distanceTo = (at: Node<"vec3">) =>
897
- (spatial ? length(origin.sub(at)) : length(origin.xz.sub(at.xz))).mul(distanceBias);
1076
+ const quantised = floor(root.mul(16).add(0.5)).div(16);
1077
+ const origin = varying(quantised);
1078
+ const distanceFrom = (point: Node<"vec3">, at: Node<"vec3">) =>
1079
+ (spatial ? length(point.sub(at)) : length(point.xz.sub(at.xz))).mul(distanceBias);
1080
+ const distanceTo = (at: Node<"vec3">) => distanceFrom(origin, at);
898
1081
  const distance = distanceTo(eye);
899
1082
  const random = fract(sin(dot(origin.xz, vec2(12.9898, 78.233))).mul(43758.5453));
900
1083
  const noise = fract(sin(dot(floor(screenCoordinate.xy), vec2(12.9898, 78.233))).mul(43758.5453));
@@ -976,6 +1159,21 @@ export function worldLodMaterial(
976
1159
  material.maskShadowNode = material.maskShadowNode
977
1160
  ? (material.maskShadowNode as Node<"bool">).and(shadow)
978
1161
  : shadow;
1162
+ // PRD-888 lever 2: an instance past `lodFadedPast` has every colour and shadow fragment of this
1163
+ // level discarded, so its vertices collapse to one point and the rasteriser drops the triangles.
1164
+ // Read per instance in the vertex stage with the worst random draw and a 0.1 % margin, so the
1165
+ // varying's rounding cannot flip a fragment the gate would have drawn.
1166
+ const collapseOn = lodCollapseNode();
1167
+ if (collapseOn !== undefined)
1168
+ collapseFadedVertices(material, collapseOn, {
1169
+ past: uniform((lodFadedPast(distances, level, width) ?? 1e30) * 1.001),
1170
+ distances: (temporal === undefined ? [eye] : [eye, temporal.from, temporal.to]).map((at) =>
1171
+ distanceFrom(quantised, at),
1172
+ ),
1173
+ lod,
1174
+ publishedRanges,
1175
+ clock,
1176
+ });
979
1177
  if (publishedRanges) material.userData.tnPublishedLodRange = true;
980
1178
  return material;
981
1179
  }
@@ -152,6 +152,8 @@ export function impostorViewWeights(direction: Vector3): IViewBlend {
152
152
  export function impostorBounds(parts: readonly IImpostorPart[]): {
153
153
  readonly center: Vector3;
154
154
  readonly radius: number;
155
+ /** Half the baked box's size per asset-local axis, which fits the quad (`impostorQuadExtents`). */
156
+ readonly halfExtents: Vector3;
155
157
  } {
156
158
  const whole = new Box3();
157
159
  whole.makeEmpty();
@@ -168,10 +170,11 @@ export function impostorBounds(parts: readonly IImpostorPart[]): {
168
170
  whole.union(localBox);
169
171
  any = true;
170
172
  }
171
- if (!any) return { center: new Vector3(), radius: 0.5 };
173
+ if (!any) return { center: new Vector3(), radius: 0.5, halfExtents: new Vector3(0.5, 0.5, 0.5) };
172
174
  const center = whole.getCenter(new Vector3());
173
175
  const radius = whole.getBoundingSphere(new Sphere()).radius;
174
- return { center, radius: radius > 0 ? radius : 0.5 };
176
+ const halfExtents = whole.getSize(new Vector3()).multiplyScalar(0.5);
177
+ return { center, radius: radius > 0 ? radius : 0.5, halfExtents };
175
178
  }
176
179
 
177
180
  /** The exact byte cost of a mip chain of `levels` RGBA8 levels at `pixels` square and `depth` deep. */
@@ -112,6 +112,17 @@ const animationRateRootRefs = new WeakMap<Object3D, WeakRef<Object3D>>();
112
112
  /** The stand-ins named in {@link animationRateSources}, so the pass can reach them without a scene walk. */
113
113
  const animationRateCarriers = new Set<WeakRef<Object3D>>();
114
114
 
115
+ /** AnimationPlayer's disposal: the root stops carrying `state`, unless a newer player already took it. */
116
+ export function untrackAnimationRate(root: Object3D, state: IAnimationRateState): void {
117
+ if (animationRateStates.get(root) !== state) return;
118
+ animationRateStates.delete(root);
119
+ const id = engineRateIds.get(root);
120
+ if (id === undefined) return;
121
+ setEngineRateState(id, undefined);
122
+ const engineRig = root as Partial<IEngineRateRig>;
123
+ if (typeof engineRig.__trackAnimationRate === "function") engineRig.__trackAnimationRate(-1);
124
+ }
125
+
115
126
  /** A projection stand-in or skinned batch names the rigs it draws (see {@link animationRateSources}). */
116
127
  export function observeAnimationRates(
117
128
  carrier: Object3D,
@@ -121,9 +132,37 @@ export function observeAnimationRates(
121
132
  animationRateSources.set(carrier, sources);
122
133
  }
123
134
 
135
+ /**
136
+ * The engine's handle for each tracked root (PRD-878): the engine keeps the rigs and answers [handle, rate]
137
+ * pairs, so a frame finds each state by index instead of walking the roots in JS.
138
+ */
139
+ const engineRateIds = new WeakMap<Object3D, number>();
140
+ const engineRateStates: (IAnimationRateState | undefined)[] = [];
141
+ /** The live entries of {@link engineRateStates}: with none, a frame makes no band call at all. */
142
+ let engineRateRigs = 0;
143
+
144
+ function setEngineRateState(id: number, state: IAnimationRateState | undefined): void {
145
+ engineRateRigs += (state === undefined ? 0 : 1) - (engineRateStates[id] === undefined ? 0 : 1);
146
+ engineRateStates[id] = state;
147
+ }
148
+
149
+ interface IEngineRateRig {
150
+ __trackAnimationRate(id: number): void;
151
+ }
152
+
124
153
  /** AnimationPlayer's registration: the state the camera pass writes, and the root it is found on. */
125
154
  export function trackAnimationRate(root: Object3D, state: IAnimationRateState): void {
126
155
  animationRateStates.set(root, state);
156
+ const engineRig = root as Partial<IEngineRateRig>;
157
+ if (typeof engineRig.__trackAnimationRate === "function") {
158
+ let id = engineRateIds.get(root);
159
+ if (id === undefined) {
160
+ id = engineRateStates.length;
161
+ engineRateIds.set(root, id);
162
+ }
163
+ setEngineRateState(id, state);
164
+ engineRig.__trackAnimationRate(id);
165
+ }
127
166
  // One ref per root: a respawn's new player on the same root must not add a second walk of it.
128
167
  let ref = animationRateRootRefs.get(root);
129
168
  if (ref === undefined) {
@@ -230,10 +269,30 @@ function hierarchyRevision(object: Object3D): number | undefined {
230
269
  * Counts one costly step by name in `globalThis.__tnEngineCost`, the bag a playtest reads per frame
231
270
  * (core reports it per frame in TN_FRAME_BUDGET.counters.engine), so a kit that brings back a per-frame walk fails its bound.
232
271
  */
233
- function countEngineCost(name: string): void {
272
+ function countEngineCost(name: string, count = 1): void {
234
273
  const host = globalThis as { __tnEngineCost?: Record<string, number> };
235
274
  host.__tnEngineCost ??= {};
236
- host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + 1;
275
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + count;
276
+ }
277
+
278
+ /**
279
+ * A scene root whose engine runs the whole band pass (scene/projected_cull.h bandAnimation): [handle, rate]
280
+ * pairs, [handle, -1] for a freed rig, or undefined when a tracked rig sits inside another.
281
+ */
282
+ interface IEngineBandRoot {
283
+ __bandAnimation(
284
+ camera: Camera,
285
+ cameraResolved: boolean,
286
+ scale: number,
287
+ frame: number,
288
+ ): readonly number[] | undefined;
289
+ }
290
+
291
+ function engineBandRoot(root: unknown): IEngineBandRoot | undefined {
292
+ const candidate = root as Partial<IEngineBandRoot> | null;
293
+ return typeof candidate?.__bandAnimation === "function"
294
+ ? (candidate as IEngineBandRoot)
295
+ : undefined;
237
296
  }
238
297
 
239
298
  function engineCullRoot(root: unknown): IEngineCullRoot | undefined {
@@ -414,6 +473,12 @@ export class RenderCameraCull {
414
473
  this.#animationFrame += 1;
415
474
  this.#animationPrepared = true;
416
475
  this.#prepareCamera(camera, viewportHeight);
476
+ if (this.#bandOnEngine(root, camera)) {
477
+ // The engine bands every rig, so the JS rig cache rebuilds nothing: a measured 0, which the kit
478
+ // contract's per-window bound needs, never a missing counter.
479
+ countEngineCost("cullRigRebuilds", 0);
480
+ return;
481
+ }
417
482
  if (!this.#prepareAnimated()) return;
418
483
  // Start at each rig and each stand-in that observes one, never at the scene: the walk then visits
419
484
  // the same objects a scene walk would have acted on, and nothing else.
@@ -429,8 +494,8 @@ export class RenderCameraCull {
429
494
  const rig = ref.deref();
430
495
  if (rig === undefined || !this.#reaches(rig, root)) continue;
431
496
  turn += 1;
432
- if (!holds || turn % RATE_MEASURE_FRAMES === 0 || !this.#holdRate(rig))
433
- this.#visitRig(rig, rootShown);
497
+ if (holds && turn % RATE_MEASURE_FRAMES !== 0 && this.#holdRate(rig)) continue;
498
+ this.#visitRig(rig, rootShown);
434
499
  }
435
500
  for (const ref of animationRateCarriers) {
436
501
  const carrier = ref.deref();
@@ -447,6 +512,42 @@ export class RenderCameraCull {
447
512
  }
448
513
  }
449
514
 
515
+ /**
516
+ * On the engine, with no stand-in observing a rig, the whole pass is one call (PRD-878): the engine keeps the
517
+ * rigs, checks which reach the root, holds a crowd's rates and bands the rest. False sends the frame to the
518
+ * walk below: plain three, a stand-in, or a rig inside a rig.
519
+ */
520
+ #bandOnEngine(root: unknown, camera: Camera): boolean {
521
+ const engine = animationRateCarriers.size === 0 ? engineBandRoot(root) : undefined;
522
+ if (engine !== undefined && engineRateRigs === 0) return true;
523
+ const pairs = engine?.__bandAnimation(
524
+ camera,
525
+ this.#cameraResolved,
526
+ this.#scale,
527
+ this.#animationFrame,
528
+ );
529
+ if (pairs === undefined) return false;
530
+ this.#takeBands(pairs);
531
+ return true;
532
+ }
533
+
534
+ /** The engine's [handle, rate] pairs, written to each state as the JS walk writes it; -1 drops a freed rig. */
535
+ #takeBands(pairs: readonly number[]): void {
536
+ for (let index = 0; index + 1 < pairs.length; index += 2) {
537
+ const id = pairs[index] as number;
538
+ const rate = pairs[index + 1] as number;
539
+ if (rate < 0) {
540
+ setEngineRateState(id, undefined);
541
+ continue;
542
+ }
543
+ const state = engineRateStates[id];
544
+ if (state === undefined) continue;
545
+ state.rate = rate;
546
+ state.source = this;
547
+ state.frame = this.#animationFrame;
548
+ }
549
+ }
550
+
450
551
  /** Carries a rig's rate into this frame; false when last frame did not measure or hold it, as for a rig just shown. */
451
552
  #holdRate(rig: Object3D): boolean {
452
553
  const state = animationRateStates.get(rig);
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The environment measure-and-sample mechanism every kit repeats: what the scene's environment
3
+ * actually contributes, a bounded GPU sample of it with a cache and a readback deadline, the
4
+ * provenance a stale readback is rejected by, and the gate that decides which renderer may run
5
+ * the material lane. The backlight itself is a shader with fixed constants, so it stays in each
6
+ * kit's `src/render/` (stamped from one source there) where the game can change how it looks.
7
+ *
8
+ * This is machinery, not a look: every colour, gain and threshold arrives as an argument, and a kit
9
+ * that wants a different bound passes a different one. It lives here because twelve kits held
10
+ * byte-identical copies — 9 084 lines — so a fix to one left eleven wrong with every gate green
11
+ * (`c93b427d0` touched 552 files for one look change).
12
+ *
13
+ * @situation measure what a scene's environment actually contributes
14
+ * @situation sample the environment on the GPU without stalling the frame
15
+ * @situation keep an environment readback from reaching a frame it does not belong to
16
+ */
17
+ export {
18
+ type IEnvironmentMeasurement,
19
+ measureEnvironment,
20
+ reportEnvironmentContribution,
21
+ } from "./render/environment/environmentContribution.js";
22
+ export { sampledRadiance } from "./render/environment/environmentRadiance.js";
23
+ export {
24
+ cacheEnvironmentSample,
25
+ cachedEnvironmentSample,
26
+ } from "./render/environment/environmentSampleCache.js";
27
+ export {
28
+ type IEnvironmentSample,
29
+ sampleEnvironment,
30
+ } from "./render/environment/environmentSampling.js";
31
+ export {
32
+ type IEnvironmentSourceSnapshot,
33
+ captureEnvironmentSnapshot,
34
+ environmentSnapshotCurrent,
35
+ samplingSourceSupported,
36
+ } from "./render/environment/environmentSnapshot.js";
37
+ export {
38
+ type IMaterialLightingEnvironment,
39
+ isWebGLFallbackRenderer,
40
+ materialLightingEnabled,
41
+ } from "./render/environment/gate.js";