@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -7,7 +7,6 @@ import {
7
7
  type InstancedBufferAttribute,
8
8
  InstancedInterleavedBuffer,
9
9
  type Material,
10
- type Object3D,
11
10
  Sphere,
12
11
  Vector3,
13
12
  } from "three";
@@ -29,6 +28,7 @@ import {
29
28
  element,
30
29
  float,
31
30
  floor,
31
+ fract,
32
32
  instanceIndex,
33
33
  instancedBufferAttribute,
34
34
  instancedDynamicBufferAttribute,
@@ -37,29 +37,47 @@ import {
37
37
  mat3,
38
38
  mat4,
39
39
  max,
40
+ min,
40
41
  modelWorldMatrix,
41
42
  normalize,
42
43
  positionGeometry,
44
+ screenCoordinate,
43
45
  select,
46
+ sin,
44
47
  storage,
45
48
  texture,
46
49
  transformNormal,
47
50
  uniform,
51
+ varying,
48
52
  varyingProperty,
49
53
  vec2,
50
54
  vec3,
51
55
  vec4,
52
56
  } from "three/tsl";
57
+ import * as threeTsl from "three/tsl";
53
58
  import {
54
59
  EventNode,
55
60
  MeshBasicNodeMaterial,
56
61
  MeshPhysicalNodeMaterial,
57
62
  MeshStandardNodeMaterial,
58
63
  type Node,
64
+ type NodeBuilder,
59
65
  type NodeMaterial,
60
66
  } from "three/webgpu";
61
67
  import { IMPOSTOR_VIEW_GRID, type WorldImpostorAtlas } from "./world-impostor.js";
62
68
 
69
+ type InstanceMatrixFn = () => Node<"mat4">;
70
+ /**
71
+ * The owned engine's drawn-instance matrix, identity for a plain mesh. The engine compiles a node
72
+ * material once per variant, so a `Fn` cannot read `builder.object`; the web engine hands the node over
73
+ * in `__tnTsl`, the V8 player as a `three/tsl` name. Upstream three has neither and keeps the builder
74
+ * path below. Read through `Reflect` so a bundler does not resolve a name upstream does not export.
75
+ */
76
+ const engineInstanceMatrix = (Reflect.get(threeTsl, "instanceMatrix") ??
77
+ (Reflect.get(threeTsl, "__tnTsl") as Record<string, unknown> | undefined)?.instanceMatrix) as
78
+ | InstanceMatrixFn
79
+ | undefined;
80
+
63
81
  /** The surface reconstructs alpha-covered ray/depth crossings in the three neighboring views. */
64
82
  export const IMPOSTOR_SURFACE_PARALLAX = true;
65
83
 
@@ -129,6 +147,19 @@ const GEOMETRY_MAPS = [
129
147
  "transmissionMap",
130
148
  ] as const;
131
149
 
150
+ /**
151
+ * The node twins of those maps: a source's surface nodes describe its own mesh (a crown's ao and
152
+ * emissive sample its texture through `attribute("uv")`), which the quad does not have. Its scalar
153
+ * roughness and metalness stay; colour, normal, coverage and the cutout are the atlas's own nodes.
154
+ */
155
+ const SURFACE_NODES = [
156
+ "aoNode",
157
+ "emissiveNode",
158
+ "roughnessNode",
159
+ "metalnessNode",
160
+ "maskNode",
161
+ ] as const;
162
+
132
163
  /** One `mat4` node per CPU instance-matrix attribute, derived once and kept live with its source. */
133
164
  const INSTANCE_COLUMNS = new WeakMap<InstancedBufferAttribute, InstancedInterleavedBuffer>();
134
165
 
@@ -140,6 +171,13 @@ export interface IImpostorSurfaceOptions {
140
171
  readonly center: Vector3;
141
172
  /** The baked bounds' radius in asset-local space. */
142
173
  readonly radius: number;
174
+ /**
175
+ * The baked box's half size per asset-local axis (`impostorBounds`). With it the quad fits the
176
+ * box's projection instead of the bounding sphere: a spruce is a quarter of its sphere's square,
177
+ * and every fragment outside it ran the whole lit shader only to be discarded. Omitted, the quad
178
+ * is the sphere's square.
179
+ */
180
+ readonly halfExtents?: Vector3;
143
181
  /** The dominant source material; its class, roughness and metalness set the lit surface. */
144
182
  readonly source: Material;
145
183
  /** The source's own cutoff, or the scatter default. Kept positive for the shadow alpha caster. */
@@ -262,6 +300,8 @@ export function instanceSyncEvent(
262
300
  /**
263
301
  * The per-instance matrix as a `mat4` node, choosing the path by the attribute three installed.
264
302
  *
303
+ * Standard instancing already built the column nodes: reuse those exact nodes and its upload
304
+ * synchronization. Only a custom vertex path without them needs the fallback below.
265
305
  * A `StorageInstancedBufferAttribute` is read through `storage(...).element(instanceIndex)`, which
266
306
  * is the same seam three's own `Instance.js` uses and which includes the indirect draw's
267
307
  * `firstInstance`. A plain CPU `InstancedBufferAttribute` cannot require storage support, so it is
@@ -270,7 +310,41 @@ export function instanceSyncEvent(
270
310
  * derived buffer exactly as `Instance.js` does — a derived buffer nobody re-uploads draws a stale
271
311
  * pose. See {@link instanceSyncEvent}.
272
312
  */
273
- function instanceMatrixNode(attribute: InstancedBufferAttribute): Node<"mat4"> {
313
+ function instanceMatrixNode(
314
+ attribute: InstancedBufferAttribute,
315
+ builder: NodeBuilder,
316
+ ): Node<"mat4"> {
317
+ // Reuse Three's actual column nodes: a second interleaved buffer consumes four more locations.
318
+ // Three 0.187 (048e6bea2) builds each column as a `BufferAttributeNode` over an
319
+ // `InterleavedBufferAttribute` view of the matrix; older Three nodes held an
320
+ // `InstancedInterleavedBuffer` over the same array. Both carry that matrix, so both are reused.
321
+ // On a real renderer r187 binds the matrix per object instead (`referenceAttribute`), and only
322
+ // those columns follow the drawn object: a build is shared by every mesh of the program, and
323
+ // `SharedBatch#resize` swaps a mesh's buffer, so a column over the build-time array draws another
324
+ // mesh's or a 64-record buffer past its end, which invalidates the whole recorded bundle.
325
+ const columns = [...(Reflect.get(builder, "nodes") as Iterable<Node>)].filter((node) => {
326
+ if (Reflect.get(node, "isReferenceBufferAttributeNode") === true)
327
+ return Reflect.get(node, "referenceNode")?.property === "instanceMatrix";
328
+ const value = Reflect.get(node, "value");
329
+ if (value?.isInterleavedBufferAttribute === true) return value.data === attribute;
330
+ return (
331
+ value?.isInstancedInterleavedBuffer === true &&
332
+ value.array === attribute.array &&
333
+ Reflect.get(node, "bufferStride") === 16
334
+ );
335
+ });
336
+ if (columns.length === 4) {
337
+ const offsetOf = (node: Node): number => {
338
+ const value = Reflect.get(node, "value");
339
+ return (
340
+ (value?.isInterleavedBufferAttribute === true
341
+ ? value.offset
342
+ : Reflect.get(node, "bufferOffset")) ?? 0
343
+ );
344
+ };
345
+ columns.sort((a, b) => offsetOf(a) - offsetOf(b));
346
+ return mat4(...(columns as [Node<"vec4">, Node<"vec4">, Node<"vec4">, Node<"vec4">]));
347
+ }
274
348
  const count = Math.max(attribute.count, 1);
275
349
  if (
276
350
  (attribute as { isStorageInstancedBufferAttribute?: boolean })
@@ -286,7 +360,7 @@ function instanceMatrixNode(attribute: InstancedBufferAttribute): Node<"mat4"> {
286
360
  attribute.usage === DynamicDrawUsage
287
361
  ? instancedDynamicBufferAttribute
288
362
  : instancedBufferAttribute;
289
- const columns = [
363
+ const ownColumns = [
290
364
  bufferFn(interleaved, "vec4", 16, 0),
291
365
  bufferFn(interleaved, "vec4", 16, 4),
292
366
  bufferFn(interleaved, "vec4", 16, 8),
@@ -294,17 +368,16 @@ function instanceMatrixNode(attribute: InstancedBufferAttribute): Node<"mat4"> {
294
368
  ];
295
369
  instanceSyncEvent(attribute, interleaved).toStack();
296
370
  return mat4(
297
- columns[0] as Node<"vec4">,
298
- columns[1] as Node<"vec4">,
299
- columns[2] as Node<"vec4">,
300
- columns[3] as Node<"vec4">,
371
+ ownColumns[0] as Node<"vec4">,
372
+ ownColumns[1] as Node<"vec4">,
373
+ ownColumns[2] as Node<"vec4">,
374
+ ownColumns[3] as Node<"vec4">,
301
375
  ) as Node<"mat4">;
302
376
  }
303
377
 
304
378
  /** `cameraViewMatrix * modelWorldMatrix * instanceMatrix`: asset-space to view-space per instance. */
305
- function instanceViewMatrixNode(object: Object3D): Node<"mat4"> {
306
- const attribute = (object as { instanceMatrix?: InstancedBufferAttribute }).instanceMatrix;
307
- const instance = attribute === undefined ? identityMat4() : instanceMatrixNode(attribute);
379
+ function instanceViewMatrixNode(builder: NodeBuilder): Node<"mat4"> {
380
+ const instance = userInstanceMatrix(builder);
308
381
  return cameraViewMatrix.mul(modelWorldMatrix).mul(instance) as Node<"mat4">;
309
382
  }
310
383
 
@@ -318,9 +391,14 @@ function identityMat4(): Node<"mat4"> {
318
391
  ) as Node<"mat4">;
319
392
  }
320
393
 
321
- /** A node twin of a source material: its class and every value it authored, by reference. */
394
+ /** A node twin retaining the source material's authored values and shader nodes. */
322
395
  function cloneLitMaterial(source: Material): NodeMaterial {
323
- if (Reflect.get(source, "isNodeMaterial") === true) return (source as NodeMaterial).clone();
396
+ if (Reflect.get(source, "isNodeMaterial") === true) {
397
+ const twin = (source as NodeMaterial).clone();
398
+ // NodeMaterial.copy skips the inherited alphaTest accessor and its private backing value.
399
+ twin.alphaTest = source.alphaTest;
400
+ return twin;
401
+ }
324
402
  const nodeClass = NODE_CLASSES.get(source.type);
325
403
  if (nodeClass === undefined)
326
404
  throw new Error(`WorldImpostorSurface cannot convert material type '${source.type}'.`);
@@ -363,6 +441,7 @@ export class WorldImpostorSurface {
363
441
  throw new Error("WorldImpostorSurface requires a baked atlas.");
364
442
  const material = cloneLitMaterial(options.source);
365
443
  for (const key of GEOMETRY_MAPS) Reflect.set(material, key, null);
444
+ for (const key of SURFACE_NODES) Reflect.set(material, key, null);
366
445
  // Albedo and coverage are baked into the atlas; a vertex-colour attribute the quad does not
367
446
  // have, an opacity multiplier or an opacity node would apply the source's own colour and
368
447
  // coverage a second time on top of the baked one.
@@ -384,15 +463,16 @@ export class WorldImpostorSurface {
384
463
 
385
464
  const centerUniform = uniform(center);
386
465
  const radiusUniform = uniform(radius);
466
+ const halfUniform =
467
+ options.halfExtents === undefined ? undefined : uniform(options.halfExtents.clone());
387
468
  const cull = options.cull === true;
388
469
  const name = `WorldImpostorSurface${surfaceId}`;
389
470
  surfaceId += 1;
390
471
  const relVarying = varyingProperty("vec3", `${name}Rel`);
391
472
  const dirVarying = varyingProperty("vec3", `${name}Dir`);
392
473
 
393
- const positionNode = Fn((_inputs: unknown, builder: { readonly object: Object3D }) => {
394
- const object = builder.object;
395
- const instance = userInstanceMatrix(object);
474
+ const positionNode = Fn((_inputs: unknown, builder: NodeBuilder) => {
475
+ const instance = userInstanceMatrix(builder);
396
476
  const view = cameraViewMatrix.mul(modelWorldMatrix).mul(instance);
397
477
  const centerView = view.mul(vec4(centerUniform, 1)).xyz;
398
478
  // The authored cull contract in `world-gpu-scene.ts` `cullAndSelect` measures horizontal
@@ -409,7 +489,22 @@ export class WorldImpostorSurface {
409
489
  const dAsset = normalize(asMat3(view).inverse().mul(eyeView));
410
490
  const basis = frameBasisNode(dAsset);
411
491
  const corner = positionGeometry.xy;
412
- const rel = basis.right.mul(corner.x).add(basis.up.mul(corner.y)).mul(radiusUniform);
492
+ // `impostorQuadExtents` on the GPU: the box's footprint circle across, its projection on `up`
493
+ // down, each with the slack a neighbouring frame's blend reaches, never past the sphere.
494
+ const extent = halfUniform
495
+ ? vec2(
496
+ min(radiusUniform, length(halfUniform.xz).mul(QUAD_ACROSS_SLACK)),
497
+ min(
498
+ radiusUniform,
499
+ abs(basis.up.x)
500
+ .mul(halfUniform.x)
501
+ .add(abs(basis.up.y).mul(halfUniform.y))
502
+ .add(abs(basis.up.z).mul(halfUniform.z))
503
+ .mul(QUAD_UP_SLACK),
504
+ ),
505
+ )
506
+ : vec2(radiusUniform, radiusUniform);
507
+ const rel = basis.right.mul(corner.x.mul(extent.x)).add(basis.up.mul(corner.y.mul(extent.y)));
413
508
  // A main-pass horizontal-distance gate: when the instance centre is past the asset's own cull
414
509
  // the quad collapses to a point, which the rasteriser drops. The cull is a per-instance
415
510
  // attribute, so one surface serves every canonical asset over this atlas each at its own
@@ -449,10 +544,13 @@ export class WorldImpostorSurface {
449
544
  material.colorNode = vec4(fragment.albedo, fragment.coverage);
450
545
  material.alphaTestNode = fragment.threshold;
451
546
  material.maskShadowNode = fragment.coverage.greaterThan(fragment.threshold);
452
- material.normalNode = Fn((_inputs: unknown, builder: { readonly object: Object3D }) =>
453
- transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder.object)),
547
+ material.normalNode = Fn((_inputs: unknown, builder: NodeBuilder) =>
548
+ transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder)),
454
549
  )();
455
550
  material.positionNode = positionNode;
551
+ // A source's shadow position (a wind-swept crown casts its rest pose) would bypass the billboard
552
+ // above in the shadow draw: the quad must cast through its own positionNode.
553
+ material.castShadowPositionNode = null;
456
554
 
457
555
  const geometry = new BufferGeometry();
458
556
  geometry.setAttribute(
@@ -487,11 +585,38 @@ export class WorldImpostorSurface {
487
585
  let surfaceId = 0;
488
586
 
489
587
  /** The attribute node for the position pass; a plain `Mesh` falls back to the identity. */
490
- function userInstanceMatrix(object: Object3D): Node<"mat4"> {
588
+ function userInstanceMatrix(builder: NodeBuilder): Node<"mat4"> {
589
+ if (engineInstanceMatrix !== undefined) return engineInstanceMatrix();
590
+ const object = builder.object;
491
591
  const attribute = (object as { instanceMatrix?: InstancedBufferAttribute }).instanceMatrix;
492
- return attribute === undefined ? identityMat4() : instanceMatrixNode(attribute);
592
+ return attribute === undefined ? identityMat4() : instanceMatrixNode(attribute, builder);
493
593
  }
494
594
 
595
+ /**
596
+ * A random in [0, 1) that stays with its instance, as UE 5.8.3's PerInstanceRandom: hashed from the
597
+ * instance's world origin, never from its draw slot. WorldCells repacks instances on every refilter,
598
+ * main-pass cull and LOD switch, so `instanceIndex` names another tree from one frame to the next; a
599
+ * wind phase hashed from it re-rolled each crown about every 0.7 s of a walk and snapped its top by a
600
+ * median 0.37 m. Parts of one placement share its translation, so its bark and needles read one value.
601
+ *
602
+ * @situation a per-instance random number that stays with each streamed placement as WorldCells repacks
603
+ * @situation replace instanceIndex in a WorldCells part material, which WorldCells refuses
604
+ * @example const phase = instanceRandom().mul(6.2831);
605
+ */
606
+ export function instanceRandom(): Node<"float"> {
607
+ return Fn((_inputs: unknown, builder: NodeBuilder) => {
608
+ const origin = userInstanceMatrix(builder).mul(vec4(0, 0, 0, 1)).xyz;
609
+ // Quantised like `worldLodMaterial`'s origin, so float rounding in a rewritten matrix keeps the hash.
610
+ const snapped = floor(origin.mul(16).add(0.5)).div(16);
611
+ return fract(sin(dot(snapped.xz, vec2(12.9898, 78.233))).mul(43758.5453));
612
+ })() as Node<"float">;
613
+ }
614
+
615
+ /** Coarse ray-march steps across an impostor's depth; see `buildFragmentNodes`. */
616
+ export const IMPOSTOR_MARCH_STEPS = 32;
617
+ /** Bisection steps per crossing: 32 x 1024 places a hit as finely as 128 texel steps x 256 did. */
618
+ export const IMPOSTOR_BISECTION_STEPS = 10;
619
+
495
620
  interface IFragmentNodes {
496
621
  readonly albedo: Node<"vec3">;
497
622
  readonly coverage: Node<"float">;
@@ -545,10 +670,21 @@ function buildFragmentNodes(
545
670
 
546
671
  const colorMap = texture(atlas.color);
547
672
  const normalMap = texture(atlas.normal);
673
+ const steps = Math.min(atlas.pixels, IMPOSTOR_MARCH_STEPS);
548
674
  const uvs: Node<"vec2">[] = [];
549
675
  const colors: Node<"vec4">[] = [];
550
676
  const normals: Node<"vec4">[] = [];
551
- for (let index = 0; index < 3; index += 1) {
677
+ // One march, on the frame the blend weighs most; the other two read the same surface point from
678
+ // their own view. Three marches were the far band's cost (PRD-866 AC-3).
679
+ const [wa, wb, wc] = weights as [Node<"float">, Node<"float">, Node<"float">];
680
+ const pickA = wa.greaterThanEqual(wb).and(wa.greaterThanEqual(wc));
681
+ const pickB = wb.greaterThanEqual(wc);
682
+ const [xa, xb, xc] = cellX as [Node<"float">, Node<"float">, Node<"float">];
683
+ const [ya, yb, yc] = cellY as [Node<"float">, Node<"float">, Node<"float">];
684
+ cellX.push(select(pickA, xa, select(pickB, xb, xc)));
685
+ cellY.push(select(pickA, ya, select(pickB, yb, yc)));
686
+ let marched: Node<"vec4"> | undefined;
687
+ for (let index = 3; index < 4; index += 1) {
552
688
  const direction = octahedralViewNode(
553
689
  cellX[index] as Node<"float">,
554
690
  cellY[index] as Node<"float">,
@@ -562,23 +698,39 @@ function buildFragmentNodes(
562
698
  .mul(grid)
563
699
  .add(cellX[index] as Node<"float">)
564
700
  .toInt();
565
- // A crossing must remain covered throughout refinement; alpha holes and depth jumps
566
- // cannot create an interior surface. One march step per baked texel, eight refinements.
701
+ // Positive baked coverage owns ray/depth geometry; the authored cutoff is applied once by the
702
+ // final mip-aware fragment threshold. Alpha holes and depth jumps cannot create an interior
703
+ // surface. A march step every four baked texels at most, ten refinements: one step per texel
704
+ // was ~770 atlas reads a fragment over three frames, 26 ms of a 42 ms walking frame with 383 fir
705
+ // impostors on screen, and two more bisection steps keep each crossing as precise as before.
706
+ // March on the mip the fragment's own footprint resolves: mip 0 under a far tree a few pixels
707
+ // wide reads scattered texels on every step and thrashes the texture cache (24 ms of a 48 ms
708
+ // walking frame on 53k far trees). Depth is coverage-premultiplied, so a mip keeps its meaning.
709
+ // Taken here, in uniform control flow, because derivatives inside the loop are undefined.
710
+ const footUv = vec2(dot(relVarying, basis.right), dot(relVarying, basis.up).negate())
711
+ .div(radiusUniform)
712
+ .mul(0.5)
713
+ .add(0.5);
714
+ const marchLevel = max(
715
+ log2(max(length(dFdx(footUv).mul(atlas.pixels)), length(dFdy(footUv).mul(atlas.pixels)))),
716
+ float(0),
717
+ ).toVar();
567
718
  const hit = Fn(() => {
568
719
  const found = float(0).toVar();
569
720
  const hitUv = vec2(2).toVar();
721
+ const hitT = float(0).toVar();
570
722
  const previousGap = float(0).toVar();
571
723
  const previousAlpha = float(0).toVar();
572
724
  const previousT = radiusUniform.toVar();
573
- Loop({ start: 0, end: atlas.pixels + 1, type: "int" }, ({ i }) => {
574
- const t = float(1).sub(float(i).div(atlas.pixels).mul(2)).mul(radiusUniform);
725
+ Loop({ start: 0, end: steps + 1, type: "int" }, ({ i }) => {
726
+ const t = float(1).sub(float(i).div(steps).mul(2)).mul(radiusUniform);
575
727
  const point = relVarying.add(ray.mul(t));
576
728
  const sampleUv = vec2(dot(point, basis.right), dot(point, basis.up).negate())
577
729
  .div(radiusUniform)
578
730
  .mul(0.5)
579
731
  .add(0.5);
580
- const c = colorMap.depth(layer).sample(sampleUv).level(float(0)).toVar();
581
- const n = normalMap.depth(layer).sample(sampleUv).level(float(0)).toVar();
732
+ const c = colorMap.depth(layer).sample(sampleUv).level(marchLevel).toVar();
733
+ const n = normalMap.depth(layer).sample(sampleUv).level(marchLevel).toVar();
582
734
  const depth = float(1)
583
735
  .sub(
584
736
  float(1)
@@ -591,23 +743,23 @@ function buildFragmentNodes(
591
743
  If(
592
744
  found
593
745
  .equal(0)
594
- .and(previousAlpha.greaterThan(cutoff))
595
- .and(c.a.greaterThan(cutoff))
746
+ .and(previousAlpha.greaterThan(0))
747
+ .and(c.a.greaterThan(0))
596
748
  .and(previousGap.greaterThan(0))
597
749
  .and(gap.lessThanEqual(0)),
598
750
  () => {
599
751
  const front = previousT.toVar();
600
752
  const back = t.toVar();
601
753
  const valid = float(1).toVar();
602
- Loop({ start: 0, end: 8, type: "int" }, () => {
754
+ Loop({ start: 0, end: IMPOSTOR_BISECTION_STEPS, type: "int" }, () => {
603
755
  const mid = front.add(back).mul(0.5).toVar();
604
756
  const p = relVarying.add(ray.mul(mid));
605
757
  const u = vec2(dot(p, basis.right), dot(p, basis.up).negate())
606
758
  .div(radiusUniform)
607
759
  .mul(0.5)
608
760
  .add(0.5);
609
- const mc = colorMap.depth(layer).sample(u).level(float(0)).toVar();
610
- const mn = normalMap.depth(layer).sample(u).level(float(0)).toVar();
761
+ const mc = colorMap.depth(layer).sample(u).level(marchLevel).toVar();
762
+ const mn = normalMap.depth(layer).sample(u).level(marchLevel).toVar();
611
763
  const md = float(1)
612
764
  .sub(
613
765
  float(1)
@@ -617,7 +769,7 @@ function buildFragmentNodes(
617
769
  )
618
770
  .mul(radiusUniform);
619
771
  const mg = dot(p, direction).sub(md);
620
- If(mc.a.lessThanEqual(cutoff), () => {
772
+ If(mc.a.lessThanEqual(0), () => {
621
773
  valid.assign(0);
622
774
  });
623
775
  If(mg.greaterThan(0), () => {
@@ -631,8 +783,8 @@ function buildFragmentNodes(
631
783
  .div(radiusUniform)
632
784
  .mul(0.5)
633
785
  .add(0.5);
634
- const hc = colorMap.depth(layer).sample(u).level(float(0)).toVar();
635
- const hn = normalMap.depth(layer).sample(u).level(float(0)).toVar();
786
+ const hc = colorMap.depth(layer).sample(u).level(marchLevel).toVar();
787
+ const hn = normalMap.depth(layer).sample(u).level(marchLevel).toVar();
636
788
  const hd = float(1)
637
789
  .sub(
638
790
  float(1)
@@ -644,7 +796,7 @@ function buildFragmentNodes(
644
796
  If(
645
797
  valid
646
798
  .equal(1)
647
- .and(hc.a.greaterThan(cutoff))
799
+ .and(hc.a.greaterThan(0))
648
800
  .and(
649
801
  abs(dot(p, direction).sub(hd)).lessThanEqual(
650
802
  radiusUniform.mul(2 / 255).div(max(hc.a, float(0.001))),
@@ -652,6 +804,7 @@ function buildFragmentNodes(
652
804
  ),
653
805
  () => {
654
806
  hitUv.assign(u);
807
+ hitT.assign(front.add(back).mul(0.5));
655
808
  found.assign(1);
656
809
  },
657
810
  );
@@ -665,11 +818,29 @@ function buildFragmentNodes(
665
818
  Break();
666
819
  });
667
820
  });
668
- return vec3(hitUv, found);
821
+ return vec4(hitUv, found, hitT);
669
822
  })();
670
- uvs.push(hit.xy);
671
- colors.push(colorMap.depth(layer).sample(hit.xy).mul(hit.z).toVar() as Node<"vec4">);
672
- normals.push(normalMap.depth(layer).sample(hit.xy).mul(hit.z).toVar() as Node<"vec4">);
823
+ marched = hit;
824
+ }
825
+
826
+ const surface = marched as Node<"vec4">;
827
+ const rayOut = normalize(select(orthographicNode(), dirVarying, dirVarying.sub(relVarying)));
828
+ const hitPoint = relVarying.add(rayOut.mul(surface.w));
829
+ for (let index = 0; index < 3; index += 1) {
830
+ const basis = frameBasisNode(
831
+ octahedralViewNode(cellX[index] as Node<"float">, cellY[index] as Node<"float">, grid),
832
+ );
833
+ const layer = (cellY[index] as Node<"float">)
834
+ .mul(grid)
835
+ .add(cellX[index] as Node<"float">)
836
+ .toInt();
837
+ const uv = vec2(dot(hitPoint, basis.right), dot(hitPoint, basis.up).negate())
838
+ .div(radiusUniform)
839
+ .mul(0.5)
840
+ .add(0.5);
841
+ uvs.push(uv);
842
+ colors.push(colorMap.depth(layer).sample(uv).mul(surface.z).toVar() as Node<"vec4">);
843
+ normals.push(normalMap.depth(layer).sample(uv).mul(surface.z).toVar() as Node<"vec4">);
673
844
  }
674
845
 
675
846
  const [w0, w1, w2] = weights as [Node<"float">, Node<"float">, Node<"float">];
@@ -688,6 +859,37 @@ function buildFragmentNodes(
688
859
  };
689
860
  }
690
861
 
862
+ /**
863
+ * Slack on the fitted quad. Across: a frame blended in from a neighbouring azimuth reprojects the
864
+ * footprint up to `1 / cos(45 deg)` wider, but its weight there is small, so a quarter covers it.
865
+ * Down: elevation neighbours shift the projection a little. Both stay inside the sphere's square.
866
+ */
867
+ const QUAD_ACROSS_SLACK = 1.25;
868
+ const QUAD_UP_SLACK = 1.1;
869
+
870
+ /**
871
+ * The quad's half width and half height for a view `direction` (asset space, toward the eye), as
872
+ * the surface's vertex shader computes them: the box footprint's circle across (any azimuth), the
873
+ * box's projection on the frame's `up` down, each with its slack and capped by the sphere radius.
874
+ */
875
+ export function impostorQuadExtents(
876
+ direction: Vector3,
877
+ halfExtents: Vector3,
878
+ radius: number,
879
+ ): { readonly across: number; readonly up: number } {
880
+ const { up } = impostorFrameBasis(direction);
881
+ return {
882
+ across: Math.min(radius, Math.hypot(halfExtents.x, halfExtents.z) * QUAD_ACROSS_SLACK),
883
+ up: Math.min(
884
+ radius,
885
+ (Math.abs(up.x) * halfExtents.x +
886
+ Math.abs(up.y) * halfExtents.y +
887
+ Math.abs(up.z) * halfExtents.z) *
888
+ QUAD_UP_SLACK,
889
+ ),
890
+ };
891
+ }
892
+
691
893
  /**
692
894
  * The frame basis the baker's orthographic camera actually built for `direction`: the three
693
895
  * endpoints of a view's own `lookAt`, so the sampler's projection and the bake share one basis.
@@ -720,3 +922,163 @@ export function impostorFrameUv(
720
922
  v: 0.5 - (relative.dot(basis.up) / radius) * 0.5,
721
923
  };
722
924
  }
925
+
926
+ /**
927
+ * How long a published level change fades, in seconds: UE 5.8.3 `lod.TemporalLag`
928
+ * (Engine/Source/Runtime/Engine/Private/SceneManagement.cpp:28-32).
929
+ */
930
+ export const LOD_TEMPORAL_LAG = 0.5;
931
+
932
+ /**
933
+ * UE 5.8.3's temporal LOD state (Engine/Source/Runtime/Engine/Private/SceneManagement.cpp:113-140):
934
+ * two lagged view origins and the blend between them. LOD is chosen at both and cross-faded by
935
+ * `alpha`, so a placement crossing a gate fades over one `lag` window and none stays mid-fade while
936
+ * the viewer stands still.
937
+ */
938
+ export interface ITemporalLod {
939
+ readonly from: Vector3;
940
+ readonly to: Vector3;
941
+ fromTime: number;
942
+ toTime: number;
943
+ alpha: number;
944
+ }
945
+
946
+ /** Advance {@link ITemporalLod} to `now` seconds with the view at `eye`, as UE's UpdateTemporalLODTransition. */
947
+ export function advanceTemporalLod(
948
+ state: ITemporalLod,
949
+ eye: Vector3,
950
+ now: number,
951
+ lag = LOD_TEMPORAL_LAG,
952
+ ): void {
953
+ if (!Number.isFinite(state.toTime) || now < state.toTime) {
954
+ state.from.copy(eye);
955
+ state.to.copy(eye);
956
+ state.fromTime = now;
957
+ state.toTime = now;
958
+ } else if (state.toTime < now - lag) {
959
+ if (state.fromTime < state.toTime) {
960
+ state.from.copy(state.to);
961
+ state.fromTime = state.toTime;
962
+ }
963
+ state.to.copy(eye);
964
+ state.toTime = now;
965
+ }
966
+ const window = state.toTime - state.fromTime;
967
+ state.alpha = window > 0 ? Math.min(1, Math.max(0, (now - lag - state.fromTime) / window)) : 1;
968
+ }
969
+
970
+ /** Complementary LOD masks over the caller's distance bands, shared by colour and shadow passes. */
971
+ export function worldLodMaterial(
972
+ source: Material,
973
+ local: import("three").Matrix4,
974
+ distances: readonly number[],
975
+ level: number,
976
+ width: number,
977
+ eye: Node<"vec3">,
978
+ distanceBias: Node<"float">,
979
+ spatial: boolean,
980
+ publishedRanges = false,
981
+ clock?: Node<"float">,
982
+ temporal?: {
983
+ readonly from: Node<"vec3">;
984
+ readonly to: Node<"vec3">;
985
+ readonly alpha: Node<"float">;
986
+ },
987
+ shadowFloor = 0,
988
+ ): NodeMaterial {
989
+ const material = cloneLitMaterial(source);
990
+ const inverse = uniform(local.clone().invert());
991
+ const root = Fn(
992
+ (_inputs: unknown, builder: NodeBuilder) =>
993
+ userInstanceMatrix(builder)
994
+ .mul(inverse)
995
+ .mul(vec4(0, 0, 0, 1)).xyz,
996
+ )();
997
+ // Quantise recovered roots so part-local float rounding cannot change the instance hash.
998
+ const origin = varying(floor(root.mul(16).add(0.5)).div(16));
999
+ const distanceTo = (at: Node<"vec3">) =>
1000
+ (spatial ? length(origin.sub(at)) : length(origin.xz.sub(at.xz))).mul(distanceBias);
1001
+ const distance = distanceTo(eye);
1002
+ const random = fract(sin(dot(origin.xz, vec2(12.9898, 78.233))).mul(43758.5453));
1003
+ const noise = fract(sin(dot(floor(screenCoordinate.xy), vec2(12.9898, 78.233))).mul(43758.5453));
1004
+ // CPU-admitted batches publish the levels their instance currently has beside its matrix. During
1005
+ // a queued refilter, an old level outside that set remains whole until the replacement is swapped.
1006
+ // LOD indices are categorical; interpolating 2 below 2 can clip an otherwise whole tree.
1007
+ // `.zw` is the fade a swap stamped: the level the record was whole at (-1: none) and when.
1008
+ const published = publishedRanges
1009
+ ? varying(attribute("tnPublishedLodRange", "vec4") as Node<"vec4">).setInterpolation("flat")
1010
+ : undefined;
1011
+ // The level and the gate distances are uniforms, not constants, so every level of an asset (and
1012
+ // every asset with as many gates) is one shader program and one pipeline, as an Unreal material
1013
+ // instance shares its parent's shader. Baked, each level was a first-time program that compiled in
1014
+ // the frame it first came into view: 14 ms of CPU and a 50 ms frame in a 360-degree turn.
1015
+ const lod = uniform(level);
1016
+ const gates = distances.map((at) => uniform(at));
1017
+ const always = float(1).greaterThan(0);
1018
+ // `mixAt(gate)` is how far past the gate this placement is, 0..1; pixels with noise below it draw
1019
+ // the coarser level.
1020
+ const levelMask = (
1021
+ mixAt: (at: Node<"float">, span: Node<"float">) => Node<"float">,
1022
+ first = 1,
1023
+ ) => {
1024
+ let mask = always;
1025
+ for (let gate = first; gate < distances.length; gate++) {
1026
+ const at = gates[gate] as Node<"float">;
1027
+ let span = at.mul(width).min(at.sub(gates[gate - 1] as Node<"float">).mul(width));
1028
+ if (gate + 1 < distances.length)
1029
+ span = span.min((gates[gate + 1] as Node<"float">).sub(at).mul(width));
1030
+ const mix = mixAt(at, span);
1031
+ // `gate === level` fades this level in past the gate; `gate === level + 1` fades it out.
1032
+ const fadeIn =
1033
+ published === undefined
1034
+ ? noise.lessThan(mix)
1035
+ : select(published.x.lessThan(lod), noise.lessThan(mix), always);
1036
+ const fadeOut =
1037
+ published === undefined
1038
+ ? noise.greaterThanEqual(mix)
1039
+ : select(published.y.greaterThan(lod), noise.greaterThanEqual(mix), always);
1040
+ mask = mask.and(lod.notEqual(gate).or(fadeIn)).and(lod.notEqual(gate - 1).or(fadeOut));
1041
+ }
1042
+ return mask;
1043
+ };
1044
+ const rampAt = (at: Node<"float">, span: Node<"float">) =>
1045
+ distance.sub(at).div(span).add(0.5).add(random.sub(0.5).mul(0.5)).clamp(0, 1);
1046
+ const mask = levelMask(rampAt);
1047
+ // `shadowFloor`: finer placements cast in the floor level's shape (`castLevelOf`), so the floor's
1048
+ // shadow covers every distance under its outer gate and a finer level casts nothing.
1049
+ const shadow =
1050
+ shadowFloor > 0
1051
+ ? lod.greaterThanEqual(shadowFloor).and(levelMask(rampAt, shadowFloor + 1))
1052
+ : mask;
1053
+ // Temporal: the gate is hard in space and the colour pass blends the level seen from the older
1054
+ // eye into the level seen from the newer one, as UE's instanced foliage does.
1055
+ const past = (eyeAt: Node<"vec3">, at: Node<"float">) =>
1056
+ select(distanceTo(eyeAt).greaterThan(at), float(1), float(0));
1057
+ const crossFaded =
1058
+ temporal === undefined
1059
+ ? mask
1060
+ : levelMask((at) =>
1061
+ past(temporal.from, at)
1062
+ .mul(float(1).sub(temporal.alpha))
1063
+ .add(past(temporal.to, at).mul(temporal.alpha)),
1064
+ );
1065
+ // A refilter that lands late turns a whole tree into a dithered pair in one frame. The colour pass
1066
+ // keeps the old whole level on a shrinking share of pixels for `LOD_TEMPORAL_LAG`, as UE fades
1067
+ // every LOD change in time; the shares stay complementary, so no pixel holds both or neither.
1068
+ // Shadows take the new answer at once: a cached shadow page must not keep a frame of the fade.
1069
+ let colour = crossFaded;
1070
+ if (published !== undefined && clock !== undefined) {
1071
+ const progress = clock.sub(published.w).div(LOD_TEMPORAL_LAG);
1072
+ const blend = fract(
1073
+ sin(dot(floor(screenCoordinate.xy), vec2(39.3468, 11.1353))).mul(24634.6345),
1074
+ );
1075
+ const holdOld = published.z.greaterThanEqual(0).and(blend.greaterThanEqual(progress));
1076
+ colour = select(holdOld, published.z.sub(lod).abs().lessThan(0.5), crossFaded);
1077
+ }
1078
+ material.maskNode = material.maskNode ? (material.maskNode as Node<"bool">).and(colour) : colour;
1079
+ material.maskShadowNode = material.maskShadowNode
1080
+ ? (material.maskShadowNode as Node<"bool">).and(shadow)
1081
+ : shadow;
1082
+ if (publishedRanges) material.userData.tnPublishedLodRange = true;
1083
+ return material;
1084
+ }