@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
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);
@@ -0,0 +1,152 @@
1
+ import { type BufferGeometry, Vector3 } from "three";
2
+
3
+ /**
4
+ * A far level for a card mesh: keep `keep` of its cards and grow each kept card about its own
5
+ * centre so the mesh holds its total surface area.
6
+ *
7
+ * Needle and leaf cards are disconnected quads, so an edge-collapse simplifier cannot reduce them
8
+ * (the asset cook's chain skips them, and a far tree drew every card of its middle level to the
9
+ * horizon). Dropping cards alone thins the crown, so the kept ones take the lost area, as Unreal's
10
+ * Nanite "Preserve Area" foliage does (UE 5.8.3:
11
+ * Engine/Source/Developer/MeshSimplifier/Private/MeshSimplify.cpp `PreserveSurfaceArea`).
12
+ *
13
+ * A card is one island of triangles joined by shared vertex indices. The choice is deterministic: a
14
+ * fixed-seed shuffle of the islands, taken until the triangle share is met. Positions move; every
15
+ * other attribute is kept, and a uniform scale about the centre leaves normals and UVs valid.
16
+ *
17
+ * Only the drawn range counts: a material section cut from a shared index by `setDrawRange` thins its
18
+ * own triangles, and the result, whose index holds just the kept ones, draws its whole index.
19
+ */
20
+ export function thinCards(geometry: BufferGeometry, keep: number): BufferGeometry {
21
+ if (!(keep > 0 && keep <= 1)) throw new Error(`thinCards keep must be in (0, 1], got ${keep}.`);
22
+ const index = geometry.index;
23
+ if (index === null) throw new Error("thinCards needs an indexed geometry.");
24
+ if (geometry.groups.length > 0) throw new Error("thinCards cannot keep material groups.");
25
+ const [first, end] = drawnRange(geometry);
26
+ const triangles = (end - first) / 3;
27
+ const target = Math.max(1, Math.round(triangles * keep));
28
+ if (target >= triangles) return geometry;
29
+
30
+ const position = geometry.getAttribute("position");
31
+ const { kept, scale } = pickCards([...cardIslands(geometry, first, end).values()], target);
32
+
33
+ const out = geometry.clone();
34
+ const moved = out.getAttribute("position");
35
+ const indices: number[] = [];
36
+ const vertex = new Vector3();
37
+ for (const island of kept) {
38
+ // An island of zero area accumulated nothing in the weighted centre, so it takes the plain mean of
39
+ // its triangle centroids; the origin would scale the card about the world origin instead.
40
+ const centre =
41
+ island.area > 0
42
+ ? island.centre.divideScalar(island.area)
43
+ : island.plain.divideScalar(island.firsts.length);
44
+ const own = new Set<number>();
45
+ for (const t of island.firsts)
46
+ for (let k = 0; k < 3; k++) {
47
+ const v = index.getX(t + k);
48
+ indices.push(v);
49
+ own.add(v);
50
+ }
51
+ for (const v of own) {
52
+ vertex.fromBufferAttribute(position, v).sub(centre).multiplyScalar(scale).add(centre);
53
+ moved.setXYZ(v, vertex.x, vertex.y, vertex.z);
54
+ }
55
+ }
56
+ moved.needsUpdate = true;
57
+ out.setIndex(indices);
58
+ out.setDrawRange(0, Number.POSITIVE_INFINITY);
59
+ out.computeBoundingBox();
60
+ out.computeBoundingSphere();
61
+ return out;
62
+ }
63
+
64
+ interface ICardIsland {
65
+ readonly firsts: number[];
66
+ area: number;
67
+ /** Area-weighted sum of the triangle centroids; the centre once divided by `area`. */
68
+ readonly centre: Vector3;
69
+ /** Unweighted sum of the triangle centroids, the centre of an island whose area is zero. */
70
+ readonly plain: Vector3;
71
+ }
72
+
73
+ /** The index entries the geometry draws, [first, end), whole triangles. */
74
+ function drawnRange(geometry: BufferGeometry): [number, number] {
75
+ const count = (geometry.index as NonNullable<BufferGeometry["index"]>).count;
76
+ const first = Math.min(count, Math.max(0, geometry.drawRange.start));
77
+ const end = Math.min(count, first + geometry.drawRange.count);
78
+ return [first - (first % 3), end - ((end - first) % 3)];
79
+ }
80
+
81
+ /** Islands of the drawn triangles joined by shared vertex indices, with their area and centres. */
82
+ function cardIslands(
83
+ geometry: BufferGeometry,
84
+ first: number,
85
+ end: number,
86
+ ): Map<number, ICardIsland> {
87
+ const index = geometry.index as NonNullable<BufferGeometry["index"]>;
88
+ const position = geometry.getAttribute("position");
89
+ const parent = Int32Array.from({ length: position.count }, (_, i) => i);
90
+ const find = (vertex: number): number => {
91
+ let at = vertex;
92
+ while (parent[at] !== at) {
93
+ parent[at] = parent[parent[at] as number] as number;
94
+ at = parent[at] as number;
95
+ }
96
+ return at;
97
+ };
98
+ for (let t = first; t < end; t += 3) {
99
+ const root = find(index.getX(t));
100
+ parent[find(index.getX(t + 1))] = root;
101
+ parent[find(index.getX(t + 2))] = root;
102
+ }
103
+
104
+ const islands = new Map<number, ICardIsland>();
105
+ const a = new Vector3();
106
+ const b = new Vector3();
107
+ const c = new Vector3();
108
+ for (let t = first; t < end; t += 3) {
109
+ a.fromBufferAttribute(position, index.getX(t));
110
+ b.fromBufferAttribute(position, index.getX(t + 1));
111
+ c.fromBufferAttribute(position, index.getX(t + 2));
112
+ const centre = a.clone().add(b).add(c).divideScalar(3);
113
+ const area = b.sub(a).cross(c.sub(a)).length() / 2;
114
+ const root = find(index.getX(t));
115
+ const island = islands.get(root) ?? {
116
+ firsts: [],
117
+ area: 0,
118
+ centre: new Vector3(),
119
+ plain: new Vector3(),
120
+ };
121
+ island.firsts.push(t);
122
+ island.area += area;
123
+ island.centre.addScaledVector(centre, area);
124
+ island.plain.add(centre);
125
+ islands.set(root, island);
126
+ }
127
+
128
+ return islands;
129
+ }
130
+
131
+ /** A fixed-seed shuffle of the islands, taken until `target` triangles, and the scale that keeps the area. */
132
+ function pickCards(order: ICardIsland[], target: number): { kept: ICardIsland[]; scale: number } {
133
+ let seed = 0x9e3779b9;
134
+ for (let i = order.length - 1; i > 0; i--) {
135
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
136
+ const j = seed % (i + 1);
137
+ [order[i], order[j]] = [order[j] as ICardIsland, order[i] as ICardIsland];
138
+ }
139
+ const total = order.reduce((sum, island) => sum + island.area, 0);
140
+ const kept: ICardIsland[] = [];
141
+ let keptTriangles = 0;
142
+ let keptArea = 0;
143
+ for (const island of order) {
144
+ if (keptTriangles >= target) break;
145
+ kept.push(island);
146
+ keptTriangles += island.firsts.length;
147
+ keptArea += island.area;
148
+ }
149
+ const scale = keptArea > 0 ? Math.sqrt(total / keptArea) : 1;
150
+
151
+ return { kept, scale };
152
+ }