@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
package/src/auto-batch.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { type BufferGeometry, type Material, type Mesh, Object3D } from "three";
1
+ import { type BufferGeometry, type Layers, type Material, type Mesh, Object3D } from "three";
2
2
 
3
3
  import { isEngineRenderHook } from "./engine-render-hook.js";
4
4
  import type { Registry } from "./entities.js";
5
5
  import { mergeByMaterial } from "./merge-parts.js";
6
+ import { isStreamedGeometry } from "./model-lod.js";
6
7
  import { displacesVertices, hasMorphAttributes } from "./projection-plan.js";
7
8
  import { unbilled } from "./startup-offscreen-bytes.js";
8
9
 
@@ -25,6 +26,13 @@ import { unbilled } from "./startup-offscreen-bytes.js";
25
26
  * geometry, no render hook, no skin, morph, instancing or vertex displacement. Everything else keeps
26
27
  * its draw. The merged mesh keeps the game's own material and shadow, layer and render-order flags.
27
28
  *
29
+ * **The game never sees the merge.** A source is kept out of the draw without touching anything the game
30
+ * reads or copies: the engine's own `__tnBatchHidden` flag, or on plain three a `layers` view that answers
31
+ * the renderer's `test` with `false` and the game's `mask` with its own value. `visible` stays the game's,
32
+ * so a game that saves and restores visibility (a warm-up that shows everything to compile it) or clones a
33
+ * merged source gets back exactly what it authored. Hiding through `visible` let Midway's warm-up re-hide a
34
+ * given-back control stick for good, and a clone inherit the hide.
35
+ *
28
36
  * **Named overrides, both reported.** `userData.batch = "off"` on a mesh or any ancestor keeps that
29
37
  * subtree out. `autoBatch: false` in the game config switches the pass off.
30
38
  */
@@ -56,8 +64,10 @@ const ENGINE_GUARD_CHUNK = 2048;
56
64
  * compares it in place, so a lap of 8,000 sources fits the budget the JS slice spent on 200.
57
65
  */
58
66
  interface IEngineGuard {
59
- __tnGuardWatch(sources: readonly Mesh[]): number;
67
+ __tnGuardWatch(sources: readonly Mesh[], ancestors?: readonly Object3D[]): number;
60
68
  __tnGuardCheck(limit: number): ArrayLike<number>;
69
+ /** PRD-828: the sources' ancestors, checked whole in the engine; absent on an older engine. */
70
+ __tnGuardCheckAncestors?(): ArrayLike<number>;
61
71
  }
62
72
 
63
73
  function engineGuardOf(scene: Object3D): IEngineGuard | undefined {
@@ -254,6 +264,57 @@ function stampMatches(object: Object3D, stamp: Float64Array): boolean {
254
264
  return true;
255
265
  }
256
266
 
267
+ /** Each plain-three source's own `Layers`, kept while a view stands in for it. */
268
+ const ownLayers = new WeakMap<Object3D, Layers>();
269
+
270
+ /** Nonzero while core draws the world; only then does a plain-three source's view fail the layer test. */
271
+ let drawingWorld = 0;
272
+
273
+ /**
274
+ * Runs core's world draw. On plain three a merged source is out of the renderer's layer test only in
275
+ * here, so a game's own raycast or `layers.test` still finds it, as it did before the merge.
276
+ */
277
+ export function drawWorld<T>(draw: () => T): T {
278
+ drawingWorld += 1;
279
+ try {
280
+ return draw();
281
+ } finally {
282
+ drawingWorld -= 1;
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Takes a merged source out of the draw, or puts it back, leaving every property the game reads as it was.
288
+ * The engine hides it natively; on plain three, the renderer and shadow passes ask `layers.test(camera)`,
289
+ * and a view whose `test` fails inside {@link drawWorld} and whose `mask` reads and writes the source's own
290
+ * `Layers` hides it from that draw alone. A clone copies `mask`, so it copies the game's layers, not the hide.
291
+ */
292
+ function setBatchHidden(mesh: Mesh, hidden: boolean): void {
293
+ const engine = mesh as Mesh & { __tnBatchHidden?: boolean };
294
+ if ("__tnBatchHidden" in engine) {
295
+ engine.__tnBatchHidden = hidden;
296
+ return;
297
+ }
298
+ if (!hidden) {
299
+ const own = ownLayers.get(mesh);
300
+ if (own !== undefined) mesh.layers = own;
301
+ ownLayers.delete(mesh);
302
+ return;
303
+ }
304
+ if (ownLayers.has(mesh)) return;
305
+ const own = mesh.layers;
306
+ ownLayers.set(mesh, own);
307
+ mesh.layers = Object.create(Object.getPrototypeOf(own) as object, {
308
+ mask: {
309
+ get: () => own.mask,
310
+ set: (mask: number) => {
311
+ own.mask = mask;
312
+ },
313
+ },
314
+ test: { value: (layers: Layers) => drawingWorld === 0 && own.test(layers) },
315
+ }) as Layers;
316
+ }
317
+
257
318
  function isMesh(object: Object3D): object is Mesh {
258
319
  return (object as Mesh).isMesh === true;
259
320
  }
@@ -290,9 +351,17 @@ function bakeable(geometry: BufferGeometry): boolean {
290
351
  return true;
291
352
  }
292
353
 
293
- /** Whether merging this mesh leaves the frame looking the same. */
354
+ /**
355
+ * Whether merging this mesh leaves the frame looking the same. A streamed coarse model stays out:
356
+ * its full file replaces the geometry in place, and a merged copy would keep the coarse vertices.
357
+ */
294
358
  function mergeable(mesh: Mesh): boolean {
295
- return plainDraw(mesh) && bakeable(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
359
+ return (
360
+ plainDraw(mesh) &&
361
+ bakeable(mesh.geometry) &&
362
+ !isStreamedGeometry(mesh.geometry) &&
363
+ mesh.matrixWorld.determinant() > 0
364
+ );
296
365
  }
297
366
 
298
367
  /** Meshes with equal keys can share a merged mesh without changing how any of them draws. */
@@ -340,6 +409,8 @@ export class AutoBatch {
340
409
  readonly #excluded = new WeakSet<Object3D>();
341
410
  #records: IRecord[] = [];
342
411
  readonly #ancestors = new Map<Object3D, IAncestor>();
412
+ /** The ancestors in the order the engine's guard watches them, so its indices name them. */
413
+ #watchedAncestors: Object3D[] = [];
343
414
  #watched = new Map<Mesh, Float64Array>();
344
415
  #state: State = "idle";
345
416
  #known = Number.NaN;
@@ -366,12 +437,24 @@ export class AutoBatch {
366
437
  readonly #levelOne = new Set<Object3D>();
367
438
  /** Children added to or removed from the scene since the last frame, to start or stop counting. */
368
439
  #arrived: Object3D[] = [];
369
- readonly #onTopChild = (event: { child: Object3D }): void => {
440
+ /**
441
+ * The subtrees a scan walks: what was added at the top two levels since the last finished scan, plus what an
442
+ * earlier scan could not merge yet (a hidden subtree, a mesh that moved while watched, a mesh with no partner).
443
+ * A scan costs what arrived and what still waits, never the scene: ten thrown objects a second re-walked the
444
+ * stress lab's 5,000 nodes after every add and every remove, 4.1 ms of a 9.8 ms frame.
445
+ * ponytail: a mesh with no partner is walked by every scan; index those by material when a scene holds thousands.
446
+ */
447
+ #pending = new Set<Object3D>();
448
+ /** What the scan in progress met and left for the next one: hidden subtrees. */
449
+ #later = new Set<Object3D>();
450
+ readonly #onTopChild = (event: { type: string; child: Object3D }): void => {
370
451
  this.#shapeChanges += 1;
371
452
  this.#arrived.push(event.child);
453
+ if (event.type === "childadded") this.#pending.add(event.child);
372
454
  };
373
- readonly #onChild = (): void => {
455
+ readonly #onChild = (event: { type: string; child: Object3D }): void => {
374
456
  this.#shapeChanges += 1;
457
+ if (event.type === "childadded") this.#pending.add(event.child);
375
458
  };
376
459
 
377
460
  constructor(scene: Object3D, options: IAutoBatchOptions = {}) {
@@ -386,6 +469,7 @@ export class AutoBatch {
386
469
  scene.addEventListener("childadded", this.#onTopChild);
387
470
  scene.addEventListener("childremoved", this.#onTopChild);
388
471
  this.#arrived = [...scene.children];
472
+ this.#pending = new Set(this.#arrived);
389
473
  }
390
474
 
391
475
  get census(): IAutoBatchCensus {
@@ -435,6 +519,7 @@ export class AutoBatch {
435
519
  this.#frames = 0;
436
520
  if (this.#watched.size < 2) {
437
521
  // Nothing here can share a draw: the pass is finished until the scene's shape changes.
522
+ this.#finish(this.#watched);
438
523
  this.#known = shape;
439
524
  this.#state = "idle";
440
525
  }
@@ -452,6 +537,7 @@ export class AutoBatch {
452
537
  if (!this.#enabled) return;
453
538
  const meshes = this.#snapshot();
454
539
  if (meshes.size >= 2) this.#merge([...meshes.keys()]);
540
+ this.#finish(meshes);
455
541
  this.#watchEngine();
456
542
  this.#known = this.#shape();
457
543
  this.#state = "idle";
@@ -461,11 +547,13 @@ export class AutoBatch {
461
547
  reset(): void {
462
548
  for (const record of this.#records) if (!record.out) this.#giveBack(record);
463
549
  this.#records = [];
464
- this.#watchEngine();
465
550
  this.#ancestors.clear();
551
+ this.#watchEngine();
466
552
  this.#watched.clear();
467
553
  this.#state = "idle";
468
554
  this.#known = Number.NaN;
555
+ // The next scene's content arrives through the events; what stays under the scene is scanned once more.
556
+ this.#pending = new Set(this.#scene.children);
469
557
  }
470
558
 
471
559
  /**
@@ -491,50 +579,83 @@ export class AutoBatch {
491
579
  }
492
580
 
493
581
  /**
494
- * Eligible meshes with the world matrix they were drawn at. Runs only while the scene settles, so
495
- * its reads are no game's steady cost and the bridge census leaves them out.
582
+ * Eligible meshes under the pending subtrees, with the world matrix they were drawn at. Runs only while
583
+ * the scene settles, so its reads are no game's steady cost and the bridge census leaves them out.
496
584
  */
497
585
  #snapshot(): Map<Mesh, Float64Array> {
498
586
  return unbilled(() => {
499
- this.#scene.updateMatrixWorld(true);
500
587
  const found = new Map<Mesh, Float64Array>();
501
588
  this.#optedOut = 0;
502
589
  this.#held = 0;
590
+ this.#later = new Set();
503
591
  const held = heldObjects(this.#entities);
504
- this.#walk(this.#scene, false, held, (mesh) => {
592
+ const visit = (mesh: Mesh): void => {
505
593
  found.set(mesh, Float64Array.from(mesh.matrixWorld.elements));
506
- });
594
+ };
595
+ for (const root of [...this.#pending]) {
596
+ const off = this.#hangs(root, held);
597
+ if (off === "gone") this.#pending.delete(root);
598
+ else if (off === "wait") this.#later.add(root);
599
+ else {
600
+ root.updateWorldMatrix(true, true);
601
+ this.#visit(root, off, held, visit);
602
+ }
603
+ }
507
604
  return found;
508
605
  });
509
606
  }
510
607
 
511
- #walk(
512
- object: Object3D,
608
+ /**
609
+ * How a pending subtree hangs under the scene. `gone`: it left the scene, or a pending ancestor walks it.
610
+ * `wait`: an ancestor is hidden, held or an LOD, which the game can change. Else whether an ancestor opted it out.
611
+ */
612
+ #hangs(root: Object3D, held: ReadonlySet<Object3D>): boolean | "gone" | "wait" {
613
+ let off = false;
614
+ let wait = false;
615
+ for (let node = root.parent; node !== this.#scene; node = node.parent) {
616
+ if (node === null || this.#excluded.has(node) || this.#pending.has(node)) return "gone";
617
+ wait ||= !node.visible || (node as { isLOD?: boolean }).isLOD === true || held.has(node);
618
+ off ||= node.userData.batch === "off";
619
+ }
620
+ return wait ? "wait" : off;
621
+ }
622
+
623
+ /**
624
+ * Ends a scan: the next one walks what this one left (`#later`) and each mesh it found that no merge took.
625
+ * A mesh that moved can come to rest, and a mesh with no partner can get one.
626
+ */
627
+ #finish(found: ReadonlyMap<Mesh, Float64Array>): void {
628
+ this.#pending = this.#later;
629
+ this.#later = new Set();
630
+ for (const mesh of found.keys()) if (!sourceGroups.has(mesh)) this.#pending.add(mesh);
631
+ }
632
+
633
+ #visit(
634
+ child: Object3D,
513
635
  off: boolean,
514
636
  held: ReadonlySet<Object3D>,
515
637
  visit: (mesh: Mesh) => void,
516
638
  ): void {
517
- for (const child of object.children) {
518
- if (
519
- !child.visible ||
520
- this.#excluded.has(child) ||
521
- (child as { isLOD?: boolean }).isLOD === true
522
- )
523
- continue;
524
- if (held.has(child)) {
525
- const parts = countMeshes(child);
526
- if (parts <= HELD_SUBTREE_MAX_MESHES) {
527
- this.#held += parts;
528
- continue;
529
- }
530
- }
531
- const skip = off || child.userData.batch === "off";
532
- if (isMesh(child) && mergeable(child)) {
533
- if (skip) this.#optedOut += 1;
534
- else visit(child);
639
+ if (!child.visible) {
640
+ // Hidden now; the game can show it, so the next scan asks again.
641
+ this.#later.add(child);
642
+ return;
643
+ }
644
+ if (this.#excluded.has(child) || (child as { isLOD?: boolean }).isLOD === true) return;
645
+ if (held.has(child)) {
646
+ const parts = countMeshes(child);
647
+ if (parts <= HELD_SUBTREE_MAX_MESHES) {
648
+ this.#held += parts;
649
+ return;
535
650
  }
536
- this.#walk(child, skip, held, visit);
537
651
  }
652
+ const skip = off || child.userData.batch === "off";
653
+ // A source already drawn by a merge is not walked into a second one: its `visible` stays true.
654
+ if (isMesh(child) && !sourceGroups.has(child) && mergeable(child)) {
655
+ if (skip) this.#optedOut += 1;
656
+ else visit(child);
657
+ }
658
+ for (const part of child.children) this.#visit(part, skip, held, visit);
538
659
  }
539
660
 
540
661
  #settle(): void {
@@ -551,6 +672,7 @@ export class AutoBatch {
551
672
  this.#unsettled = moved;
552
673
  this.#watched = new Map();
553
674
  this.#merge([...stable.keys()]);
675
+ this.#finish(now);
554
676
  this.#watchEngine();
555
677
  this.#known = this.#shape();
556
678
  this.#state = "idle";
@@ -629,8 +751,8 @@ export class AutoBatch {
629
751
  };
630
752
  vertexStart += vertexCount;
631
753
  // The source stays where the game put it, so rays, `userData` and world matrices keep working.
632
- // Only the renderer is told not to draw it.
633
- mesh.visible = false;
754
+ // Only the renderer is told not to draw it; `visible` stays the game's.
755
+ setBatchHidden(mesh, true);
634
756
  writeStamp(mesh, record.stamp);
635
757
  group.sources.push(record);
636
758
  sourceGroups.set(mesh, group);
@@ -674,15 +796,33 @@ export class AutoBatch {
674
796
  /** Every frame, because there are few ancestors and one moved parent changes thousands of sources. */
675
797
  #checkAncestors(): number {
676
798
  let given = 0;
799
+ const engine = this.#engine;
800
+ if (engine?.__tnGuardCheckAncestors !== undefined) {
801
+ const changed = engine.__tnGuardCheckAncestors();
802
+ for (let at = 0; at < changed.length; at += 1) {
803
+ const node = this.#watchedAncestors[changed[at] as number];
804
+ if (node !== undefined) given += this.#giveBackUnder(node);
805
+ }
806
+ return given;
807
+ }
677
808
  for (const [node, entry] of this.#ancestors) {
678
809
  if (node.parent === entry.parent && stampMatches(node, entry.stamp)) continue;
679
- this.#excluded.add(node);
680
- this.#ancestors.delete(node);
681
- for (const record of entry.records) {
682
- if (record.out) continue;
683
- this.#giveBack(record);
684
- given += 1;
685
- }
810
+ given += this.#giveBackUnder(node);
811
+ }
812
+ return given;
813
+ }
814
+
815
+ /** An ancestor moved: it never merges again, and every source under it goes back to the game. */
816
+ #giveBackUnder(node: Object3D): number {
817
+ const entry = this.#ancestors.get(node);
818
+ if (entry === undefined) return 0;
819
+ let given = 0;
820
+ this.#excluded.add(node);
821
+ this.#ancestors.delete(node);
822
+ for (const record of entry.records) {
823
+ if (record.out) continue;
824
+ this.#giveBack(record);
825
+ given += 1;
686
826
  }
687
827
  return given;
688
828
  }
@@ -692,7 +832,12 @@ export class AutoBatch {
692
832
  * and each give-back, so no game code runs between the state merged and the state watched.
693
833
  */
694
834
  #watchEngine(): void {
695
- this.#engine?.__tnGuardWatch(this.#records.map((record) => record.mesh));
835
+ if (this.#engine === undefined) return;
836
+ this.#watchedAncestors = [...this.#ancestors.keys()];
837
+ this.#engine.__tnGuardWatch(
838
+ this.#records.map((record) => record.mesh),
839
+ this.#watchedAncestors,
840
+ );
696
841
  }
697
842
 
698
843
  /** A slice of the sources bounded by {@link GUARD_BUDGET_MS}, or all of them under `everyFrame`. */
@@ -764,7 +909,8 @@ export class AutoBatch {
764
909
  this.#excluded.add(record.mesh);
765
910
  this.#restored += 1;
766
911
  this.#meshes -= 1;
767
- record.mesh.visible = true;
912
+ // Drawn on its own again, as the game now has it: a source the game hid stays hidden.
913
+ setBatchHidden(record.mesh, false);
768
914
  const { group } = record;
769
915
  group.live -= 1;
770
916
  if (group.live > 0) this.#collapse(record);
@@ -3,6 +3,7 @@ import {
3
3
  BufferGeometry,
4
4
  type Camera,
5
5
  Euler,
6
+ Frustum,
6
7
  InstancedMesh,
7
8
  type Material,
8
9
  Matrix4,
@@ -10,7 +11,17 @@ import {
10
11
  Quaternion,
11
12
  Vector3,
12
13
  } from "three";
13
- import { type IClusterTable, pixelsPerUnit, selectClusterCut } from "./clustered-mesh.js";
14
+ import {
15
+ ClusterView,
16
+ DEFAULT_VIEW_MARGIN,
17
+ type IClusterTable,
18
+ assertViewMargin,
19
+ clusterTableRadius,
20
+ outsideFrustum,
21
+ pixelsPerUnit,
22
+ selectClusterCut,
23
+ worldFrustum,
24
+ } from "./clustered-mesh.js";
14
25
 
15
26
  /**
16
27
  * Many copies of one clustered body, each drawn at the detail its own distance earns.
@@ -57,6 +68,16 @@ export interface IClusteredBatchOptions {
57
68
  readonly distanceRatio?: number;
58
69
  /** Screen-space error budget in pixels, as {@link ClusteredMesh}. Default 1. */
59
70
  readonly errorPixels?: number;
71
+ /**
72
+ * Whether copies the camera cannot see are skipped.
73
+ *
74
+ * On by default. A batch that casts shadows keeps every copy regardless — a copy out of the main
75
+ * view can still cast into it — until shadows have a cut of their own. The batch reports what it
76
+ * did through {@link ClusteredBatch.viewCullReport}.
77
+ */
78
+ readonly viewCull?: boolean;
79
+ /** How far the camera may turn, in radians, before the bands are taken again. Default two degrees. */
80
+ readonly viewMargin?: number;
60
81
  /** The shape every copy draws, carrying the baked cluster table. */
61
82
  readonly geometry: BufferGeometry;
62
83
  /** The surface every copy draws with, supplied by the game and used by reference. */
@@ -99,6 +120,8 @@ const DEFAULT_RECUT_FRACTION = 0.01;
99
120
  const DEFAULT_ERROR_PIXELS = 1;
100
121
  /** A copy nearer than this is treated as this far away, rather than taking log of zero. */
101
122
  const MIN_DISTANCE = 1e-3;
123
+ /** A copy the view does not hold: it joins no band, anchors no cut, and submits nothing. */
124
+ const CULLED = -2147483648;
102
125
 
103
126
  interface IPlaced {
104
127
  readonly matrix: Matrix4;
@@ -163,14 +186,34 @@ export class ClusteredBatch {
163
186
  readonly #cameraWorld = new Vector3();
164
187
  readonly #cameraLocal = new Vector3();
165
188
  readonly #lastCut = new Vector3();
189
+ readonly #rotation = new Quaternion();
190
+ readonly #lastRotation = new Quaternion();
191
+ readonly #view = new ClusterView();
166
192
  #hasCut = false;
167
193
  #lastScale = 0;
194
+ /** The projection the bands were chosen by: an aspect or zoom change keeps the pixel scale. */
195
+ readonly #lastProjection = new Matrix4();
196
+ #culled = false;
168
197
  readonly #distanceRatio: number;
198
+ /** Radians the camera may turn before the bands are taken again. */
199
+ readonly viewMargin: number;
200
+ /**
201
+ * Whether copies the camera cannot see are skipped. Writable; the batch reports what it did
202
+ * through {@link ClusteredBatch.viewCullReport}.
203
+ */
204
+ viewCull: boolean;
169
205
  /** Bands this camera wants that are not built yet; while any remain the cut cannot settle. */
170
206
  #pending = 0;
171
207
  #root: Object3D | null = null;
172
208
  #built: IClusteredBatchBuildOptions | null = null;
173
209
  #drawnTriangles = 0;
210
+ readonly #meshRadius: number;
211
+ readonly #frustum = new Frustum();
212
+ readonly #viewMatrix = new Matrix4();
213
+ /** The band each copy was drawn in this update, or `CULLED` when it was not drawn at all. */
214
+ #bandKey: Int32Array;
215
+ #drawnCopiesOutsideView = 0;
216
+ #drawnTrianglesOutsideView = 0;
174
217
 
175
218
  constructor(options: IClusteredBatchOptions) {
176
219
  this.#options = options;
@@ -179,8 +222,13 @@ export class ClusteredBatch {
179
222
  throw new Error(
180
223
  `ClusteredBatch distanceRatio must be above one, got ${this.#distanceRatio}.`,
181
224
  );
225
+ this.viewCull = options.viewCull ?? true;
226
+ this.viewMargin = options.viewMargin ?? DEFAULT_VIEW_MARGIN;
227
+ assertViewMargin(this.viewMargin);
182
228
  this.#selection = new Uint32Array(options.table.ranges.length / 2);
183
229
  this.#wantedKey = new Int32Array(0);
230
+ this.#bandKey = new Int32Array(0);
231
+ this.#meshRadius = clusterTableRadius(options.table);
184
232
  }
185
233
 
186
234
  /** How many copies are placed. */
@@ -200,6 +248,33 @@ export class ClusteredBatch {
200
248
  return this.#drawnTriangles;
201
249
  }
202
250
 
251
+ /**
252
+ * Copies the current cut submits whose own bounding sphere lies wholly outside the view volume.
253
+ *
254
+ * A measurement, not a cull: see {@link ClusteredMesh.drawnTrianglesOutsideView}.
255
+ */
256
+ get drawnCopiesOutsideView(): number {
257
+ return this.#drawnCopiesOutsideView;
258
+ }
259
+
260
+ /** Triangles those copies submit: their own band's cut, times how many copies are outside. */
261
+ get drawnTrianglesOutsideView(): number {
262
+ return this.#drawnTrianglesOutsideView;
263
+ }
264
+
265
+ /**
266
+ * What this batch does about copies outside the view, and why.
267
+ *
268
+ * `"on"` when copies the camera cannot see are skipped, and a reason when they are not — a batch
269
+ * that silently kept drawing a whole copy behind the camera would be a cost with no symptom, and
270
+ * one that silently dropped what a shadow camera can see would be a missing shadow with no cause.
271
+ */
272
+ get viewCullReport(): string {
273
+ if (!this.viewCull) return "off (viewCull = false)";
274
+ if (this.#built?.castShadow === true) return "off (castShadow)";
275
+ return "on";
276
+ }
277
+
203
278
  /** Adds one copy. Returns its index, so the game can move it later. */
204
279
  place(placement: IClusteredPlacement): number {
205
280
  if (this.#built !== null)
@@ -238,32 +313,67 @@ export class ClusteredBatch {
238
313
  const scale = pixelsPerUnit(camera, viewportHeight);
239
314
  camera.updateWorldMatrix(true, false);
240
315
  this.#cameraWorld.setFromMatrixPosition(camera.matrixWorld);
316
+ camera.getWorldQuaternion(this.#rotation);
317
+
318
+ // A culled batch is a batch whose bands were chosen for a view, so the turn it was widened by is
319
+ // part of what makes the previous cut still right. `castShadow` keeps every copy: one outside
320
+ // the main view can still be cast into it.
321
+ const culled = this.viewCull && this.#built?.castShadow !== true;
322
+ if (culled) {
323
+ this.#view.setFromCamera(camera, this.viewMargin);
324
+ // Copies are placed in the batch root's space; a parent that moves the batch moves them too.
325
+ root.updateWorldMatrix(true, false);
326
+ this.#view.setTransform(root.matrixWorld);
327
+ }
241
328
 
242
329
  // Everything below walks every cluster of every occupied band. Skip it outright when the camera
243
- // has not moved enough to change a cut, and when every band this camera needs is already built.
330
+ // has not moved or turned enough to change a cut, and when every band this camera needs is
331
+ // already built.
244
332
  let nearestCopy = Number.POSITIVE_INFINITY;
245
333
  for (const placed of this.#placed)
246
334
  nearestCopy = Math.min(nearestCopy, this.#cameraWorld.distanceTo(placed.position));
247
335
  const settled =
248
336
  this.#hasCut &&
337
+ culled === this.#culled &&
249
338
  scale === this.#lastScale &&
339
+ camera.projectionMatrix.equals(this.#lastProjection) &&
250
340
  this.#pending === 0 &&
341
+ this.#rotation.angleTo(this.#lastRotation) <= this.viewMargin &&
251
342
  this.#cameraWorld.distanceTo(this.#lastCut) <=
252
343
  Math.max(nearestCopy, MIN_DISTANCE) *
253
344
  (this.#options.recutFraction ?? DEFAULT_RECUT_FRACTION);
254
345
  if (settled) return this.#drawnTriangles;
255
346
  this.#lastCut.copy(this.#cameraWorld);
347
+ this.#lastRotation.copy(this.#rotation);
256
348
  this.#lastScale = scale;
349
+ this.#lastProjection.copy(camera.projectionMatrix);
350
+ this.#culled = culled;
257
351
  this.#hasCut = true;
258
352
 
259
- if (this.#wantedKey.length !== this.#placed.length)
353
+ if (this.#wantedKey.length !== this.#placed.length) {
260
354
  this.#wantedKey = new Int32Array(this.#placed.length);
355
+ this.#bandKey = new Int32Array(this.#placed.length);
356
+ }
261
357
  for (const group of this.#groups.values()) group.copies.length = 0;
262
358
 
263
359
  // Which band each copy belongs to, before any borrowing.
264
360
  const wantedKeys = new Set<number>();
265
361
  for (let copy = 0; copy < this.#placed.length; copy += 1) {
266
362
  const placed = this.#placed[copy] as IPlaced;
363
+ // A copy no camera can see joins no band, anchors no cut and submits nothing. Its own bounding
364
+ // sphere is the test, the same sphere three would cull it by.
365
+ if (
366
+ culled &&
367
+ !this.#view.touches(
368
+ placed.position.x,
369
+ placed.position.y,
370
+ placed.position.z,
371
+ this.#meshRadius * placed.scale,
372
+ )
373
+ ) {
374
+ this.#wantedKey[copy] = CULLED;
375
+ continue;
376
+ }
267
377
  const distance = Math.max(this.#cameraWorld.distanceTo(placed.position), MIN_DISTANCE);
268
378
  // Grouped on distance measured in the body's own units, so two copies at different scales
269
379
  // that cover the same screen area land in the same group.
@@ -291,7 +401,12 @@ export class ClusteredBatch {
291
401
 
292
402
  for (let copy = 0; copy < this.#placed.length; copy += 1) {
293
403
  const wanted = this.#wantedKey[copy] as number;
404
+ if (wanted === CULLED) {
405
+ this.#bandKey[copy] = CULLED;
406
+ continue;
407
+ }
294
408
  const key = open.has(wanted) ? wanted : this.#nearestOpenKey(wanted, open);
409
+ this.#bandKey[copy] = key;
295
410
  let group = this.#groups.get(key);
296
411
  if (group === undefined) {
297
412
  group = { copies: [], cut: new Uint32Array(0), empty: 0, mesh: null };
@@ -308,9 +423,33 @@ export class ClusteredBatch {
308
423
  this.#groups.delete(key);
309
424
  }
310
425
  }
426
+ this.#countOutsideView(camera);
311
427
  return this.#drawnTriangles;
312
428
  }
313
429
 
430
+ /**
431
+ * Records how many copies of this batch, and how many of their triangles, lie wholly out of view.
432
+ *
433
+ * A copy is tested on its own bounding sphere — the body's radius at the copy's scale — which is
434
+ * the sphere three itself would cull it by. Read-only, and taken only on a frame that re-cut.
435
+ */
436
+ #countOutsideView(camera: Camera): void {
437
+ const frustum = worldFrustum(camera, this.#frustum, this.#viewMatrix);
438
+ let copies = 0;
439
+ let triangles = 0;
440
+ for (let copy = 0; copy < this.#placed.length; copy += 1) {
441
+ if ((this.#bandKey[copy] as number) === CULLED) continue;
442
+ const placed = this.#placed[copy] as IPlaced;
443
+ if (!outsideFrustum(frustum, placed.position, this.#meshRadius * placed.scale)) continue;
444
+ copies += 1;
445
+ const group = this.#groups.get(this.#bandKey[copy] as number);
446
+ const mesh = group?.mesh;
447
+ if (mesh?.visible === true) triangles += mesh.geometry.drawRange.count / 3;
448
+ }
449
+ this.#drawnCopiesOutsideView = copies;
450
+ this.#drawnTrianglesOutsideView = triangles;
451
+ }
452
+
314
453
  /**
315
454
  * Gives one group's index buffer back.
316
455
  *
@@ -388,6 +527,10 @@ export class ClusteredBatch {
388
527
  this.#options.errorPixels ?? DEFAULT_ERROR_PIXELS,
389
528
  this.#selection,
390
529
  );
530
+ // Every band's cut is taken unpruned, on purpose. One cut serves every copy in the band, and
531
+ // those copies face the camera from different directions: pruning it by the view would drop the
532
+ // clusters the copies either side of the band are looking at. What a band does not hold is
533
+ // culled per copy, above.
391
534
  let indices = 0;
392
535
  for (let slot = 0; slot < selected; slot += 1)
393
536
  indices += this.#options.table.ranges[(this.#selection[slot] as number) * 2 + 1] as number;