@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
@@ -359,16 +359,23 @@ var GPUParticles3D = class extends Sprite {
359
359
  if (camera !== void 0 && !this.castShadow && this.#authoredVisible) {
360
360
  const bounds = this.measuredBounds;
361
361
  if (bounds !== void 0 && this.#graceSeconds !== Number.POSITIVE_INFINITY) {
362
- if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
363
- this.updateWorldMatrix(true, false);
364
- viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
365
- frustum.setFromProjectionMatrix(
366
- viewProjection,
367
- camera.coordinateSystem,
368
- camera.reversedDepth
369
- );
370
- worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
371
- if (frustum.intersectsBox(worldBox)) this.#outsideSince = void 0;
362
+ const engine = this.__boundsInView;
363
+ let inView;
364
+ if (typeof engine === "function")
365
+ inView = engine.call(this, camera, bounds, this.#padding ?? Number.NaN);
366
+ else {
367
+ if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
368
+ this.updateWorldMatrix(true, false);
369
+ viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
370
+ frustum.setFromProjectionMatrix(
371
+ viewProjection,
372
+ camera.coordinateSystem,
373
+ camera.reversedDepth
374
+ );
375
+ worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
376
+ inView = frustum.intersectsBox(worldBox);
377
+ }
378
+ if (inView) this.#outsideSince = void 0;
372
379
  else {
373
380
  const now = simulatedSeconds ?? performance.now() / 1e3;
374
381
  this.#outsideSince ??= now;
@@ -1,9 +1,11 @@
1
- import { Vector3, Sphere, Mesh, BufferAttribute, BufferGeometry, InstancedMesh, Object3D, Group, Box3, Matrix4, Frustum } from 'three';
1
+ import { Vector3, Sphere, Frustum, Matrix4, Mesh, Quaternion, BufferAttribute, BufferGeometry, InstancedMesh, Object3D, Group, Box3 } from 'three';
2
2
 
3
3
  // src/clustered-mesh.ts
4
+ var NO_CLUSTER_GROUP = 4294967295;
4
5
  var MIN_DISTANCE = 1e-4;
5
6
  var DEFAULT_ERROR_PIXELS = 1;
6
7
  var RECUT_FRACTION = 1e-3;
8
+ var DEFAULT_VIEW_MARGIN = Math.PI / 90;
7
9
  function pixelsPerUnit(camera, viewportHeight) {
8
10
  const perspective = camera;
9
11
  if (perspective.isPerspectiveCamera !== true || perspective.fov === void 0)
@@ -50,6 +52,127 @@ function selectClusterCut(table, camera, scale, errorPixels, out) {
50
52
  }
51
53
  return selected;
52
54
  }
55
+ function worldFrustum(camera, into, scratch) {
56
+ return into.setFromProjectionMatrix(
57
+ scratch.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
58
+ );
59
+ }
60
+ function outsideFrustum(frustum, center, radius) {
61
+ for (const plane of frustum.planes) if (plane.distanceToPoint(center) < -radius) return true;
62
+ return false;
63
+ }
64
+ function clusterTableRadius(table) {
65
+ let radius = 0;
66
+ const { bounds } = table;
67
+ for (let at = 0; at + 3 < bounds.length; at += 4)
68
+ radius = Math.max(
69
+ radius,
70
+ Math.hypot(bounds[at], bounds[at + 1], bounds[at + 2]) + bounds[at + 3]
71
+ );
72
+ return radius;
73
+ }
74
+ var hierarchies = /* @__PURE__ */ new WeakMap();
75
+ function clusterHierarchy(table) {
76
+ let hierarchy = hierarchies.get(table);
77
+ if (hierarchy === void 0) {
78
+ hierarchy = buildClusterHierarchy(table);
79
+ hierarchies.set(table, hierarchy);
80
+ }
81
+ return hierarchy;
82
+ }
83
+ function buildClusterHierarchy(table) {
84
+ const groups = table.groups;
85
+ if (groups === void 0)
86
+ throw new Error(
87
+ "ClusteredMesh needs table.groups to prune its cut by view: re-bake the model with the current asset pipeline."
88
+ );
89
+ const clusters = table.ranges.length / 2;
90
+ let groupCount = 0;
91
+ let rootCount = 0;
92
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
93
+ const group = groups[cluster * 2];
94
+ const source = groups[cluster * 2 + 1];
95
+ if (source !== NO_CLUSTER_GROUP) groupCount = Math.max(groupCount, source + 1);
96
+ if (group === NO_CLUSTER_GROUP) rootCount += 1;
97
+ else groupCount = Math.max(groupCount, group + 1);
98
+ }
99
+ const starts = new Uint32Array(groupCount + 1);
100
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
101
+ const group = groups[cluster * 2];
102
+ if (group !== NO_CLUSTER_GROUP) starts[group + 1] = starts[group + 1] + 1;
103
+ }
104
+ for (let group = 0; group < groupCount; group += 1)
105
+ starts[group + 1] = starts[group + 1] + starts[group];
106
+ const children = new Uint32Array(clusters);
107
+ const cursor = starts.slice();
108
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
109
+ const group = groups[cluster * 2];
110
+ if (group === NO_CLUSTER_GROUP) continue;
111
+ children[cursor[group]] = cluster;
112
+ cursor[group] = cursor[group] + 1;
113
+ }
114
+ const roots = new Uint32Array(rootCount);
115
+ let written = 0;
116
+ for (let cluster = 0; cluster < clusters; cluster += 1)
117
+ if (groups[cluster * 2] === NO_CLUSTER_GROUP) {
118
+ roots[written] = cluster;
119
+ written += 1;
120
+ }
121
+ const reached = reachableClusters({ children, groups, roots, starts });
122
+ if (reached !== clusters)
123
+ throw new Error(
124
+ `TN_CLUSTER_DAG_UNREACHABLE: the cluster DAG reaches ${reached} of ${clusters} clusters from its ${rootCount} roots; re-bake the model with the current asset pipeline.`
125
+ );
126
+ return { children, groups, roots, starts };
127
+ }
128
+ function reachableClusters(hierarchy) {
129
+ const { children, groups, roots, starts } = hierarchy;
130
+ const seen = new Uint8Array(groups.length / 2);
131
+ const stack = [];
132
+ for (const root of roots) {
133
+ seen[root] = 1;
134
+ stack.push(root);
135
+ }
136
+ let reached = roots.length;
137
+ while (stack.length > 0) {
138
+ const parent = groups[stack.pop() * 2 + 1];
139
+ if (parent === NO_CLUSTER_GROUP) continue;
140
+ for (let slot = starts[parent]; slot < starts[parent + 1]; slot += 1) {
141
+ const child = children[slot];
142
+ if (seen[child] === 1) continue;
143
+ seen[child] = 1;
144
+ reached += 1;
145
+ stack.push(child);
146
+ }
147
+ }
148
+ return reached;
149
+ }
150
+ var ClusterView = class {
151
+ #frustum = new Frustum();
152
+ #viewMatrix = new Matrix4();
153
+ #eye = new Vector3();
154
+ #center = new Vector3();
155
+ #toWorld = new Matrix4();
156
+ #scale = 1;
157
+ #margin = 0;
158
+ /** Points this view at `camera`, kept valid for a turn of `margin` radians. */
159
+ setFromCamera(camera, margin) {
160
+ camera.updateWorldMatrix(true, false);
161
+ worldFrustum(camera, this.#frustum, this.#viewMatrix);
162
+ this.#eye.setFromMatrixPosition(camera.matrixWorld);
163
+ this.#margin = 2 * Math.sin(margin / 2);
164
+ }
165
+ /** The transform from the units the spheres are given in to world space. */
166
+ setTransform(matrixWorld) {
167
+ this.#toWorld.copy(matrixWorld);
168
+ this.#scale = matrixWorld.getMaxScaleOnAxis();
169
+ }
170
+ touches(x, y, z, radius) {
171
+ this.#center.set(x, y, z).applyMatrix4(this.#toWorld);
172
+ const slack = this.#margin === 0 ? 0 : this.#center.distanceTo(this.#eye) * this.#margin;
173
+ return !outsideFrustum(this.#frustum, this.#center, radius * this.#scale + slack);
174
+ }
175
+ };
53
176
  function finestIndexCount(table) {
54
177
  let count = 0;
55
178
  for (let cluster = 0; cluster * 2 < table.ranges.length; cluster += 1)
@@ -57,6 +180,77 @@ function finestIndexCount(table) {
57
180
  count += table.ranges[cluster * 2 + 1];
58
181
  return count;
59
182
  }
183
+ var ClusterWalk = class {
184
+ #table;
185
+ #hierarchy;
186
+ #stack;
187
+ /** Which cut last descended into each group, so a group shared by siblings is visited once. */
188
+ #stamps;
189
+ #generation = 0;
190
+ constructor(table, hierarchy = clusterHierarchy(table)) {
191
+ this.#table = table;
192
+ this.#hierarchy = hierarchy;
193
+ this.#stack = new Uint32Array(table.ranges.length / 2);
194
+ this.#stamps = new Int32Array(hierarchy.starts.length);
195
+ }
196
+ /** The cut, as cluster indices, written into `out`; returns how many were selected. */
197
+ select(camera, scale, errorPixels, view, out) {
198
+ const { children, groups, roots, starts } = this.#hierarchy;
199
+ const { errors, parentSpheres, sourceSpheres } = this.#table;
200
+ this.#generation += 1;
201
+ const generation = this.#generation;
202
+ let selected = 0;
203
+ let depth = 0;
204
+ for (let root = 0; root < roots.length; root += 1) {
205
+ this.#stack[depth] = roots[root];
206
+ depth += 1;
207
+ while (depth > 0) {
208
+ depth -= 1;
209
+ const cluster = this.#stack[depth];
210
+ const own = projectedError(
211
+ errors[cluster * 2],
212
+ sourceSpheres,
213
+ cluster,
214
+ camera,
215
+ scale
216
+ );
217
+ if (own <= errorPixels) {
218
+ const parent = projectedError(
219
+ errors[cluster * 2 + 1],
220
+ parentSpheres,
221
+ cluster,
222
+ camera,
223
+ scale
224
+ );
225
+ if (parent <= errorPixels) continue;
226
+ if (selected >= out.length)
227
+ throw new Error(
228
+ `ClusteredMesh selected more than the ${out.length} clusters level 0 holds; the table is inconsistent.`
229
+ );
230
+ out[selected] = cluster;
231
+ selected += 1;
232
+ continue;
233
+ }
234
+ const source = groups[cluster * 2 + 1];
235
+ if (source === NO_CLUSTER_GROUP) continue;
236
+ if (this.#stamps[source] === generation) continue;
237
+ this.#stamps[source] = generation;
238
+ if (!view.touches(
239
+ sourceSpheres[cluster * 4],
240
+ sourceSpheres[cluster * 4 + 1],
241
+ sourceSpheres[cluster * 4 + 2],
242
+ sourceSpheres[cluster * 4 + 3]
243
+ ))
244
+ continue;
245
+ for (let slot = starts[source]; slot < starts[source + 1]; slot += 1) {
246
+ this.#stack[depth] = children[slot];
247
+ depth += 1;
248
+ }
249
+ }
250
+ }
251
+ return selected;
252
+ }
253
+ };
60
254
  var ClusteredMesh = class _ClusteredMesh extends Mesh {
61
255
  /** The baked payload. The bake is the only thing that writes it; a copy takes the source's. */
62
256
  table;
@@ -64,20 +258,45 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
64
258
  errorPixels;
65
259
  /** Camera movement, in the mesh's own units, below which the previous cut is kept. */
66
260
  recutDistance;
261
+ /**
262
+ * Whether the cut skips clusters the camera cannot see. Writable — a mesh drawn through a second
263
+ * camera can turn it off, and {@link ClusteredMesh.viewCullReport} says what happened either way.
264
+ */
265
+ viewCull;
266
+ /** Camera turn, in radians, the kept cut stays valid for. Writable. */
267
+ viewMargin;
67
268
  #cut;
68
269
  #selection;
270
+ #walk;
271
+ #view = new ClusterView();
69
272
  #cameraLocal = new Vector3();
70
273
  #lastCut = new Vector3();
274
+ #rotation = new Quaternion();
275
+ #lastRotation = new Quaternion();
276
+ #frustum = new Frustum();
277
+ #viewMatrix = new Matrix4();
278
+ #sphereCenter = new Vector3();
71
279
  #drawnClusters = 0;
72
280
  #drawnIndices = 0;
281
+ #drawnClustersOutsideView = 0;
282
+ #drawnTrianglesOutsideView = 0;
283
+ #recutMs = 0;
284
+ #recutBytes = 0;
285
+ #recutCount = 0;
73
286
  #hasCut = false;
287
+ #pruned = false;
74
288
  #lastScale = 0;
75
289
  #lastErrorPixels = 0;
290
+ /** The projection the cut was pruned by: an aspect or zoom change keeps the pixel scale. */
291
+ #lastProjection = new Matrix4();
76
292
  constructor(geometry, surface, table, options = {}) {
77
293
  super(geometry, surface);
78
294
  assertTable(table);
79
295
  this.errorPixels = options.errorPixels ?? DEFAULT_ERROR_PIXELS;
80
296
  this.recutDistance = options.recutDistance ?? radiusOf(table) * RECUT_FRACTION;
297
+ this.viewCull = options.viewCull ?? true;
298
+ this.viewMargin = options.viewMargin ?? DEFAULT_VIEW_MARGIN;
299
+ assertViewMargin(this.viewMargin);
81
300
  this.#load(table, geometry);
82
301
  this.#compact(this.#finestCut());
83
302
  }
@@ -86,6 +305,12 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
86
305
  this.table = table;
87
306
  this.#cut = new Uint32Array(finestIndexCount(table));
88
307
  this.#selection = new Uint32Array(table.ranges.length / 2);
308
+ this.#drawnClustersOutsideView = 0;
309
+ this.#drawnTrianglesOutsideView = 0;
310
+ this.#recutMs = 0;
311
+ this.#recutBytes = 0;
312
+ this.#recutCount = 0;
313
+ this.#walk = table.groups === void 0 ? void 0 : new ClusterWalk(table);
89
314
  geometry.setIndex(new BufferAttribute(this.#cut, 1));
90
315
  }
91
316
  /**
@@ -99,7 +324,9 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
99
324
  clone(recursive = true) {
100
325
  return new _ClusteredMesh(withOwnCut(this.geometry), this.material, this.table, {
101
326
  errorPixels: this.errorPixels,
102
- recutDistance: this.recutDistance
327
+ recutDistance: this.recutDistance,
328
+ viewCull: this.viewCull,
329
+ viewMargin: this.viewMargin
103
330
  }).copy(this, recursive);
104
331
  }
105
332
  /**
@@ -119,6 +346,8 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
119
346
  this.geometry = geometry;
120
347
  this.errorPixels = source.errorPixels;
121
348
  this.recutDistance = source.recutDistance;
349
+ this.viewCull = source.viewCull;
350
+ this.viewMargin = source.viewMargin;
122
351
  this.#hasCut = false;
123
352
  this.#compact(this.#finestCut());
124
353
  return this;
@@ -141,6 +370,56 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
141
370
  get drawnTriangles() {
142
371
  return this.#drawnIndices / 3;
143
372
  }
373
+ /**
374
+ * Triangles in the current cut whose cluster bounds lie wholly outside the view volume.
375
+ *
376
+ * A measurement, not a cull: PRD-600 records this number before and after the walk learns to skip
377
+ * what the view does not hold. It is taken when the cut is taken, so a still camera reads the
378
+ * number its standing cut was made with.
379
+ */
380
+ get drawnTrianglesOutsideView() {
381
+ return this.#drawnTrianglesOutsideView;
382
+ }
383
+ /** Clusters in the current cut whose bounds lie wholly outside the view volume. */
384
+ get drawnClustersOutsideView() {
385
+ return this.#drawnClustersOutsideView;
386
+ }
387
+ /**
388
+ * Milliseconds the last re-cut took, from choosing the cut to the index buffer being marked for
389
+ * upload.
390
+ *
391
+ * The whole re-cut, because that is the cost a game pays for turning the camera and the number
392
+ * `viewMargin` is chosen against. The bytes below are only the compact's copy, so the throughput
393
+ * this divides out is the pessimistic one.
394
+ */
395
+ get recutMs() {
396
+ return this.#recutMs;
397
+ }
398
+ /** Index bytes the last re-cut copied and uploaded. */
399
+ get recutBytes() {
400
+ return this.#recutBytes;
401
+ }
402
+ /** Throughput of the last re-cut's copy of the cut, in megabytes per second. */
403
+ get recutMegabytesPerSecond() {
404
+ return this.#recutMs > 0 ? this.#recutBytes / 1e3 / this.#recutMs : 0;
405
+ }
406
+ /** How many re-cuts this mesh has taken, so a reader can tell a fresh one from a stale reading. */
407
+ get recutCount() {
408
+ return this.#recutCount;
409
+ }
410
+ /**
411
+ * What this mesh does about clusters outside the view, and why.
412
+ *
413
+ * `"on"` when the cut is pruned, and a reason when it is not — a mesh that silently kept drawing
414
+ * what nobody can see would be a performance bug with no symptom, and one that silently dropped
415
+ * what a second camera can see would be a hole with no cause.
416
+ */
417
+ get viewCullReport() {
418
+ if (!this.viewCull) return "off (viewCull = false)";
419
+ if (this.castShadow) return "off (castShadow)";
420
+ if (this.#walk === void 0) return "off (no clusterGroups)";
421
+ return "on";
422
+ }
144
423
  /**
145
424
  * Chooses this frame's cut and compacts it into one index range.
146
425
  *
@@ -157,18 +436,71 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
157
436
  camera.updateWorldMatrix(true, false);
158
437
  this.#cameraLocal.setFromMatrixPosition(camera.matrixWorld);
159
438
  this.worldToLocal(this.#cameraLocal);
439
+ camera.getWorldQuaternion(this.#rotation);
440
+ const pruned = this.viewCull && !this.castShadow && this.#walk !== void 0;
160
441
  const moved = this.#cameraLocal.distanceTo(this.#lastCut);
161
- const settled = this.#hasCut && moved <= this.recutDistance && scale === this.#lastScale && this.errorPixels === this.#lastErrorPixels;
442
+ const settled = this.#hasCut && pruned === this.#pruned && moved <= this.recutDistance && this.#rotation.angleTo(this.#lastRotation) <= this.viewMargin && scale === this.#lastScale && this.errorPixels === this.#lastErrorPixels && camera.projectionMatrix.equals(this.#lastProjection);
162
443
  if (settled) return this.drawnTriangles;
163
444
  this.#lastCut.copy(this.#cameraLocal);
445
+ this.#lastRotation.copy(this.#rotation);
164
446
  this.#lastScale = scale;
165
447
  this.#lastErrorPixels = this.errorPixels;
448
+ this.#lastProjection.copy(camera.projectionMatrix);
449
+ this.#pruned = pruned;
166
450
  this.#hasCut = true;
167
- this.#compact(
168
- selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection)
169
- );
451
+ const started = performance.now();
452
+ const walk = this.#walk;
453
+ if (pruned && walk !== void 0) {
454
+ this.#view.setFromCamera(camera, this.viewMargin);
455
+ this.#view.setTransform(this.matrixWorld);
456
+ this.#compact(
457
+ walk.select(this.#cameraLocal, scale, this.errorPixels, this.#view, this.#selection)
458
+ );
459
+ } else {
460
+ this.#compact(
461
+ selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection)
462
+ );
463
+ }
464
+ this.#recutMs = performance.now() - started;
465
+ this.#recutBytes = this.#drawnIndices * 4;
466
+ this.#recutCount += 1;
467
+ this.#countOutsideView(camera);
170
468
  return this.drawnTriangles;
171
469
  }
470
+ /**
471
+ * Records how much of this cut the view volume does not hold.
472
+ *
473
+ * Read-only and taken when a cut is taken, so it costs one sphere test per selected cluster on the
474
+ * re-cut path and nothing at all on a frame the cut settled. The mesh's own scale is folded into
475
+ * the radius the way three folds it into its own cull, so a scaled placement is measured as it
476
+ * draws.
477
+ */
478
+ #countOutsideView(camera) {
479
+ const frustum = worldFrustum(camera, this.#frustum, this.#viewMatrix);
480
+ const scale = this.matrixWorld.getMaxScaleOnAxis();
481
+ const world = this.matrixWorld;
482
+ let clusters = 0;
483
+ let indices = 0;
484
+ for (let slot = 0; slot < this.#drawnClusters; slot += 1) {
485
+ const cluster = this.#selection[slot];
486
+ const count = this.table.ranges[cluster * 2 + 1];
487
+ this.#sphereCenter.set(
488
+ this.table.bounds[cluster * 4],
489
+ this.table.bounds[cluster * 4 + 1],
490
+ this.table.bounds[cluster * 4 + 2]
491
+ ).applyMatrix4(world);
492
+ if (!outsideFrustum(
493
+ frustum,
494
+ this.#sphereCenter,
495
+ this.table.bounds[cluster * 4 + 3] * scale
496
+ ))
497
+ continue;
498
+ clusters += 1;
499
+ indices += count;
500
+ }
501
+ this.#drawnClustersOutsideView = clusters;
502
+ this.#drawnTrianglesOutsideView = indices / 3;
503
+ }
172
504
  #compact(selected) {
173
505
  let cursor = 0;
174
506
  for (let slot = 0; slot < selected; slot += 1) {
@@ -199,10 +531,13 @@ function withOwnCut(geometry) {
199
531
  return shell;
200
532
  }
201
533
  function radiusOf(table) {
202
- let radius = 0;
203
- for (let cluster = 0; cluster * 4 < table.bounds.length; cluster += 1)
204
- radius = Math.max(radius, table.bounds[cluster * 4 + 3]);
205
- return radius;
534
+ return clusterTableRadius(table);
535
+ }
536
+ function assertViewMargin(margin) {
537
+ if (!Number.isFinite(margin) || margin < 0 || margin >= Math.PI / 2)
538
+ throw new Error(
539
+ `ClusteredMesh viewMargin must be a turn in radians below a quarter circle, got ${margin}.`
540
+ );
206
541
  }
207
542
  function assertTable(table) {
208
543
  const clusters = table.ranges.length / 2;
@@ -222,6 +557,10 @@ function assertTable(table) {
222
557
  `ClusteredMesh table.${name} holds ${array.length} values for ${clusters} clusters; it needs ${clusters * width}.`
223
558
  );
224
559
  }
560
+ if (table.groups !== void 0 && table.groups.length !== clusters * 2)
561
+ throw new Error(
562
+ `ClusteredMesh table.groups holds ${table.groups.length} values for ${clusters} clusters; it needs ${clusters * 2}.`
563
+ );
225
564
  for (let cluster = 0; cluster < clusters; cluster += 1) {
226
565
  const start = table.ranges[cluster * 2];
227
566
  const count = table.ranges[cluster * 2 + 1];
@@ -242,6 +581,7 @@ var TABLE_FIELDS = [
242
581
  "clusterBounds",
243
582
  "clusterCones",
244
583
  "clusterErrors",
584
+ "clusterGroups",
245
585
  "clusterParentSpheres",
246
586
  "clusterRanges",
247
587
  "clusterSourceSpheres",
@@ -254,10 +594,11 @@ async function readTable(parser, def) {
254
594
  `TN_VIRTUAL_GEOMETRY_INCOMPLETE: the ${TN_VIRTUAL_GEOMETRY} payload is missing ${missing.join(", ")}; re-bake the model with the current asset pipeline.`
255
595
  );
256
596
  const accessor = async (index) => (await parser.getDependency("accessor", index)).array;
257
- const [bounds, cones, errors, parentSpheres, ranges, sourceSpheres, indices] = await Promise.all([
597
+ const [bounds, cones, errors, groups, parentSpheres, ranges, sourceSpheres, indices] = await Promise.all([
258
598
  accessor(def.clusterBounds),
259
599
  accessor(def.clusterCones),
260
600
  accessor(def.clusterErrors),
601
+ accessor(def.clusterGroups),
261
602
  accessor(def.clusterParentSpheres),
262
603
  accessor(def.clusterRanges),
263
604
  accessor(def.clusterSourceSpheres),
@@ -267,6 +608,7 @@ async function readTable(parser, def) {
267
608
  bounds: typedFloat(bounds),
268
609
  cones: typedFloat(cones),
269
610
  errors: typedFloat(errors),
611
+ groups: typedUint(groups),
270
612
  indices: typedUint(indices),
271
613
  parentSpheres: typedFloat(parentSpheres),
272
614
  ranges: typedUint(ranges),
@@ -412,11 +754,21 @@ function biasedLodDistance(distance) {
412
754
  return distance * lodBiasState.value;
413
755
  }
414
756
  var nearest = new Vector3();
757
+ var LOD_NEAR_PLANE = 0;
415
758
  function conservativeViewDepth(camera, center, radius, nearPlane) {
416
759
  nearest.copy(center).applyMatrix4(camera.matrixWorldInverse);
417
760
  const depth = -nearest.z - Math.max(0, radius);
418
761
  return { depth, degenerate: depth <= nearPlane };
419
762
  }
763
+ function selectLodFor(camera, sphere, nearPlane) {
764
+ const { depth, degenerate } = conservativeViewDepth(
765
+ camera,
766
+ sphere.center,
767
+ sphere.radius,
768
+ nearPlane
769
+ );
770
+ return { biased: biasedLodDistance(depth), degenerate, depth };
771
+ }
420
772
  function worldSphere(local, object, out = new Sphere().copy(local), matrix = object.matrixWorld) {
421
773
  out.center.copy(local.center).applyMatrix4(matrix);
422
774
  const scale = matrix.getMaxScaleOnAxis();
@@ -492,9 +844,15 @@ async function readPendingLevels(parser, def) {
492
844
  }
493
845
  return { absoluteErrors, indices: resolved, lod0Triangles: def.lod0Triangles };
494
846
  }
847
+ var levelTriangles = /* @__PURE__ */ new WeakMap();
495
848
  function drawTriangles(geometry) {
496
- const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
497
- return Math.floor(drawn / 3);
849
+ let triangles = levelTriangles.get(geometry);
850
+ if (triangles === void 0) {
851
+ const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
852
+ triangles = Math.floor(drawn / 3);
853
+ levelTriangles.set(geometry, triangles);
854
+ }
855
+ return triangles;
498
856
  }
499
857
  var ModelLod = class {
500
858
  #mesh;
@@ -533,16 +891,15 @@ var ModelLod = class {
533
891
  return;
534
892
  }
535
893
  const world = worldSphere(this.#chain.sphere, this.#mesh, void 0, this.#mesh.matrixWorld);
536
- const { depth, degenerate } = conservativeViewDepth(
894
+ const { biased, degenerate } = selectLodFor(
537
895
  camera,
538
- world.center,
539
- world.radius,
896
+ world,
540
897
  camera.near ?? 0
541
898
  );
542
899
  const view = {
543
900
  camera,
544
901
  degenerate,
545
- depth: biasedLodDistance(depth),
902
+ depth: biased,
546
903
  viewportHeight
547
904
  };
548
905
  const index = selectLodLevel(
@@ -568,10 +925,9 @@ var ModelLod = class {
568
925
  const container = this.#container;
569
926
  if (container === null) return;
570
927
  const world = worldSphere(rung.sphere, container, void 0, container.matrixWorld);
571
- const { depth, degenerate } = conservativeViewDepth(
928
+ const { biased, degenerate } = selectLodFor(
572
929
  camera,
573
- world.center,
574
- world.radius,
930
+ world,
575
931
  camera.near ?? 0
576
932
  );
577
933
  const errors = [...this.#chain.errors, rung.error];
@@ -579,7 +935,7 @@ var ModelLod = class {
579
935
  const view = {
580
936
  camera,
581
937
  degenerate,
582
- depth: biasedLodDistance(depth),
938
+ depth: biased,
583
939
  viewportHeight
584
940
  };
585
941
  const index = selectLodLevel(
@@ -856,7 +1212,27 @@ function registerModelLodController(mesh, controller) {
856
1212
  function isChained(object) {
857
1213
  const mesh = object;
858
1214
  const geometry = mesh.geometry;
859
- return mesh.isMesh === true && geometry !== void 0 && chains.has(geometry);
1215
+ return mesh.isMesh === true && geometry !== void 0 && (chains.has(geometry) || streaming.has(geometry));
1216
+ }
1217
+ var streaming = /* @__PURE__ */ new WeakSet();
1218
+ function markStreamedGeometry(coarse) {
1219
+ streaming.add(coarse);
1220
+ }
1221
+ function isStreamedGeometry(geometry) {
1222
+ return streaming.has(geometry);
1223
+ }
1224
+ function upgradeStreamedGeometry(coarse, full) {
1225
+ const attributes = full.attributes;
1226
+ for (const name of Object.keys(coarse.attributes))
1227
+ if (attributes[name] === void 0) coarse.deleteAttribute(name);
1228
+ for (const [name, attribute] of Object.entries(attributes)) coarse.setAttribute(name, attribute);
1229
+ coarse.setIndex(full.index);
1230
+ coarse.computeBoundingBox();
1231
+ coarse.computeBoundingSphere();
1232
+ levelTriangles.delete(coarse);
1233
+ const registered = chains.get(full);
1234
+ if (registered !== void 0) chains.set(coarse, registered);
1235
+ streaming.delete(coarse);
860
1236
  }
861
1237
  function controllerFor(mesh) {
862
1238
  const existing = controllers.get(mesh);
@@ -1211,7 +1587,7 @@ function updateModelLods(root, camera, viewportHeight) {
1211
1587
  for (const mesh of tracking.items) {
1212
1588
  const entry = controllerFor(mesh);
1213
1589
  if (entry === void 0) {
1214
- tracking.items.delete(mesh);
1590
+ if (!streaming.has(mesh.geometry)) tracking.items.delete(mesh);
1215
1591
  continue;
1216
1592
  }
1217
1593
  entry.update(camera, viewportHeight);
@@ -1314,12 +1690,12 @@ function projectedCenter(centre, camera, viewportWidth, viewportHeight) {
1314
1690
  function projectedSize(sphere, camera, viewportHeight) {
1315
1691
  if (!(viewportHeight > 0)) return void 0;
1316
1692
  const like = camera;
1317
- const near = like.near ?? 0.1;
1693
+ const near = like.near ?? LOD_NEAR_PLANE;
1318
1694
  const distance = centreScratch.copy(sphere.center).distanceTo(camera.getWorldPosition(new Vector3()));
1319
1695
  let depth;
1320
1696
  let degenerate;
1321
1697
  try {
1322
- const view = conservativeViewDepth(camera, sphere.center, sphere.radius, near);
1698
+ const view = selectLodFor(camera, sphere, near);
1323
1699
  depth = view.depth;
1324
1700
  degenerate = view.degenerate;
1325
1701
  } catch {
@@ -1344,6 +1720,7 @@ function rendererBackendIdentity(raw) {
1344
1720
  var GeometryCapture = class {
1345
1721
  #pending;
1346
1722
  #armed;
1723
+ #deferredPasses;
1347
1724
  /**
1348
1725
  * Arms one capture and answers its report. A malformed request throws rather than quietly
1349
1726
  * choosing a scope the caller did not ask for. Concurrent requests coalesce onto one frame.
@@ -1436,7 +1813,12 @@ var GeometryCapture = class {
1436
1813
  * Ends the frame: removes every hook, reconciles the rows against the measured pass totals and
1437
1814
  * answers the waiting request.
1438
1815
  */
1439
- finishFrame(passes) {
1816
+ finishFrame(passes, options) {
1817
+ if (options?.drawsAfterFrame === true && this.#pending !== void 0) {
1818
+ this.#deferredPasses = passes;
1819
+ return;
1820
+ }
1821
+ this.#deferredPasses = void 0;
1440
1822
  const armed = this.#armed;
1441
1823
  const pending = this.#pending;
1442
1824
  this.#restore();
@@ -1445,8 +1827,14 @@ var GeometryCapture = class {
1445
1827
  this.#pending = void 0;
1446
1828
  pending.settle(buildReport(armed, passes, pending));
1447
1829
  }
1830
+ /** Answers a capture whose frame a host drew after the frame callback. A no-op otherwise. */
1831
+ settleDeferred() {
1832
+ const passes = this.#deferredPasses;
1833
+ if (passes !== void 0) this.finishFrame(passes);
1834
+ }
1448
1835
  /** Drops a pending capture and every hook. A scene exit is not a reason to report a stale frame. */
1449
1836
  cancel(reason) {
1837
+ this.#deferredPasses = void 0;
1450
1838
  const pending = this.#pending;
1451
1839
  this.#restore();
1452
1840
  this.#pending = void 0;
@@ -1846,4 +2234,4 @@ function reconcile(passes, drafts) {
1846
2234
  });
1847
2235
  }
1848
2236
 
1849
- export { ClusteredMesh, DISCRETE_LOD_DEFAULT_ERROR_PIXELS, DISCRETE_LOD_DEFAULT_HYSTERESIS, DiscreteLodPlugin, GEOMETRY_ASSET_KEY, GEOMETRY_CAPTURE_CAPABILITY, GEOMETRY_CAPTURE_DEFAULT_LIMIT, GEOMETRY_CAPTURE_MAX_LIMIT, GEOMETRY_CAPTURE_SORTS, GEOMETRY_CAPTURE_TIMEOUT_MS, GEOMETRY_CAPTURE_WALK_CAP, GeometryCapture, TN_DISCRETE_LOD, TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin, baseGeometryOf, biasedLodDistance, conservativeViewDepth, isEngineRenderHook, isLodJoinProxy, lodChainOf, lodPixelScale, markEngineRenderHook, pixelsPerUnit, projectedLodError, registerModelLodController, rendererBackendIdentity, selectClusterCut, selectLodLevel, setLodBias, setModelLodLayers, updateClusteredMeshes, updateModelLods, worldSphere };
2237
+ export { ClusterView, ClusteredMesh, DEFAULT_VIEW_MARGIN, DISCRETE_LOD_DEFAULT_ERROR_PIXELS, DISCRETE_LOD_DEFAULT_HYSTERESIS, DiscreteLodPlugin, GEOMETRY_ASSET_KEY, GEOMETRY_CAPTURE_CAPABILITY, GEOMETRY_CAPTURE_DEFAULT_LIMIT, GEOMETRY_CAPTURE_MAX_LIMIT, GEOMETRY_CAPTURE_SORTS, GEOMETRY_CAPTURE_TIMEOUT_MS, GEOMETRY_CAPTURE_WALK_CAP, GeometryCapture, LOD_NEAR_PLANE, TN_DISCRETE_LOD, TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin, assertViewMargin, baseGeometryOf, biasedLodDistance, clusterTableRadius, isEngineRenderHook, isLodJoinProxy, isStreamedGeometry, lodChainOf, lodPixelScale, markEngineRenderHook, markStreamedGeometry, outsideFrustum, pixelsPerUnit, projectedLodError, registerModelLodController, rendererBackendIdentity, selectClusterCut, selectLodFor, selectLodLevel, setLodBias, setModelLodLayers, updateClusteredMeshes, updateModelLods, upgradeStreamedGeometry, worldFrustum, worldSphere };