@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
@@ -8,8 +8,10 @@ import {
8
8
  Sphere,
9
9
  Vector3,
10
10
  } from "three";
11
+ import { GEOMETRY_ASSET_KEY } from "./geometry-capture.js";
11
12
  import type { InstancedBatch } from "./instanced-batch.js";
12
- import { currentWriteEpoch, pooledCapacity, pooledMesh } from "./render/mesh-pool.js";
13
+ import { pooledCapacity, pooledMesh } from "./render/mesh-pool.js";
14
+ import { type IRecordWriter, batchRecords } from "./world-cell-records.js";
13
15
 
14
16
  /**
15
17
  * Records a retired batch's instance buffer is shrunk to; see `SharedBatch.park`.
@@ -73,25 +75,12 @@ type ISquareSizes = Map<string, number>;
73
75
  * main batch is the only bound on it. Module-level like the upload epoch, because there is one world
74
76
  * drawing at a time.
75
77
  */
76
- let regroupScratch = new Float32Array(0);
77
- let lodRangeScratch = new Float32Array(0);
78
-
79
78
  const LOD_RANGE_ATTRIBUTE = "tnPublishedLodRange";
79
+ /** The local box of a part with no readable bounds: the record box is then its origins' extent. */
80
+ const ZERO = new Vector3();
80
81
  /** Floats per record in it: the levels published (min, max), the level a fade starts from (-1: none) and when. */
81
82
  export const LOD_RANGE_STRIDE = 4;
82
83
 
83
- function lodScratchFor(floats: number): Float32Array {
84
- if (lodRangeScratch.length < floats) lodRangeScratch = new Float32Array(floats * 2);
85
- return lodRangeScratch;
86
- }
87
-
88
- /** A scratch with room for `floats`, kept between regroups so a walk allocates it once. */
89
- function scratchFor(floats: number): Float32Array {
90
- if (regroupScratch.length < floats) regroupScratch = new Float32Array(floats * 2);
91
- return regroupScratch;
92
- }
93
-
94
- /** Records a square's blocks hold, which is its share of the batch. */
95
84
  function sizeOf(square: { blocks: Array<[number, number, number, string]> }): number {
96
85
  let size = 0;
97
86
  for (const block of square.blocks) size += block[2];
@@ -104,7 +93,7 @@ export function sameSquares(next: Set<string>, was: Set<string> | undefined): bo
104
93
  return true;
105
94
  }
106
95
 
107
- export class SharedBatch {
96
+ export class SharedBatch implements IRecordWriter {
108
97
  mesh: ICasterScaleMesh;
109
98
  #sourceGeometry: BufferGeometry;
110
99
  readonly #rangeLevel: number;
@@ -228,17 +217,19 @@ export class SharedBatch {
228
217
  readonly #boxes = new Map<number, Box3>();
229
218
  /** Block handle -> the largest instance scale in it; the union is published on the mesh. */
230
219
  readonly #scales = new Map<number, number>();
231
- /** Carried out of the last `#boxOf` pass, which already reads every record's basis. */
232
- #maxScale = 0;
233
220
  #localGeometry: BufferGeometry | undefined;
234
221
  readonly #localCenter = new Vector3();
235
222
  readonly #localHalf = new Vector3();
236
223
  readonly #union = new Box3();
237
224
  readonly #point = new Vector3();
238
- /** This batch's own pending upload span, and the `update` it was opened in. See `#touched`. */
225
+ /** This batch's pending upload span, in floats of the instance buffer, until the next flush. See `#touched`. */
239
226
  #pendingLow = 0;
240
227
  #pendingHigh = 0;
241
- #pendingEpoch = -1;
228
+ /** The buffers that span belongs to: the ones this batch wrote last, whatever a later dress swaps in. */
229
+ #pendingMatrix: InstancedBufferAttribute | undefined;
230
+ #pendingRanges: InstancedBufferAttribute | undefined;
231
+ /** Block handle -> where its box starts in the flush's answer; see {@link settleRecords}. */
232
+ readonly #pendingBoxes = new Map<number, number>();
242
233
 
243
234
  constructor(
244
235
  geometry: BufferGeometry,
@@ -284,6 +275,9 @@ export class SharedBatch {
284
275
  view.boundingSphere = source.boundingSphere;
285
276
  view.setDrawRange(source.drawRange.start, source.drawRange.count);
286
277
  view.userData.tnPublishedLodRangeView = true;
278
+ // The view is drawn in the source's place, so it keeps the loader's provenance stamp.
279
+ const stamp = source.userData[GEOMETRY_ASSET_KEY];
280
+ if (stamp !== undefined) view.userData[GEOMETRY_ASSET_KEY] = stamp;
287
281
  const ranges = new InstancedBufferAttribute(
288
282
  new Float32Array(capacity * LOD_RANGE_STRIDE),
289
283
  LOD_RANGE_STRIDE,
@@ -347,8 +341,8 @@ export class SharedBatch {
347
341
  mesh.frustumCulled = true;
348
342
  mesh.castShadow = false;
349
343
  mesh.receiveShadow = false;
350
- (mesh.instanceMatrix.array as Float32Array).fill(0);
351
- mesh.instanceMatrix.needsUpdate = true;
344
+ batchRecords.fill(mesh.instanceMatrix, 0, records * 16);
345
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
352
346
  // A pooled mesh arrives carrying the last user's scale; nothing lives here yet.
353
347
  mesh.casterInstanceScale = 0;
354
348
  // Nor the last user's bundle membership: a mesh is only bundled while `WorldCells#bundleIn` says
@@ -388,13 +382,8 @@ export class SharedBatch {
388
382
  this.#setGeometry(this.#geometryFor(this.mesh.instanceMatrix.count));
389
383
  const ranges = this.#lodRangeAttribute();
390
384
  if (ranges === undefined) return;
391
- const values = ranges.array as Float32Array;
392
- for (let at = 0; at < values.length; at += LOD_RANGE_STRIDE) {
393
- values[at] = this.#rangeLevel;
394
- values[at + 1] = this.#rangeLevel;
395
- values[at + 2] = -1;
396
- }
397
- ranges.needsUpdate = true;
385
+ batchRecords.lanes(ranges, LOD_RANGE_STRIDE, [this.#rangeLevel, this.#rangeLevel, -1]);
386
+ batchRecords.upload(ranges, 0, 0);
398
387
  }
399
388
 
400
389
  /** The capacity this batch had when it was parked; see {@link park}. */
@@ -464,76 +453,28 @@ export class SharedBatch {
464
453
  }
465
454
 
466
455
  /**
467
- * The AABB of records `[from, from + count)` of the instance buffer, read from the bytes just
468
- * written rather than from the batch that wrote them, so it is the same numbers the GPU gets. The
469
- * half-extents are `|basis| * half`, which is the box a rotated or stretched instance of the part
470
- * actually covers — a translate-only box would let a scaled trunk through the shadow cull.
456
+ * The part's local box centre and half size, read once per geometry: the input of the record box
457
+ * the engine measures from the bytes as written (see {@link write}). False when the geometry has
458
+ * no readable box, and the package extent stands in for the block's records.
471
459
  */
472
- #boxOf(from: number, count: number): Box3 {
473
- const array = this.mesh.instanceMatrix.array as Float32Array;
460
+ #localBox(): boolean {
474
461
  const geometry = this.mesh.geometry;
475
462
  if (this.#localGeometry !== geometry) {
476
463
  this.#localGeometry = geometry;
477
464
  if (geometry?.boundingBox === null || geometry?.boundingBox === undefined)
478
465
  geometry?.computeBoundingBox?.();
479
466
  const local = geometry?.boundingBox;
480
- // No readable local box means no readable instances either; the package extent is the answer
481
- // that cannot be wrong, and it is what these meshes carried before the blocks were sized.
482
- if (local === undefined || local === null || local.isEmpty()) return this.#bounds;
483
- this.#localCenter.copy(local.getCenter(this.#point));
484
- this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
485
- }
486
- const cx = this.#localCenter.x;
487
- const cy = this.#localCenter.y;
488
- const cz = this.#localCenter.z;
489
- const hx = this.#localHalf.x;
490
- const hy = this.#localHalf.y;
491
- const hz = this.#localHalf.z;
492
- const out = new Box3();
493
- let minX = Number.POSITIVE_INFINITY;
494
- let minY = Number.POSITIVE_INFINITY;
495
- let minZ = Number.POSITIVE_INFINITY;
496
- let maxX = Number.NEGATIVE_INFINITY;
497
- let maxY = Number.NEGATIVE_INFINITY;
498
- let maxZ = Number.NEGATIVE_INFINITY;
499
- let scale = 0;
500
- for (let index = from; index < from + count; index += 1) {
501
- const at = index * 16;
502
- const m0 = array[at] as number;
503
- const m1 = array[at + 1] as number;
504
- const m2 = array[at + 2] as number;
505
- const m4 = array[at + 4] as number;
506
- const m5 = array[at + 5] as number;
507
- const m6 = array[at + 6] as number;
508
- const m8 = array[at + 8] as number;
509
- const m9 = array[at + 9] as number;
510
- const m10 = array[at + 10] as number;
511
- const px = m0 * cx + m4 * cy + m8 * cz + (array[at + 12] as number);
512
- const py = m1 * cx + m5 * cy + m9 * cz + (array[at + 13] as number);
513
- const pz = m2 * cx + m6 * cy + m10 * cz + (array[at + 14] as number);
514
- const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
515
- const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
516
- const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
517
- if (px - ex < minX) minX = px - ex;
518
- if (py - ey < minY) minY = py - ey;
519
- if (pz - ez < minZ) minZ = pz - ez;
520
- if (px + ex > maxX) maxX = px + ex;
521
- if (py + ey > maxY) maxY = py + ey;
522
- if (pz + ez > maxZ) maxZ = pz + ez;
523
- // The largest column of the instance basis: the scale a fern or a trunk is drawn at.
524
- const basis = Math.max(
525
- Math.hypot(m0, m1, m2),
526
- Math.hypot(m4, m5, m6),
527
- Math.hypot(m8, m9, m10),
528
- );
529
- if (basis > scale) scale = basis;
467
+ this.#localReadable = !(local === undefined || local === null || local.isEmpty());
468
+ if (local !== undefined && local !== null && this.#localReadable) {
469
+ this.#localCenter.copy(local.getCenter(this.#point));
470
+ this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
471
+ }
530
472
  }
531
- this.#maxScale = scale;
532
- out.min.set(minX, minY, minZ);
533
- out.max.set(maxX, maxY, maxZ);
534
- return out;
473
+ return this.#localReadable;
535
474
  }
536
475
 
476
+ #localReadable = false;
477
+
537
478
  /** A handle for `count` free records, or `undefined` when the buffer has none and must grow. */
538
479
  allocate(count: number, cluster?: string): number | undefined {
539
480
  const at = this.#take(count);
@@ -575,16 +516,15 @@ export class SharedBatch {
575
516
  old.name,
576
517
  this.#bounds,
577
518
  );
578
- (mesh.instanceMatrix.array as Float32Array).set(old.instanceMatrix.array as Float32Array);
519
+ const records = old.instanceMatrix.count;
520
+ batchRecords.copy(mesh.instanceMatrix, old.instanceMatrix, records * 16);
579
521
  const oldRanges = old.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
580
522
  const nextRanges = mesh.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
581
523
  if (
582
524
  oldRanges instanceof InstancedBufferAttribute &&
583
525
  nextRanges instanceof InstancedBufferAttribute
584
- ) {
585
- (nextRanges.array as Float32Array).set(oldRanges.array as Float32Array);
586
- nextRanges.needsUpdate = true;
587
- }
526
+ )
527
+ batchRecords.copy(nextRanges, oldRanges, records * LOD_RANGE_STRIDE);
588
528
  mesh.castShadow = old.castShadow;
589
529
  mesh.receiveShadow = old.receiveShadow;
590
530
  this.mesh = mesh;
@@ -597,7 +537,6 @@ export class SharedBatch {
597
537
  // of the old array reached the GPU. A narrow range here would leave the new buffer's first
598
538
  // records as the zeros it was created with.
599
539
  this.#touched(0, this.#drawn);
600
- this.#rebound();
601
540
  return old;
602
541
  }
603
542
 
@@ -637,39 +576,59 @@ export class SharedBatch {
637
576
  this.#publish(this.#drawn);
638
577
  return;
639
578
  }
640
- const array = this.mesh.instanceMatrix.array as Float32Array;
641
- const written = batch.writeMatrices(array, start);
642
- const ranges = this.#lodRangeAttribute();
643
- if (ranges !== undefined) {
644
- const values = ranges.array as Float32Array;
645
- if (lodRanges !== undefined)
646
- values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), start * LOD_RANGE_STRIDE);
647
- else
648
- for (let index = 0; index < written; index += 1) {
649
- const at = (start + index) * LOD_RANGE_STRIDE;
650
- values[at] = this.#rangeLevel;
651
- values[at + 1] = this.#rangeLevel;
652
- values[at + 2] = -1;
653
- values[at + 3] = 0;
654
- }
655
- values.fill(0, (start + written) * LOD_RANGE_STRIDE, (start + reserved) * LOD_RANGE_STRIDE);
656
- ranges.needsUpdate = true;
657
- }
658
- array.fill(0, (start + written) * 16, (start + reserved) * 16);
579
+ // The records go to the engine as ops (see `world-cell-records.ts`): the matrices are written
580
+ // straight into the frame's payload, and this batch never holds the buffer's bytes.
581
+ const matrix = this.mesh.instanceMatrix;
582
+ const payloadAt = batchRecords.reserve(batch.count * 16);
583
+ const written = batch.writeMatrices(batchRecords.payload, payloadAt / 16);
584
+ batchRecords.write(matrix, start * 16, written * 16, payloadAt);
585
+ this.#writeRanges(start, written, reserved, lodRanges);
586
+ batchRecords.fill(matrix, (start + written) * 16, (reserved - written) * 16);
659
587
  if (written < reserved) this.#hole(start + written, start + reserved);
660
588
  this.#size.set(segment, written);
661
- // The block's extent, read from the records where they are now, because `#compact` is about to
662
- // move them. The box is keyed by handle, so the move cannot falsify it.
589
+ // The block's extent, measured by the engine from the records where they are now, because
590
+ // `#compact` is about to move them. The box is keyed by handle, so the move cannot falsify it;
591
+ // it lands in `#boxes` when the flush answers (`settleRecords`).
663
592
  if (written > 0) {
664
- this.#boxes.set(segment, this.#boxOf(start, written));
665
- this.#scales.set(segment, this.#maxScale);
593
+ const readable = this.#localBox();
594
+ const index = batchRecords.box(
595
+ matrix,
596
+ start,
597
+ written,
598
+ readable ? this.#localCenter : ZERO,
599
+ readable ? this.#localHalf : ZERO,
600
+ );
601
+ this.#pendingBoxes.set(segment, readable ? index : -1 - index);
666
602
  } else {
667
603
  this.#boxes.delete(segment);
668
604
  this.#scales.delete(segment);
605
+ this.#pendingBoxes.delete(segment);
669
606
  }
670
607
  this.#settle();
671
608
  this.#touched(start, written);
672
- this.#rebound();
609
+ }
610
+
611
+ /** The block's LOD-range column: the published ranges, or each record whole at this batch's level. */
612
+ #writeRanges(start: number, written: number, reserved: number, lodRanges?: Float32Array): void {
613
+ const ranges = this.#lodRangeAttribute();
614
+ if (ranges === undefined) return;
615
+ const at = batchRecords.reserve(written * LOD_RANGE_STRIDE);
616
+ const values = batchRecords.payload;
617
+ if (lodRanges !== undefined) values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), at);
618
+ else
619
+ for (let index = 0; index < written; index += 1) {
620
+ const record = at + index * LOD_RANGE_STRIDE;
621
+ values[record] = this.#rangeLevel;
622
+ values[record + 1] = this.#rangeLevel;
623
+ values[record + 2] = -1;
624
+ values[record + 3] = 0;
625
+ }
626
+ batchRecords.write(ranges, start * LOD_RANGE_STRIDE, written * LOD_RANGE_STRIDE, at);
627
+ batchRecords.fill(
628
+ ranges,
629
+ (start + written) * LOD_RANGE_STRIDE,
630
+ (reserved - written) * LOD_RANGE_STRIDE,
631
+ );
673
632
  }
674
633
 
675
634
  clear(segment: number): void {
@@ -695,16 +654,10 @@ export class SharedBatch {
695
654
  this.#publish(this.#drawn);
696
655
  return;
697
656
  }
698
- (this.mesh.instanceMatrix.array as Float32Array).fill(0, start * 16, (start + size) * 16);
657
+ batchRecords.fill(this.mesh.instanceMatrix, start * 16, size * 16);
699
658
  const ranges = this.#lodRangeAttribute();
700
- if (ranges !== undefined) {
701
- (ranges.array as Float32Array).fill(
702
- 0,
703
- start * LOD_RANGE_STRIDE,
704
- (start + size) * LOD_RANGE_STRIDE,
705
- );
706
- ranges.needsUpdate = true;
707
- }
659
+ if (ranges !== undefined)
660
+ batchRecords.fill(ranges, start * LOD_RANGE_STRIDE, size * LOD_RANGE_STRIDE);
708
661
  this.#hole(start, start + size);
709
662
  this.#settle();
710
663
  // The drawn range, not nothing. `#compact` closed the hole by moving the topmost block down
@@ -713,7 +666,7 @@ export class SharedBatch {
713
666
  this.#touched(0, this.#drawn);
714
667
  this.#boxes.delete(segment);
715
668
  this.#scales.delete(segment);
716
- this.#rebound();
669
+ this.#pendingBoxes.delete(segment);
717
670
  }
718
671
 
719
672
  /** The first free range with room for `count` records, taken out of the list; -1 when there is none. */
@@ -754,7 +707,8 @@ export class SharedBatch {
754
707
  * instead of a `grow`, and the free list is left as the single tail range `[drawn, capacity)`.
755
708
  */
756
709
  #compact(): void {
757
- const array = this.mesh.instanceMatrix.array as Float32Array;
710
+ const matrix = this.mesh.instanceMatrix;
711
+ const ranges = this.#lodRangeAttribute();
758
712
  for (;;) {
759
713
  let drawn = 0;
760
714
  let top = -1;
@@ -772,12 +726,14 @@ export class SharedBatch {
772
726
  const [holeStart, holeEnd] = lowest;
773
727
  const size = this.#size.get(top) ?? 0;
774
728
  if (size <= holeEnd - holeStart) {
775
- array.copyWithin(holeStart * 16, topFrom * 16, drawn * 16);
776
- this.#lodRangeAttribute()?.array.copyWithin(
777
- holeStart * LOD_RANGE_STRIDE,
778
- topFrom * LOD_RANGE_STRIDE,
779
- drawn * LOD_RANGE_STRIDE,
780
- );
729
+ batchRecords.move(matrix, topFrom * 16, holeStart * 16, (drawn - topFrom) * 16);
730
+ if (ranges !== undefined)
731
+ batchRecords.move(
732
+ ranges,
733
+ topFrom * LOD_RANGE_STRIDE,
734
+ holeStart * LOD_RANGE_STRIDE,
735
+ (drawn - topFrom) * LOD_RANGE_STRIDE,
736
+ );
781
737
  this.#start.set(top, holeStart);
782
738
  if (holeEnd - holeStart > size) this.#free[0] = [holeStart + size, holeEnd];
783
739
  else this.#free.shift();
@@ -786,12 +742,14 @@ export class SharedBatch {
786
742
  this.#touched(holeStart, size);
787
743
  } else {
788
744
  const shift = holeEnd - holeStart;
789
- array.copyWithin(holeStart * 16, holeEnd * 16, drawn * 16);
790
- this.#lodRangeAttribute()?.array.copyWithin(
791
- holeStart * LOD_RANGE_STRIDE,
792
- holeEnd * LOD_RANGE_STRIDE,
793
- drawn * LOD_RANGE_STRIDE,
794
- );
745
+ batchRecords.move(matrix, holeEnd * 16, holeStart * 16, (drawn - holeEnd) * 16);
746
+ if (ranges !== undefined)
747
+ batchRecords.move(
748
+ ranges,
749
+ holeEnd * LOD_RANGE_STRIDE,
750
+ holeStart * LOD_RANGE_STRIDE,
751
+ (drawn - holeEnd) * LOD_RANGE_STRIDE,
752
+ );
795
753
  this.#free.shift();
796
754
  for (const [handle, start] of this.#start) {
797
755
  if (start >= holeEnd) this.#start.set(handle, start - shift);
@@ -840,8 +798,8 @@ export class SharedBatch {
840
798
  *
841
799
  * A regroup is a permutation of `[0, drawn)` and there is no in-place order for one: writing the
842
800
  * visible squares to the front necessarily lands on squares whose records have not been read out
843
- * yet, in either direction. So every block is copied into {@link regroupScratch} and the new order
844
- * is copied back — two passes over the drawn range, and only when a square entered or left the
801
+ * yet, in either direction. So the engine's gather op reads every block out before it writes the
802
+ * new order back — two passes over the drawn range, and only when a square entered or left the
845
803
  * window, which on a settled camera is not once a frame.
846
804
  *
847
805
  * Squares keep their relative order within each half, so a residency change regroups in place and
@@ -860,15 +818,7 @@ export class SharedBatch {
860
818
  * stay few and large rather than many and small.
861
819
  */
862
820
  #regroup(visible = this.#visible): void {
863
- const array = this.mesh.instanceMatrix.array as Float32Array;
864
- const rangeAttribute = this.#lodRangeAttribute();
865
- const rangeArray = rangeAttribute?.array as Float32Array | undefined;
866
821
  const squares = this.#squares();
867
- let total = 0;
868
- for (const square of squares) total += sizeOf(square);
869
- const scratch = scratchFor(total * 16);
870
- const rangeScratch =
871
- rangeArray === undefined ? undefined : lodScratchFor(total * LOD_RANGE_STRIDE);
872
822
  // The visible squares first. `filter` is stable, so both halves keep the order the buffer had
873
823
  // them in and a residency change lays out exactly what the last one did.
874
824
  const front = squares.filter((one) => visible?.has(one.cluster) ?? true);
@@ -879,36 +829,27 @@ export class SharedBatch {
879
829
  // identity reorder touches nothing.
880
830
  let movedFrom = -1;
881
831
  let movedTo = 0;
832
+ const blocks: number[] = [];
882
833
  this.#squareSizes.clear();
883
834
  for (const square of [...front, ...back]) {
884
- const union = new Box3();
885
835
  for (const [handle, start, count] of square.blocks) {
886
- scratch.set(array.subarray(start * 16, (start + count) * 16), written * 16);
887
- if (rangeScratch !== undefined && rangeArray !== undefined)
888
- rangeScratch.set(
889
- rangeArray.subarray(start * LOD_RANGE_STRIDE, (start + count) * LOD_RANGE_STRIDE),
890
- written * LOD_RANGE_STRIDE,
891
- );
892
- // Read before it is overwritten: a block written back to its own offset is a record the GPU
893
- // already holds, and is the whole difference between a repack that costs nothing and one
894
- // that re-uploads the key.
836
+ blocks.push(start, count);
837
+ // A block written back to its own offset is a record the GPU already holds, and is the
838
+ // whole difference between a repack that costs nothing and one that re-uploads the key.
895
839
  if (this.#start.get(handle) !== written) {
896
840
  if (movedFrom < 0) movedFrom = written;
897
841
  movedTo = written + count;
898
842
  }
899
843
  this.#start.set(handle, written);
900
- const box = this.#boxes.get(handle);
901
- // A fresh `Box3` is already empty, so the first block's box is the square's and every block
902
- // after it unions into it.
903
- if (box !== undefined) union.union(box);
904
844
  written += count;
905
845
  }
906
846
  this.#squareSizes.set(square.cluster, sizeOf(square));
907
847
  }
908
- array.set(scratch.subarray(0, written * 16));
909
- if (rangeArray !== undefined && rangeScratch !== undefined && rangeAttribute !== undefined) {
910
- rangeArray.set(rangeScratch.subarray(0, written * LOD_RANGE_STRIDE));
911
- rangeAttribute.needsUpdate = true;
848
+ // The permutation itself is the engine's: one gather per buffer, read whole before it is written.
849
+ if (movedFrom >= 0) {
850
+ batchRecords.gather(this.mesh.instanceMatrix, 16, blocks);
851
+ const ranges = this.#lodRangeAttribute();
852
+ if (ranges !== undefined) batchRecords.gather(ranges, LOD_RANGE_STRIDE, blocks);
912
853
  }
913
854
  this.#drawn = written;
914
855
  const capacity = this.mesh.instanceMatrix.count;
@@ -1060,22 +1001,15 @@ export class SharedBatch {
1060
1001
  // A dressed batch's records were never in this attribute, so there is nothing to upload and
1061
1002
  // nothing to put back in charge of culling: the dispatch decided what it drew.
1062
1003
  if (this.gpu !== undefined) return;
1063
- const matrix = this.mesh.instanceMatrix;
1064
1004
  // A record is 16 array elements, and that is the unit `updateRanges` is in: three reads them
1065
1005
  // as element offsets into `array`, not as bytes.
1066
1006
  const drawn = this.#drawn * 16;
1067
- const low0 = from * 16;
1068
- const high0 = (from + count) * 16;
1069
- // The pending span is ours, and it lasts one update. Three's WebGPU path uploads through the
1070
- // interleaved buffer it derives from `instanceMatrix.array` and only that buffer's ranges are
1071
- // cleared after the write, so the ranges on `instanceMatrix` are never consumed: they were
1072
- // unioned in here forever, and after one wide write every later write re-uploaded the whole
1073
- // drawn range. The epoch moves once per `update()`, and the render at the end of an update is
1074
- // what consumes the span, so a fresh epoch is a fresh span.
1075
- let low = low0;
1076
- let high = high0;
1077
- const epoch = currentWriteEpoch();
1078
- if (this.#pendingEpoch === epoch) {
1007
+ let low = from * 16;
1008
+ let high = (from + count) * 16;
1009
+ // The pending span is ours, and it lasts until the flush at the end of this `update`, which is
1010
+ // what hands it to the engine: a frame that touches a mesh from several directions still
1011
+ // uploads one range.
1012
+ if (this.#pendingMatrix !== undefined) {
1079
1013
  if (this.#pendingLow < low) low = this.#pendingLow;
1080
1014
  if (this.#pendingHigh > high) high = this.#pendingHigh;
1081
1015
  }
@@ -1085,26 +1019,58 @@ export class SharedBatch {
1085
1019
  }
1086
1020
  this.#pendingLow = low;
1087
1021
  this.#pendingHigh = high;
1088
- this.#pendingEpoch = epoch;
1089
- matrix.clearUpdateRanges();
1090
- if (high > low) matrix.addUpdateRange(low, high - low);
1091
- matrix.needsUpdate = true;
1092
- const ranges = this.#lodRangeAttribute();
1093
- if (ranges !== undefined) {
1094
- ranges.clearUpdateRanges();
1095
- if (high > low)
1096
- ranges.addUpdateRange(
1097
- (low / 16) * LOD_RANGE_STRIDE,
1098
- ((high - low) / 16) * LOD_RANGE_STRIDE,
1099
- );
1100
- ranges.needsUpdate = true;
1101
- }
1022
+ this.#pendingMatrix = this.mesh.instanceMatrix;
1023
+ this.#pendingRanges = this.#lodRangeAttribute();
1024
+ batchRecords.touch(this);
1102
1025
  this.#publish(this.#drawn);
1103
- // Records are real, so the bounds are the ones `#rebound` just wrote and the mesh goes back to
1104
- // being culled.
1026
+ // Records are real, so the bounds `settleRecords` publishes are the ones to cull by.
1105
1027
  this.mesh.frustumCulled = true;
1106
1028
  }
1107
1029
 
1030
+ /** The flush asks for this frame's upload span, one range per buffer; see {@link #touched}. */
1031
+ uploadRecords(): void {
1032
+ const matrix = this.#pendingMatrix;
1033
+ if (matrix === undefined) return;
1034
+ const low = this.#pendingLow;
1035
+ const high = this.#pendingHigh;
1036
+ batchRecords.upload(matrix, low, high - low);
1037
+ if (this.#pendingRanges !== undefined)
1038
+ batchRecords.upload(
1039
+ this.#pendingRanges,
1040
+ (low / 16) * LOD_RANGE_STRIDE,
1041
+ ((high - low) / 16) * LOD_RANGE_STRIDE,
1042
+ );
1043
+ this.#pendingMatrix = undefined;
1044
+ this.#pendingRanges = undefined;
1045
+ }
1046
+
1047
+ /**
1048
+ * The flush answered: each block written this frame gets the box the engine measured, and the
1049
+ * mesh's bounds are published once from all of them.
1050
+ */
1051
+ settleRecords(boxes: ArrayLike<number>): void {
1052
+ for (const [segment, encoded] of this.#pendingBoxes) {
1053
+ // A block cleared after its write in the same frame has no box left to keep.
1054
+ if (!this.#start.has(segment)) continue;
1055
+ const at = encoded < 0 ? -1 - encoded : encoded;
1056
+ const box =
1057
+ encoded < 0
1058
+ ? this.#bounds
1059
+ : new Box3(
1060
+ new Vector3(boxes[at] as number, boxes[at + 1] as number, boxes[at + 2] as number),
1061
+ new Vector3(
1062
+ boxes[at + 3] as number,
1063
+ boxes[at + 4] as number,
1064
+ boxes[at + 5] as number,
1065
+ ),
1066
+ );
1067
+ this.#boxes.set(segment, box);
1068
+ this.#scales.set(segment, boxes[at + 6] as number);
1069
+ }
1070
+ this.#pendingBoxes.clear();
1071
+ this.#rebound();
1072
+ }
1073
+
1108
1074
  /**
1109
1075
  * The one place `mesh.count` is written, so a batch that would draw nothing is not submitted.
1110
1076
  *
@@ -11,9 +11,10 @@ import {
11
11
  import { markEngineRenderHook } from "./engine-render-hook.js";
12
12
  import { mergeByMaterial } from "./merge-parts.js";
13
13
  import {
14
- conservativeViewDepth,
14
+ LOD_NEAR_PLANE,
15
15
  isLodJoinProxy,
16
16
  lodChainOf,
17
+ selectLodFor,
17
18
  setModelLodLayers,
18
19
  } from "./model-lod.js";
19
20
  import { displacesVertices } from "./projection-plan.js";
@@ -777,12 +778,7 @@ export class CellChunks {
777
778
  const view =
778
779
  camera === undefined
779
780
  ? undefined
780
- : conservativeViewDepth(
781
- camera,
782
- sphere.center,
783
- sphere.radius,
784
- Reflect.get(camera, "near") ?? 0.1,
785
- );
781
+ : selectLodFor(camera, sphere, Reflect.get(camera, "near") ?? LOD_NEAR_PLANE);
786
782
  const height = renderer?.domElement.height;
787
783
  const selected = state.selector.select({
788
784
  sourceReady: cellLoaded(cell),
@@ -210,6 +210,13 @@ export interface IWorldCellsLoadOptions {
210
210
  * loader works. The url is the authored one, so a compiled package wants `assets` instead.
211
211
  */
212
212
  readonly loadModel?: (url: string) => Promise<Object3D>;
213
+ /**
214
+ * The game's surface for one loaded part, given the authored material and the part's geometry: a
215
+ * swaying tree returns its own node material reading the baked wind attribute. Return the material
216
+ * passed in to keep it. The game memoises per source material, so every level and placement of an
217
+ * asset shares one surface; this world releases it with the asset's own.
218
+ */
219
+ readonly partMaterial?: (material: Material, geometry: BufferGeometry) => Material;
213
220
  /**
214
221
  * Model loads in flight at once, assets and chunks together. Defaults to `loadAll`'s
215
222
  * `concurrency`, six.