@threenative/core 0.3.13 → 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 (50) hide show
  1. package/capabilities.json +299 -10
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-DIPIJICH.js → chunk-GEMQJBY4.js} +70 -18
  4. package/dist/{chunk-EFWZWLPY.js → chunk-QAMSM3Z5.js} +354 -12
  5. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  6. package/dist/{chunk-EEABDLUC.js → chunk-VBBYWGAT.js} +2 -2
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/index.d.ts +605 -7
  9. package/dist/index.js +1973 -609
  10. package/dist/playtest.js +3 -3
  11. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  12. package/dist/render-environment.d.ts +1 -1
  13. package/dist/ui-layer.js +2 -2
  14. package/dist/worker.js +2 -2
  15. package/dist/world.d.ts +13 -3
  16. package/dist/world.js +179 -36
  17. package/mcp/animation-server.mjs +1 -1
  18. package/mcp/engine-server.mjs +32 -6
  19. package/mcp/servers.mjs +3 -3
  20. package/package.json +5 -5
  21. package/scripts/ensure-mcp.mjs +6 -1
  22. package/src/clustered-batch.ts +146 -3
  23. package/src/clustered-mesh.ts +548 -20
  24. package/src/debug.ts +16 -0
  25. package/src/displaced-surface.ts +428 -0
  26. package/src/frame-budget.ts +16 -0
  27. package/src/generated/console-markers.ts +1 -0
  28. package/src/grass-field.ts +628 -0
  29. package/src/index.ts +112 -0
  30. package/src/render/material-key.ts +21 -1
  31. package/src/render/screen-probe-gather.ts +303 -0
  32. package/src/render/short-range-ao.ts +274 -0
  33. package/src/render/world-impostor-surface.ts +98 -3
  34. package/src/render-camera-cull.ts +9 -3
  35. package/src/renderer.ts +26 -4
  36. package/src/scatter-field.ts +496 -0
  37. package/src/startup-offscreen-bytes.ts +11 -5
  38. package/src/state.ts +16 -3
  39. package/src/static-transform.ts +75 -6
  40. package/src/tile-ring.ts +294 -0
  41. package/src/version.ts +1 -1
  42. package/src/warmup.ts +15 -2
  43. package/src/world-cell-batches.ts +4 -0
  44. package/src/world-cell-data.ts +7 -0
  45. package/src/world-cell-models.ts +36 -8
  46. package/src/world-cell-render-gpu-dress.ts +4 -2
  47. package/src/world-cell-render-util.ts +2 -2
  48. package/src/world-cells.ts +1 -1
  49. package/src/world-river-ribbon.ts +13 -22
  50. package/src/world-water-bodies.ts +113 -3
@@ -1,4 +1,14 @@
1
- import { BufferAttribute, BufferGeometry, type Camera, type Material, Mesh, Vector3 } from "three";
1
+ import {
2
+ BufferAttribute,
3
+ BufferGeometry,
4
+ type Camera,
5
+ Frustum,
6
+ type Material,
7
+ Matrix4,
8
+ Mesh,
9
+ Quaternion,
10
+ Vector3,
11
+ } from "three";
2
12
 
3
13
  /**
4
14
  * A mesh that draws only the clusters this camera can resolve.
@@ -17,12 +27,26 @@ import { BufferAttribute, BufferGeometry, type Camera, type Material, Mesh, Vect
17
27
 
18
28
  /** The baked payload, exactly as `TN_virtual_geometry` stores it. */
19
29
  export interface IClusterTable {
20
- /** Per cluster, `[centreX, centreY, centreZ, radius]`. Culling reads it; PRD-283 will. */
30
+ /**
31
+ * Per cluster, `[centreX, centreY, centreZ, radius]`, in the mesh's own space.
32
+ *
33
+ * "The mesh's own space" is the one its `POSITION` attribute is in, which is why the asset pass
34
+ * never quantizes a primitive that carries this table: quantization keeps the drawn positions but
35
+ * moves the space out from under them, and every sphere below is tested against a transform.
36
+ */
21
37
  readonly bounds: Float32Array;
22
- /** Per cluster, `[axisX, axisY, axisZ, cutoff]`. */
38
+ /** Per cluster, `[axisX, axisY, axisZ, cutoff]`. Read into a field nothing uses yet. */
23
39
  readonly cones: Float32Array;
24
40
  /** Per cluster, `[ownError, parentError]`, in the mesh's own units. */
25
41
  readonly errors: Float32Array;
42
+ /**
43
+ * Per cluster, `[group, sourceGroup]`, or absent on a table built by hand.
44
+ *
45
+ * `group` is the group that folded this cluster one level up (`NO_GROUP` when nothing above
46
+ * replaces it), and `sourceGroup` is the group whose simplification produced it. Inverting `group`
47
+ * gives the children of every group, which is the descent a view-pruned cut walks.
48
+ */
49
+ readonly groups?: Uint32Array;
26
50
  /** Cluster-ordered triangles for every level, indexing the geometry's vertex buffer. */
27
51
  readonly indices: Uint32Array;
28
52
  /** Per cluster, the sphere `parentError` is projected through. */
@@ -33,6 +57,9 @@ export interface IClusterTable {
33
57
  readonly sourceSpheres: Float32Array;
34
58
  }
35
59
 
60
+ /** Written into `clusterGroups` where a cluster has no group on that side. */
61
+ export const NO_CLUSTER_GROUP = 0xffffffff;
62
+
36
63
  export interface IClusteredMeshOptions {
37
64
  /**
38
65
  * Screen-space error a cluster may show, in pixels, before its children are drawn instead.
@@ -51,6 +78,24 @@ export interface IClusteredMeshOptions {
51
78
  * radius.
52
79
  */
53
80
  readonly recutDistance?: number;
81
+ /**
82
+ * Whether clusters the camera cannot see are skipped.
83
+ *
84
+ * On by default, because a cluster behind the camera is a cluster nobody can resolve. A mesh that
85
+ * casts shadows keeps the unpruned cut until shadows have a cut of their own, and a game that
86
+ * renders the mesh through a second camera (a mirror, a portal) can turn it off; either way the
87
+ * mesh reports what it did through {@link ClusteredMesh.viewCullReport}.
88
+ */
89
+ readonly viewCull?: boolean;
90
+ /**
91
+ * How far the camera may turn, in radians, before the cut is taken again.
92
+ *
93
+ * A cut pruned by the view is only valid for the view it was taken with, so the frustum it was
94
+ * pruned by is widened by this angle and the cut is kept until the camera turns past it. It is the
95
+ * one constant this technique needs: too small re-cuts on every nudge, too large draws a sliver of
96
+ * clusters that turning would reveal. Default {@link DEFAULT_VIEW_MARGIN}.
97
+ */
98
+ readonly viewMargin?: number;
54
99
  }
55
100
 
56
101
  /** A cluster nearer than this to the camera is treated as this far away, rather than dividing by zero. */
@@ -58,6 +103,15 @@ const MIN_DISTANCE = 1e-4;
58
103
 
59
104
  const DEFAULT_ERROR_PIXELS = 1;
60
105
  const RECUT_FRACTION = 0.001;
106
+ /**
107
+ * Radians the camera may turn before a view-pruned cut is taken again.
108
+ *
109
+ * Chosen from the measured re-cut cost on the quarry route: a re-cut copies a cut of a few hundred
110
+ * thousand indices and costs well under a millisecond there, so two degrees buys steadiness a nudge
111
+ * cannot spend and still re-cuts inside a normal look-around. Raising it trades a few clusters of
112
+ * overdraw for fewer re-cuts; the game can set its own.
113
+ */
114
+ export const DEFAULT_VIEW_MARGIN = Math.PI / 90;
61
115
 
62
116
  /**
63
117
  * The two things a screen-space error needs from a camera.
@@ -146,6 +200,213 @@ export function selectClusterCut(
146
200
  return selected;
147
201
  }
148
202
 
203
+ /**
204
+ * The six planes of a camera's view volume, in world space.
205
+ *
206
+ * The camera's own world matrix has to be current for this to mean anything, which is why every
207
+ * caller here walks the camera first. `projectionMatrix` is read as the renderer left it: rebuilding
208
+ * it here would silently disagree with the frame that is about to be drawn.
209
+ */
210
+ export function worldFrustum(camera: Camera, into: Frustum, scratch: Matrix4): Frustum {
211
+ return into.setFromProjectionMatrix(
212
+ scratch.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
213
+ );
214
+ }
215
+
216
+ /**
217
+ * Whether a sphere lies wholly outside the view volume.
218
+ *
219
+ * Every plane has to be crossed for the sphere to be out: a sphere that is behind the near plane is
220
+ * outside it, and one that is merely to the left of the left plane and also past the far plane is
221
+ * still outside. This is the read-only question PRD-600's counters ask — nothing is culled by it.
222
+ */
223
+ export function outsideFrustum(frustum: Frustum, center: Vector3, radius: number): boolean {
224
+ for (const plane of frustum.planes) if (plane.distanceToPoint(center) < -radius) return true;
225
+ return false;
226
+ }
227
+
228
+ /**
229
+ * Radius of the sphere on the mesh's origin that holds every cluster's bounds, in the mesh's own
230
+ * units. A body pivoted off its centre (a rock on its base) reaches past its largest cluster.
231
+ */
232
+ export function clusterTableRadius(table: IClusterTable): number {
233
+ let radius = 0;
234
+ const { bounds } = table;
235
+ for (let at = 0; at + 3 < bounds.length; at += 4)
236
+ radius = Math.max(
237
+ radius,
238
+ Math.hypot(bounds[at] as number, bounds[at + 1] as number, bounds[at + 2] as number) +
239
+ (bounds[at + 3] as number),
240
+ );
241
+ return radius;
242
+ }
243
+
244
+ /**
245
+ * The child lists a view-pruned cut descends by, built once from the bake's `clusterGroups`.
246
+ *
247
+ * A cluster's own error says whether it may draw; whether *its* children must be looked at is a
248
+ * different question, and answering it needs the DAG's edges rather than its errors. The edges are
249
+ * the inverse of `clusterGroups`' first value: every cluster folded into group *g* is one of the
250
+ * clusters *g* simplified, and a cluster's finer clusters are the ones the group that produced it
251
+ * folded.
252
+ */
253
+ export interface IClusterHierarchy {
254
+ /** The clusters nothing above replaces — where a cut starts, and the only place it can. */
255
+ readonly roots: Uint32Array;
256
+ /** Per group *g*, its children are `children[starts[g]]` up to `children[starts[g + 1]]`. */
257
+ readonly starts: Uint32Array;
258
+ readonly children: Uint32Array;
259
+ /** Per cluster, `[group, sourceGroup]`, exactly as the bake wrote them. */
260
+ readonly groups: Uint32Array;
261
+ }
262
+
263
+ /**
264
+ * Builds the descent lists, and refuses a table whose edges do not reach every cluster.
265
+ *
266
+ * Fails closed like every other table check here: a DAG whose edges strand a cluster would draw a
267
+ * hole in the mesh the moment the walk used it, and a hole that only appears when a camera turns is
268
+ * the worst kind to find. The bake guarantees the reachability this checks for.
269
+ */
270
+ /** One hierarchy per table: it is a pure function of the bake, and every clone walks the same one. */
271
+ const hierarchies = new WeakMap<IClusterTable, IClusterHierarchy>();
272
+
273
+ export function clusterHierarchy(table: IClusterTable): IClusterHierarchy {
274
+ let hierarchy = hierarchies.get(table);
275
+ if (hierarchy === undefined) {
276
+ hierarchy = buildClusterHierarchy(table);
277
+ hierarchies.set(table, hierarchy);
278
+ }
279
+ return hierarchy;
280
+ }
281
+
282
+ function buildClusterHierarchy(table: IClusterTable): IClusterHierarchy {
283
+ const groups = table.groups;
284
+ if (groups === undefined)
285
+ throw new Error(
286
+ "ClusteredMesh needs table.groups to prune its cut by view: re-bake the model with the current asset pipeline.",
287
+ );
288
+ const clusters = table.ranges.length / 2;
289
+ let groupCount = 0;
290
+ let rootCount = 0;
291
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
292
+ const group = groups[cluster * 2] as number;
293
+ const source = groups[cluster * 2 + 1] as number;
294
+ if (source !== NO_CLUSTER_GROUP) groupCount = Math.max(groupCount, source + 1);
295
+ if (group === NO_CLUSTER_GROUP) rootCount += 1;
296
+ else groupCount = Math.max(groupCount, group + 1);
297
+ }
298
+ const starts = new Uint32Array(groupCount + 1);
299
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
300
+ const group = groups[cluster * 2] as number;
301
+ if (group !== NO_CLUSTER_GROUP) starts[group + 1] = (starts[group + 1] as number) + 1;
302
+ }
303
+ for (let group = 0; group < groupCount; group += 1)
304
+ starts[group + 1] = (starts[group + 1] as number) + (starts[group] as number);
305
+ const children = new Uint32Array(clusters);
306
+ const cursor = starts.slice();
307
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
308
+ const group = groups[cluster * 2] as number;
309
+ if (group === NO_CLUSTER_GROUP) continue;
310
+ children[cursor[group] as number] = cluster;
311
+ cursor[group] = (cursor[group] as number) + 1;
312
+ }
313
+ const roots = new Uint32Array(rootCount);
314
+ let written = 0;
315
+ for (let cluster = 0; cluster < clusters; cluster += 1)
316
+ if ((groups[cluster * 2] as number) === NO_CLUSTER_GROUP) {
317
+ roots[written] = cluster;
318
+ written += 1;
319
+ }
320
+ // Every cluster has to be under a root, or a cut taken by the walk would silently miss it.
321
+ const reached = reachableClusters({ children, groups, roots, starts });
322
+ if (reached !== clusters)
323
+ throw new Error(
324
+ `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.`,
325
+ );
326
+ return { children, groups, roots, starts };
327
+ }
328
+
329
+ /** How many clusters the roots reach by descending the produced-by edges. */
330
+ function reachableClusters(hierarchy: IClusterHierarchy): number {
331
+ const { children, groups, roots, starts } = hierarchy;
332
+ const seen = new Uint8Array(groups.length / 2);
333
+ const stack: number[] = [];
334
+ for (const root of roots) {
335
+ seen[root] = 1;
336
+ stack.push(root);
337
+ }
338
+ let reached = roots.length;
339
+ while (stack.length > 0) {
340
+ const parent = groups[(stack.pop() as number) * 2 + 1] as number;
341
+ if (parent === NO_CLUSTER_GROUP) continue;
342
+ for (let slot = starts[parent] as number; slot < (starts[parent + 1] as number); slot += 1) {
343
+ const child = children[slot] as number;
344
+ if (seen[child] === 1) continue;
345
+ seen[child] = 1;
346
+ reached += 1;
347
+ stack.push(child);
348
+ }
349
+ }
350
+ return reached;
351
+ }
352
+
353
+ /**
354
+ * What a pruned cut is allowed to skip: one sphere against the view.
355
+ *
356
+ * Structural rather than a class, so a spec can hand the walk a plane it decides for itself.
357
+ */
358
+ export interface IClusterView {
359
+ /**
360
+ * Whether anything inside this sphere — in the mesh's own units — could still touch the view.
361
+ *
362
+ * Answers `true` for a sphere that only grazes it and for one the walk cannot decide, because a
363
+ * wrong `false` is a hole and a wrong `true` is a few triangles.
364
+ */
365
+ touches(x: number, y: number, z: number, radius: number): boolean;
366
+ }
367
+
368
+ /**
369
+ * One camera's view, widened by the turn the cut stays valid for, and the mesh's own transform.
370
+ *
371
+ * The frustum lives in world space and the sphere comes in the mesh's own units, so the transform
372
+ * is applied here rather than at every call site. A sphere is scaled by the matrix's largest axis
373
+ * scale, the same way three's own frustum cull scales one, and a camera that has moved `d` away
374
+ * from the view it cut by keeps anything within `d` times the margin — which is exactly the set a
375
+ * turn inside the margin can reveal.
376
+ */
377
+ export class ClusterView implements IClusterView {
378
+ readonly #frustum = new Frustum();
379
+ readonly #viewMatrix = new Matrix4();
380
+ readonly #eye = new Vector3();
381
+ readonly #center = new Vector3();
382
+ readonly #toWorld = new Matrix4();
383
+ #scale = 1;
384
+ #margin = 0;
385
+
386
+ /** Points this view at `camera`, kept valid for a turn of `margin` radians. */
387
+ setFromCamera(camera: Camera, margin: number): void {
388
+ camera.updateWorldMatrix(true, false);
389
+ worldFrustum(camera, this.#frustum, this.#viewMatrix);
390
+ this.#eye.setFromMatrixPosition(camera.matrixWorld);
391
+ // A turn of `m` rotates each plane about the eye, and a plane's normal moves by `2 sin(m / 2)` —
392
+ // the chord, not the sine. So a sphere at distance `d` keeps everything a turn that far can
393
+ // reveal when it is inflated by `d` times this, which is the exact bound rather than a guess.
394
+ this.#margin = 2 * Math.sin(margin / 2);
395
+ }
396
+
397
+ /** The transform from the units the spheres are given in to world space. */
398
+ setTransform(matrixWorld: Matrix4): void {
399
+ this.#toWorld.copy(matrixWorld);
400
+ this.#scale = matrixWorld.getMaxScaleOnAxis();
401
+ }
402
+
403
+ touches(x: number, y: number, z: number, radius: number): boolean {
404
+ this.#center.set(x, y, z).applyMatrix4(this.#toWorld);
405
+ const slack = this.#margin === 0 ? 0 : this.#center.distanceTo(this.#eye) * this.#margin;
406
+ return !outsideFrustum(this.#frustum, this.#center, radius * this.#scale + slack);
407
+ }
408
+ }
409
+
149
410
  /** Index slots the finest possible cut needs: every cluster whose own error is zero. */
150
411
  function finestIndexCount(table: IClusterTable): number {
151
412
  let count = 0;
@@ -155,6 +416,102 @@ function finestIndexCount(table: IClusterTable): number {
155
416
  return count;
156
417
  }
157
418
 
419
+ /**
420
+ * The view-pruned walk, and the scratch it needs to run without allocating.
421
+ *
422
+ * Selects exactly what {@link selectClusterCut} selects, without visiting clusters the view cannot
423
+ * hold: it descends only where the parent test still fails and the sphere that encloses a whole
424
+ * subtree still touches the (widened) frustum, and stops at the cluster it draws. `selectClusterCut`
425
+ * stays the oracle this is graded against. One of these belongs to one table.
426
+ */
427
+ export class ClusterWalk {
428
+ readonly #table: IClusterTable;
429
+ readonly #hierarchy: IClusterHierarchy;
430
+ readonly #stack: Uint32Array;
431
+ /** Which cut last descended into each group, so a group shared by siblings is visited once. */
432
+ readonly #stamps: Int32Array;
433
+ #generation = 0;
434
+
435
+ constructor(table: IClusterTable, hierarchy: IClusterHierarchy = clusterHierarchy(table)) {
436
+ this.#table = table;
437
+ this.#hierarchy = hierarchy;
438
+ this.#stack = new Uint32Array(table.ranges.length / 2);
439
+ this.#stamps = new Int32Array(hierarchy.starts.length);
440
+ }
441
+
442
+ /** The cut, as cluster indices, written into `out`; returns how many were selected. */
443
+ select(
444
+ camera: Vector3,
445
+ scale: number,
446
+ errorPixels: number,
447
+ view: IClusterView,
448
+ out: Uint32Array,
449
+ ): number {
450
+ const { children, groups, roots, starts } = this.#hierarchy;
451
+ const { errors, parentSpheres, sourceSpheres } = this.#table;
452
+ this.#generation += 1;
453
+ const generation = this.#generation;
454
+ let selected = 0;
455
+ let depth = 0;
456
+ for (let root = 0; root < roots.length; root += 1) {
457
+ this.#stack[depth] = roots[root] as number;
458
+ depth += 1;
459
+ while (depth > 0) {
460
+ depth -= 1;
461
+ const cluster = this.#stack[depth] as number;
462
+ const own = projectedError(
463
+ errors[cluster * 2] as number,
464
+ sourceSpheres,
465
+ cluster,
466
+ camera,
467
+ scale,
468
+ );
469
+ if (own <= errorPixels) {
470
+ const parent = projectedError(
471
+ errors[cluster * 2 + 1] as number,
472
+ parentSpheres,
473
+ cluster,
474
+ camera,
475
+ scale,
476
+ );
477
+ if (parent <= errorPixels) continue;
478
+ if (selected >= out.length)
479
+ throw new Error(
480
+ `ClusteredMesh selected more than the ${out.length} clusters level 0 holds; the table is inconsistent.`,
481
+ );
482
+ out[selected] = cluster;
483
+ selected += 1;
484
+ continue;
485
+ }
486
+ // Too coarse to draw at this distance, so the clusters it replaced are the only candidates
487
+ // left — and none of them can be in view if the sphere holding all of them cannot be.
488
+ const source = groups[cluster * 2 + 1] as number;
489
+ if (source === NO_CLUSTER_GROUP) continue;
490
+ if (this.#stamps[source] === generation) continue;
491
+ this.#stamps[source] = generation;
492
+ if (
493
+ !view.touches(
494
+ sourceSpheres[cluster * 4] as number,
495
+ sourceSpheres[cluster * 4 + 1] as number,
496
+ sourceSpheres[cluster * 4 + 2] as number,
497
+ sourceSpheres[cluster * 4 + 3] as number,
498
+ )
499
+ )
500
+ continue;
501
+ for (
502
+ let slot = starts[source] as number;
503
+ slot < (starts[source + 1] as number);
504
+ slot += 1
505
+ ) {
506
+ this.#stack[depth] = children[slot] as number;
507
+ depth += 1;
508
+ }
509
+ }
510
+ }
511
+ return selected;
512
+ }
513
+ }
514
+
158
515
  export class ClusteredMesh extends Mesh {
159
516
  /** The baked payload. The bake is the only thing that writes it; a copy takes the source's. */
160
517
  table!: IClusterTable;
@@ -162,16 +519,38 @@ export class ClusteredMesh extends Mesh {
162
519
  errorPixels: number;
163
520
  /** Camera movement, in the mesh's own units, below which the previous cut is kept. */
164
521
  recutDistance: number;
522
+ /**
523
+ * Whether the cut skips clusters the camera cannot see. Writable — a mesh drawn through a second
524
+ * camera can turn it off, and {@link ClusteredMesh.viewCullReport} says what happened either way.
525
+ */
526
+ viewCull: boolean;
527
+ /** Camera turn, in radians, the kept cut stays valid for. Writable. */
528
+ viewMargin: number;
165
529
 
166
530
  #cut!: Uint32Array;
167
531
  #selection!: Uint32Array;
532
+ #walk: ClusterWalk | undefined;
533
+ readonly #view = new ClusterView();
168
534
  readonly #cameraLocal = new Vector3();
169
535
  readonly #lastCut = new Vector3();
536
+ readonly #rotation = new Quaternion();
537
+ readonly #lastRotation = new Quaternion();
538
+ readonly #frustum = new Frustum();
539
+ readonly #viewMatrix = new Matrix4();
540
+ readonly #sphereCenter = new Vector3();
170
541
  #drawnClusters = 0;
171
542
  #drawnIndices = 0;
543
+ #drawnClustersOutsideView = 0;
544
+ #drawnTrianglesOutsideView = 0;
545
+ #recutMs = 0;
546
+ #recutBytes = 0;
547
+ #recutCount = 0;
172
548
  #hasCut = false;
549
+ #pruned = false;
173
550
  #lastScale = 0;
174
551
  #lastErrorPixels = 0;
552
+ /** The projection the cut was pruned by: an aspect or zoom change keeps the pixel scale. */
553
+ readonly #lastProjection = new Matrix4();
175
554
 
176
555
  constructor(
177
556
  geometry: BufferGeometry,
@@ -183,6 +562,9 @@ export class ClusteredMesh extends Mesh {
183
562
  assertTable(table);
184
563
  this.errorPixels = options.errorPixels ?? DEFAULT_ERROR_PIXELS;
185
564
  this.recutDistance = options.recutDistance ?? radiusOf(table) * RECUT_FRACTION;
565
+ this.viewCull = options.viewCull ?? true;
566
+ this.viewMargin = options.viewMargin ?? DEFAULT_VIEW_MARGIN;
567
+ assertViewMargin(this.viewMargin);
186
568
  this.#load(table, geometry);
187
569
  // Full detail until something cuts it. Virtual geometry ships on by default, so the mesh a
188
570
  // game never touches has to draw exactly what an ordinary `Mesh` would have drawn — a class
@@ -196,6 +578,13 @@ export class ClusteredMesh extends Mesh {
196
578
  this.table = table;
197
579
  this.#cut = new Uint32Array(finestIndexCount(table));
198
580
  this.#selection = new Uint32Array(table.ranges.length / 2);
581
+ // No camera has taken a cut of this table yet, so there is nothing outside a view to report.
582
+ this.#drawnClustersOutsideView = 0;
583
+ this.#drawnTrianglesOutsideView = 0;
584
+ this.#recutMs = 0;
585
+ this.#recutBytes = 0;
586
+ this.#recutCount = 0;
587
+ this.#walk = table.groups === undefined ? undefined : new ClusterWalk(table);
199
588
  // The geometry draws out of the cut buffer from here on. Its vertex attributes are untouched:
200
589
  // every level of the DAG indexes the vertices the mesh already shipped.
201
590
  //
@@ -217,6 +606,8 @@ export class ClusteredMesh extends Mesh {
217
606
  return new ClusteredMesh(withOwnCut(this.geometry), this.material, this.table, {
218
607
  errorPixels: this.errorPixels,
219
608
  recutDistance: this.recutDistance,
609
+ viewCull: this.viewCull,
610
+ viewMargin: this.viewMargin,
220
611
  }).copy(this, recursive) as this;
221
612
  }
222
613
 
@@ -237,6 +628,8 @@ export class ClusteredMesh extends Mesh {
237
628
  this.geometry = geometry;
238
629
  this.errorPixels = source.errorPixels;
239
630
  this.recutDistance = source.recutDistance;
631
+ this.viewCull = source.viewCull;
632
+ this.viewMargin = source.viewMargin;
240
633
  // Nothing this copy has drawn yet, so the next update has to cut it for where it stands.
241
634
  this.#hasCut = false;
242
635
  this.#compact(this.#finestCut());
@@ -264,6 +657,63 @@ export class ClusteredMesh extends Mesh {
264
657
  return this.#drawnIndices / 3;
265
658
  }
266
659
 
660
+ /**
661
+ * Triangles in the current cut whose cluster bounds lie wholly outside the view volume.
662
+ *
663
+ * A measurement, not a cull: PRD-600 records this number before and after the walk learns to skip
664
+ * what the view does not hold. It is taken when the cut is taken, so a still camera reads the
665
+ * number its standing cut was made with.
666
+ */
667
+ get drawnTrianglesOutsideView(): number {
668
+ return this.#drawnTrianglesOutsideView;
669
+ }
670
+
671
+ /** Clusters in the current cut whose bounds lie wholly outside the view volume. */
672
+ get drawnClustersOutsideView(): number {
673
+ return this.#drawnClustersOutsideView;
674
+ }
675
+
676
+ /**
677
+ * Milliseconds the last re-cut took, from choosing the cut to the index buffer being marked for
678
+ * upload.
679
+ *
680
+ * The whole re-cut, because that is the cost a game pays for turning the camera and the number
681
+ * `viewMargin` is chosen against. The bytes below are only the compact's copy, so the throughput
682
+ * this divides out is the pessimistic one.
683
+ */
684
+ get recutMs(): number {
685
+ return this.#recutMs;
686
+ }
687
+
688
+ /** Index bytes the last re-cut copied and uploaded. */
689
+ get recutBytes(): number {
690
+ return this.#recutBytes;
691
+ }
692
+
693
+ /** Throughput of the last re-cut's copy of the cut, in megabytes per second. */
694
+ get recutMegabytesPerSecond(): number {
695
+ return this.#recutMs > 0 ? this.#recutBytes / 1e3 / this.#recutMs : 0;
696
+ }
697
+
698
+ /** How many re-cuts this mesh has taken, so a reader can tell a fresh one from a stale reading. */
699
+ get recutCount(): number {
700
+ return this.#recutCount;
701
+ }
702
+
703
+ /**
704
+ * What this mesh does about clusters outside the view, and why.
705
+ *
706
+ * `"on"` when the cut is pruned, and a reason when it is not — a mesh that silently kept drawing
707
+ * what nobody can see would be a performance bug with no symptom, and one that silently dropped
708
+ * what a second camera can see would be a hole with no cause.
709
+ */
710
+ get viewCullReport(): string {
711
+ if (!this.viewCull) return "off (viewCull = false)";
712
+ if (this.castShadow) return "off (castShadow)";
713
+ if (this.#walk === undefined) return "off (no clusterGroups)";
714
+ return "on";
715
+ }
716
+
267
717
  /**
268
718
  * Chooses this frame's cut and compacts it into one index range.
269
719
  *
@@ -280,25 +730,88 @@ export class ClusteredMesh extends Mesh {
280
730
  camera.updateWorldMatrix(true, false);
281
731
  this.#cameraLocal.setFromMatrixPosition(camera.matrixWorld);
282
732
  this.worldToLocal(this.#cameraLocal);
733
+ camera.getWorldQuaternion(this.#rotation);
283
734
 
735
+ // A cut pruned by the view is only right for the view it was pruned by, so it is kept while the
736
+ // camera stays inside the band and the turn it was widened by.
737
+ const pruned = this.viewCull && !this.castShadow && this.#walk !== undefined;
284
738
  const moved = this.#cameraLocal.distanceTo(this.#lastCut);
285
739
  const settled =
286
740
  this.#hasCut &&
741
+ pruned === this.#pruned &&
287
742
  moved <= this.recutDistance &&
743
+ this.#rotation.angleTo(this.#lastRotation) <= this.viewMargin &&
288
744
  scale === this.#lastScale &&
289
- this.errorPixels === this.#lastErrorPixels;
745
+ this.errorPixels === this.#lastErrorPixels &&
746
+ camera.projectionMatrix.equals(this.#lastProjection);
290
747
  if (settled) return this.drawnTriangles;
291
748
 
292
749
  this.#lastCut.copy(this.#cameraLocal);
750
+ this.#lastRotation.copy(this.#rotation);
293
751
  this.#lastScale = scale;
294
752
  this.#lastErrorPixels = this.errorPixels;
753
+ this.#lastProjection.copy(camera.projectionMatrix);
754
+ this.#pruned = pruned;
295
755
  this.#hasCut = true;
296
- this.#compact(
297
- selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection),
298
- );
756
+ const started = performance.now();
757
+ const walk = this.#walk;
758
+ if (pruned && walk !== undefined) {
759
+ this.#view.setFromCamera(camera, this.viewMargin);
760
+ this.#view.setTransform(this.matrixWorld);
761
+ this.#compact(
762
+ walk.select(this.#cameraLocal, scale, this.errorPixels, this.#view, this.#selection),
763
+ );
764
+ } else {
765
+ this.#compact(
766
+ selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection),
767
+ );
768
+ }
769
+ this.#recutMs = performance.now() - started;
770
+ this.#recutBytes = this.#drawnIndices * 4;
771
+ this.#recutCount += 1;
772
+ this.#countOutsideView(camera);
299
773
  return this.drawnTriangles;
300
774
  }
301
775
 
776
+ /**
777
+ * Records how much of this cut the view volume does not hold.
778
+ *
779
+ * Read-only and taken when a cut is taken, so it costs one sphere test per selected cluster on the
780
+ * re-cut path and nothing at all on a frame the cut settled. The mesh's own scale is folded into
781
+ * the radius the way three folds it into its own cull, so a scaled placement is measured as it
782
+ * draws.
783
+ */
784
+ #countOutsideView(camera: Camera): void {
785
+ const frustum = worldFrustum(camera, this.#frustum, this.#viewMatrix);
786
+ const scale = this.matrixWorld.getMaxScaleOnAxis();
787
+ const world = this.matrixWorld;
788
+ let clusters = 0;
789
+ let indices = 0;
790
+ for (let slot = 0; slot < this.#drawnClusters; slot += 1) {
791
+ const cluster = this.#selection[slot] as number;
792
+ const count = this.table.ranges[cluster * 2 + 1] as number;
793
+ this.#sphereCenter
794
+ .set(
795
+ this.table.bounds[cluster * 4] as number,
796
+ this.table.bounds[cluster * 4 + 1] as number,
797
+ this.table.bounds[cluster * 4 + 2] as number,
798
+ )
799
+ .applyMatrix4(world);
800
+ if (
801
+ !outsideFrustum(
802
+ frustum,
803
+ this.#sphereCenter,
804
+ (this.table.bounds[cluster * 4 + 3] as number) * scale,
805
+ )
806
+ )
807
+ continue;
808
+ clusters += 1;
809
+ indices += count;
810
+ }
811
+ this.#drawnClustersOutsideView = clusters;
812
+ this.#drawnTrianglesOutsideView = indices / 3;
813
+ }
814
+
302
815
  #compact(selected: number): void {
303
816
  let cursor = 0;
304
817
  for (let slot = 0; slot < selected; slot += 1) {
@@ -340,10 +853,16 @@ function withOwnCut(geometry: BufferGeometry): BufferGeometry {
340
853
  }
341
854
 
342
855
  function radiusOf(table: IClusterTable): number {
343
- let radius = 0;
344
- for (let cluster = 0; cluster * 4 < table.bounds.length; cluster += 1)
345
- radius = Math.max(radius, table.bounds[cluster * 4 + 3] as number);
346
- return radius;
856
+ return clusterTableRadius(table);
857
+ }
858
+
859
+ export function assertViewMargin(margin: number): void {
860
+ // Zero is a legal choice — re-cut on every degree — and a quarter turn or more is a half-sphere
861
+ // kept for nothing; neither is a bug worth throwing over, but NaN and negatives are.
862
+ if (!Number.isFinite(margin) || margin < 0 || margin >= Math.PI / 2)
863
+ throw new Error(
864
+ `ClusteredMesh viewMargin must be a turn in radians below a quarter circle, got ${margin}.`,
865
+ );
347
866
  }
348
867
 
349
868
  function assertTable(table: IClusterTable): void {
@@ -364,6 +883,10 @@ function assertTable(table: IClusterTable): void {
364
883
  `ClusteredMesh table.${name} holds ${array.length} values for ${clusters} clusters; it needs ${clusters * width}.`,
365
884
  );
366
885
  }
886
+ if (table.groups !== undefined && table.groups.length !== clusters * 2)
887
+ throw new Error(
888
+ `ClusteredMesh table.groups holds ${table.groups.length} values for ${clusters} clusters; it needs ${clusters * 2}.`,
889
+ );
367
890
  for (let cluster = 0; cluster < clusters; cluster += 1) {
368
891
  const start = table.ranges[cluster * 2] as number;
369
892
  const count = table.ranges[cluster * 2 + 1] as number;
@@ -381,6 +904,7 @@ interface IVirtualGeometryDef {
381
904
  readonly clusterBounds: number;
382
905
  readonly clusterCones: number;
383
906
  readonly clusterErrors: number;
907
+ readonly clusterGroups: number;
384
908
  readonly clusterParentSpheres: number;
385
909
  readonly clusterRanges: number;
386
910
  readonly clusterSourceSpheres: number;
@@ -407,6 +931,7 @@ const TABLE_FIELDS: readonly (keyof IVirtualGeometryDef)[] = [
407
931
  "clusterBounds",
408
932
  "clusterCones",
409
933
  "clusterErrors",
934
+ "clusterGroups",
410
935
  "clusterParentSpheres",
411
936
  "clusterRanges",
412
937
  "clusterSourceSpheres",
@@ -427,19 +952,22 @@ async function readTable(
427
952
  );
428
953
  const accessor = async (index: number): Promise<ArrayLike<number>> =>
429
954
  (await parser.getDependency("accessor", index)).array;
430
- const [bounds, cones, errors, parentSpheres, ranges, sourceSpheres, indices] = await Promise.all([
431
- accessor(def.clusterBounds),
432
- accessor(def.clusterCones),
433
- accessor(def.clusterErrors),
434
- accessor(def.clusterParentSpheres),
435
- accessor(def.clusterRanges),
436
- accessor(def.clusterSourceSpheres),
437
- accessor(def.indices),
438
- ]);
955
+ const [bounds, cones, errors, groups, parentSpheres, ranges, sourceSpheres, indices] =
956
+ await Promise.all([
957
+ accessor(def.clusterBounds),
958
+ accessor(def.clusterCones),
959
+ accessor(def.clusterErrors),
960
+ accessor(def.clusterGroups),
961
+ accessor(def.clusterParentSpheres),
962
+ accessor(def.clusterRanges),
963
+ accessor(def.clusterSourceSpheres),
964
+ accessor(def.indices),
965
+ ]);
439
966
  return {
440
967
  bounds: typedFloat(bounds as Float32Array),
441
968
  cones: typedFloat(cones as Float32Array),
442
969
  errors: typedFloat(errors as Float32Array),
970
+ groups: typedUint(groups as Uint32Array),
443
971
  indices: typedUint(indices as Uint32Array),
444
972
  parentSpheres: typedFloat(parentSpheres as Float32Array),
445
973
  ranges: typedUint(ranges as Uint32Array),