@threenative/core 0.3.4 → 0.3.5

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,492 @@
1
+ import {
2
+ BufferAttribute,
3
+ BufferGeometry,
4
+ type Camera,
5
+ Euler,
6
+ InstancedMesh,
7
+ type Material,
8
+ Matrix4,
9
+ Object3D,
10
+ Quaternion,
11
+ Vector3,
12
+ } from "three";
13
+ import { type IClusterTable, pixelsPerUnit, selectClusterCut } from "./clustered-mesh.js";
14
+
15
+ /**
16
+ * Many copies of one clustered body, each drawn at the detail its own distance earns.
17
+ *
18
+ * `InstancedBatch` collapses repeated props into one draw; this does the same for a body that
19
+ * carries a cluster DAG, and adds the part `InstancedBatch` cannot do — a copy twelve metres away
20
+ * and a copy two hundred metres away do not draw the same triangles.
21
+ *
22
+ * **Why instances are bucketed rather than cut one by one.** One indexed draw has one index range,
23
+ * and multi-draw indirect is not portably available on this stack, so *n* different cuts would mean
24
+ * *n* draws and *n* index buffers — on four hundred boulders that is a gigabyte of index data to
25
+ * save vertex work. Instead the copies are grouped by distance, one cut is taken per occupied
26
+ * group, and each group draws as one instanced draw. Every group's cut is a real cut of the DAG and
27
+ * therefore watertight; the group is cut at the distance of its *nearest* member, so no copy is ever
28
+ * drawn coarser than its own distance allows — only finer, by at most the width of one group.
29
+ *
30
+ * Geometry, surface and every transform are the game's, exactly as with `InstancedBatch`.
31
+ */
32
+
33
+ /** One copy's transform, in the units the geometry was authored in. */
34
+ export interface IClusteredPlacement {
35
+ readonly position: readonly [number, number, number];
36
+ readonly rotation?: readonly [number, number, number];
37
+ readonly scale?: readonly [number, number, number] | number;
38
+ }
39
+
40
+ export interface IClusteredBatchOptions {
41
+ /**
42
+ * How far the camera must move, as a fraction of its distance to the nearest copy, before the
43
+ * cut is taken again. Default 1%.
44
+ *
45
+ * The engine cuts every batch every frame, so this is the difference between a walk that costs a
46
+ * few hundred cluster tests and one that costs half a million. A camera that has not moved
47
+ * meaningfully keeps the previous cut, which is always a cut some camera would have chosen and
48
+ * therefore always watertight.
49
+ */
50
+ readonly recutFraction?: number;
51
+ /**
52
+ * Ratio between one distance group and the next, above 1.
53
+ *
54
+ * Narrower groups follow each copy's own distance more closely and cost one more draw each.
55
+ * 1.25 is the default: about a dozen groups across a scene that spans a few hundred metres.
56
+ */
57
+ readonly distanceRatio?: number;
58
+ /** Screen-space error budget in pixels, as {@link ClusteredMesh}. Default 1. */
59
+ readonly errorPixels?: number;
60
+ /** The shape every copy draws, carrying the baked cluster table. */
61
+ readonly geometry: BufferGeometry;
62
+ /** The surface every copy draws with, supplied by the game and used by reference. */
63
+ readonly material: Material;
64
+ /** The bake, exactly as `TN_virtual_geometry` stores it. */
65
+ readonly table: IClusterTable;
66
+ }
67
+
68
+ export interface IClusteredBatchBuildOptions {
69
+ readonly castShadow?: boolean;
70
+ readonly name?: string;
71
+ readonly parent: Object3D;
72
+ readonly receiveShadow?: boolean;
73
+ }
74
+
75
+ /**
76
+ * Updates a distance group may stand empty before its index buffer goes back to the driver.
77
+ *
78
+ * Long enough that the renderer cannot still be holding the buffer in a submitted command, short
79
+ * enough that a walk across the scene does not accumulate every group it ever passed through. A
80
+ * quarry route that kept them all ran the GPU out of memory: `vkAllocateMemory failed with
81
+ * VK_ERROR_OUT_OF_DEVICE_MEMORY`.
82
+ */
83
+ const RECLAIM_AFTER_EMPTY_UPDATES = 4;
84
+
85
+ /**
86
+ * Distance groups that may be built in one update.
87
+ *
88
+ * Building a group means cutting it and uploading its index buffer, and the first frames of a route
89
+ * populate every group a walk will ever use. Doing that at once cost the quarry a 649.6 ms
90
+ * `render.p95` on the native host — one visible stall in a game that never asked for any of this.
91
+ * Four per update converges a walking camera without a visible stall; copies whose own group is
92
+ * not built yet draw with the nearest built one, which is a real cut of
93
+ * the same DAG and therefore watertight; they refine within a few frames.
94
+ */
95
+ const GROUPS_BUILT_PER_UPDATE = 4;
96
+
97
+ const DEFAULT_DISTANCE_RATIO = 1.25;
98
+ const DEFAULT_RECUT_FRACTION = 0.01;
99
+ const DEFAULT_ERROR_PIXELS = 1;
100
+ /** A copy nearer than this is treated as this far away, rather than taking log of zero. */
101
+ const MIN_DISTANCE = 1e-3;
102
+
103
+ interface IPlaced {
104
+ readonly matrix: Matrix4;
105
+ readonly inverse: Matrix4;
106
+ readonly position: Vector3;
107
+ readonly scale: number;
108
+ }
109
+
110
+ interface IGroup {
111
+ readonly copies: number[];
112
+ cut: Uint32Array;
113
+ /** Consecutive updates with no copy in this group. */
114
+ empty: number;
115
+ mesh: InstancedMesh | null;
116
+ }
117
+
118
+ /**
119
+ * The node a batch attaches to the scene.
120
+ *
121
+ * A subclass rather than a plain `Object3D` so the engine's per-frame walk can find the batch the
122
+ * same way it finds a `ClusteredMesh` — virtual geometry ships on, and a game that has to remember
123
+ * to call something has not been given it.
124
+ */
125
+ export class ClusteredBatchRoot extends Object3D {
126
+ constructor(readonly batch: ClusteredBatch) {
127
+ super();
128
+ }
129
+
130
+ /**
131
+ * A copy that is still being cut.
132
+ *
133
+ * three builds one through `new this.constructor()`, which left the copy's `batch` undefined
134
+ * and quietly stopped cutting it — a frozen cut that still drew. Sharing the batch is what
135
+ * keeps a copy alive: the batch owns the bands and their index buffers, so the copy draws the
136
+ * same cut as the root it was copied from, which is the same thing `Mesh.copy` does with
137
+ * geometry and `VirtualGeometryPlugin` does with a baked table.
138
+ */
139
+ override clone(recursive = true): this {
140
+ return new ClusteredBatchRoot(this.batch).copy(this, recursive) as this;
141
+ }
142
+ }
143
+
144
+ function placementMatrix(placement: IClusteredPlacement): Matrix4 {
145
+ const scale = placement.scale ?? 1;
146
+ const scaleVector =
147
+ typeof scale === "number" ? new Vector3(scale, scale, scale) : new Vector3(...scale);
148
+ const rotation = placement.rotation ?? [0, 0, 0];
149
+ return new Matrix4().compose(
150
+ new Vector3(...placement.position),
151
+ new Quaternion().setFromEuler(new Euler(rotation[0], rotation[1], rotation[2])),
152
+ scaleVector,
153
+ );
154
+ }
155
+
156
+ export class ClusteredBatch {
157
+ readonly #options: IClusteredBatchOptions;
158
+ readonly #placed: IPlaced[] = [];
159
+ readonly #groups = new Map<number, IGroup>();
160
+ readonly #selection: Uint32Array;
161
+ /** The distance band each copy actually belongs to this update, before any borrowing. */
162
+ #wantedKey: Int32Array;
163
+ readonly #cameraWorld = new Vector3();
164
+ readonly #cameraLocal = new Vector3();
165
+ readonly #lastCut = new Vector3();
166
+ #hasCut = false;
167
+ #lastScale = 0;
168
+ readonly #distanceRatio: number;
169
+ /** Bands this camera wants that are not built yet; while any remain the cut cannot settle. */
170
+ #pending = 0;
171
+ #root: Object3D | null = null;
172
+ #built: IClusteredBatchBuildOptions | null = null;
173
+ #drawnTriangles = 0;
174
+
175
+ constructor(options: IClusteredBatchOptions) {
176
+ this.#options = options;
177
+ this.#distanceRatio = options.distanceRatio ?? DEFAULT_DISTANCE_RATIO;
178
+ if (!(this.#distanceRatio > 1))
179
+ throw new Error(
180
+ `ClusteredBatch distanceRatio must be above one, got ${this.#distanceRatio}.`,
181
+ );
182
+ this.#selection = new Uint32Array(options.table.ranges.length / 2);
183
+ this.#wantedKey = new Int32Array(0);
184
+ }
185
+
186
+ /** How many copies are placed. */
187
+ get count(): number {
188
+ return this.#placed.length;
189
+ }
190
+
191
+ /** Draws this batch will submit — one per occupied distance group. */
192
+ get drawCalls(): number {
193
+ let calls = 0;
194
+ for (const group of this.#groups.values()) if (group.mesh?.visible === true) calls += 1;
195
+ return calls;
196
+ }
197
+
198
+ /** Triangles the current cut submits, over every copy. */
199
+ get drawnTriangles(): number {
200
+ return this.#drawnTriangles;
201
+ }
202
+
203
+ /** Adds one copy. Returns its index, so the game can move it later. */
204
+ place(placement: IClusteredPlacement): number {
205
+ if (this.#built !== null)
206
+ throw new Error("ClusteredBatch.place cannot run after build; place every copy first.");
207
+ const matrix = placementMatrix(placement);
208
+ const scaleVector = new Vector3().setFromMatrixScale(matrix);
209
+ this.#placed.push({
210
+ inverse: matrix.clone().invert(),
211
+ matrix,
212
+ position: new Vector3().setFromMatrixPosition(matrix),
213
+ scale: Math.max(scaleVector.x, scaleVector.y, scaleVector.z),
214
+ });
215
+ return this.#placed.length - 1;
216
+ }
217
+
218
+ /** Attaches the batch to the scene. Nothing draws until {@link ClusteredBatch.update} runs. */
219
+ build(options: IClusteredBatchBuildOptions): Object3D {
220
+ if (this.#placed.length === 0)
221
+ throw new Error("ClusteredBatch.build needs at least one placed copy.");
222
+ const root = new ClusteredBatchRoot(this);
223
+ root.name = options.name ?? "";
224
+ options.parent.add(root);
225
+ this.#root = root;
226
+ this.#built = options;
227
+ return root;
228
+ }
229
+
230
+ /**
231
+ * Chooses this frame's cut for every distance group.
232
+ *
233
+ * @returns triangles the batch will submit.
234
+ */
235
+ update(camera: Camera, viewportHeight: number): number {
236
+ const root = this.#root;
237
+ if (root === null) throw new Error("ClusteredBatch.update needs build() first.");
238
+ const scale = pixelsPerUnit(camera, viewportHeight);
239
+ camera.updateWorldMatrix(true, false);
240
+ this.#cameraWorld.setFromMatrixPosition(camera.matrixWorld);
241
+
242
+ // Everything below walks every cluster of every occupied band. Skip it outright when the camera
243
+ // has not moved enough to change a cut, and when every band this camera needs is already built.
244
+ let nearestCopy = Number.POSITIVE_INFINITY;
245
+ for (const placed of this.#placed)
246
+ nearestCopy = Math.min(nearestCopy, this.#cameraWorld.distanceTo(placed.position));
247
+ const settled =
248
+ this.#hasCut &&
249
+ scale === this.#lastScale &&
250
+ this.#pending === 0 &&
251
+ this.#cameraWorld.distanceTo(this.#lastCut) <=
252
+ Math.max(nearestCopy, MIN_DISTANCE) *
253
+ (this.#options.recutFraction ?? DEFAULT_RECUT_FRACTION);
254
+ if (settled) return this.#drawnTriangles;
255
+ this.#lastCut.copy(this.#cameraWorld);
256
+ this.#lastScale = scale;
257
+ this.#hasCut = true;
258
+
259
+ if (this.#wantedKey.length !== this.#placed.length)
260
+ this.#wantedKey = new Int32Array(this.#placed.length);
261
+ for (const group of this.#groups.values()) group.copies.length = 0;
262
+
263
+ // Which band each copy belongs to, before any borrowing.
264
+ const wantedKeys = new Set<number>();
265
+ for (let copy = 0; copy < this.#placed.length; copy += 1) {
266
+ const placed = this.#placed[copy] as IPlaced;
267
+ const distance = Math.max(this.#cameraWorld.distanceTo(placed.position), MIN_DISTANCE);
268
+ // Grouped on distance measured in the body's own units, so two copies at different scales
269
+ // that cover the same screen area land in the same group.
270
+ const wanted = Math.floor(Math.log(distance / placed.scale) / Math.log(this.#distanceRatio));
271
+ this.#wantedKey[copy] = wanted;
272
+ wantedKeys.add(wanted);
273
+ }
274
+
275
+ // A band nobody has built yet costs a cut and an index upload. Grant a couple per update, in
276
+ // order, so a scene arrives over a few frames instead of in one stall. The first update always
277
+ // gets one, or nothing would have anywhere to borrow from.
278
+ const open = new Set<number>();
279
+ for (const key of wantedKeys) if (this.#groups.get(key)?.mesh != null) open.add(key);
280
+ let grants = GROUPS_BUILT_PER_UPDATE;
281
+ this.#pending = 0;
282
+ for (const key of [...wantedKeys].sort((a, b) => a - b)) {
283
+ if (open.has(key)) continue;
284
+ if (grants <= 0 && open.size > 0) {
285
+ this.#pending += 1;
286
+ continue;
287
+ }
288
+ open.add(key);
289
+ grants -= 1;
290
+ }
291
+
292
+ for (let copy = 0; copy < this.#placed.length; copy += 1) {
293
+ const wanted = this.#wantedKey[copy] as number;
294
+ const key = open.has(wanted) ? wanted : this.#nearestOpenKey(wanted, open);
295
+ let group = this.#groups.get(key);
296
+ if (group === undefined) {
297
+ group = { copies: [], cut: new Uint32Array(0), empty: 0, mesh: null };
298
+ this.#groups.set(key, group);
299
+ }
300
+ group.copies.push(copy);
301
+ }
302
+
303
+ this.#drawnTriangles = 0;
304
+ for (const [key, group] of this.#groups) {
305
+ this.#drawGroup(group, root, scale, key);
306
+ if (group.empty >= RECLAIM_AFTER_EMPTY_UPDATES) {
307
+ this.#reclaim(group, root);
308
+ this.#groups.delete(key);
309
+ }
310
+ }
311
+ return this.#drawnTriangles;
312
+ }
313
+
314
+ /**
315
+ * Gives one group's index buffer back.
316
+ *
317
+ * The vertex attributes are deleted from the geometry *before* it is disposed, because they are
318
+ * the batch's own and every other group is still drawing from them: disposing a geometry that
319
+ * still holds them destroys the position buffer the whole batch shares, which WebGPU reports as
320
+ * `[Buffer (unlabeled)] used in submit while destroyed`.
321
+ */
322
+ /** The open band closest to `wanted`, or `wanted` itself when none is open. */
323
+ #nearestOpenKey(wanted: number, open: ReadonlySet<number>): number {
324
+ let best = wanted;
325
+ let bestDistance = Number.POSITIVE_INFINITY;
326
+ for (const key of open) {
327
+ const distance = Math.abs(key - wanted);
328
+ if (distance < bestDistance) {
329
+ best = key;
330
+ bestDistance = distance;
331
+ }
332
+ }
333
+ return best;
334
+ }
335
+
336
+ #reclaim(group: IGroup, root: Object3D): void {
337
+ const mesh = group.mesh;
338
+ if (mesh === null) return;
339
+ root.remove(mesh);
340
+ for (const name of Object.keys(mesh.geometry.attributes)) mesh.geometry.deleteAttribute(name);
341
+ mesh.geometry.dispose();
342
+ mesh.dispose();
343
+ group.mesh = null;
344
+ group.cut = new Uint32Array(0);
345
+ }
346
+
347
+ #drawGroup(group: IGroup, root: Object3D, scale: number, key: number): void {
348
+ if (group.copies.length === 0) {
349
+ group.empty += 1;
350
+ if (group.mesh !== null) group.mesh.visible = false;
351
+ return;
352
+ }
353
+ group.empty = 0;
354
+ // Cut at the nearest member's distance: never coarser than any copy in the group allows.
355
+ //
356
+ // Copies borrowed from a band that is not built yet are excluded from the choice: they are
357
+ // passing through, and letting one anchor the group would size its buffer for a distance the
358
+ // band never owns — which grows the buffer, and every growth strands a GPU index buffer.
359
+ let nearest = group.copies[0] as number;
360
+ let nearestDistance = Number.POSITIVE_INFINITY;
361
+ let sawNative = false;
362
+ for (const copy of group.copies) {
363
+ const native = this.#wantedKey[copy] === key;
364
+ if (sawNative && !native) continue;
365
+ const placed = this.#placed[copy] as IPlaced;
366
+ const distance = this.#cameraWorld.distanceTo(placed.position) / placed.scale;
367
+ if (native && !sawNative) {
368
+ sawNative = true;
369
+ nearest = copy;
370
+ nearestDistance = distance;
371
+ continue;
372
+ }
373
+ if (distance < nearestDistance) {
374
+ nearest = copy;
375
+ nearestDistance = distance;
376
+ }
377
+ }
378
+ const anchor = this.#placed[nearest] as IPlaced;
379
+ this.#cameraLocal.copy(this.#cameraWorld).applyMatrix4(anchor.inverse);
380
+ // Sized once, from the finest cut this band can ever need — see `#capacityFor`.
381
+ if (group.cut.length === 0)
382
+ group.cut = new Uint32Array(this.#capacityFor(group, anchor, nearestDistance, scale));
383
+
384
+ const selected = selectClusterCut(
385
+ this.#options.table,
386
+ this.#cameraLocal,
387
+ scale,
388
+ this.#options.errorPixels ?? DEFAULT_ERROR_PIXELS,
389
+ this.#selection,
390
+ );
391
+ let indices = 0;
392
+ for (let slot = 0; slot < selected; slot += 1)
393
+ indices += this.#options.table.ranges[(this.#selection[slot] as number) * 2 + 1] as number;
394
+ // Growing is the last resort and should not happen: three frees a geometry's index buffer only
395
+ // when the geometry is disposed, so every replacement leaks one. The quarry's route leaked 74 of
396
+ // them every 120 frames and ran an 8 GB card out of memory.
397
+ if (group.cut.length < indices) group.cut = new Uint32Array(Math.ceil(indices * 1.5));
398
+ let cursor = 0;
399
+ for (let slot = 0; slot < selected; slot += 1) {
400
+ const cluster = this.#selection[slot] as number;
401
+ const start = this.#options.table.ranges[cluster * 2] as number;
402
+ const count = this.#options.table.ranges[cluster * 2 + 1] as number;
403
+ group.cut.set(this.#options.table.indices.subarray(start, start + count), cursor);
404
+ cursor += count;
405
+ }
406
+
407
+ const mesh = this.#meshFor(group, root);
408
+ mesh.count = group.copies.length;
409
+ for (let slot = 0; slot < group.copies.length; slot += 1)
410
+ mesh.setMatrixAt(slot, (this.#placed[group.copies[slot] as number] as IPlaced).matrix);
411
+ mesh.instanceMatrix.needsUpdate = true;
412
+ const index = mesh.geometry.getIndex();
413
+ if (index !== null && cursor > 0) {
414
+ index.addUpdateRange(0, cursor);
415
+ index.needsUpdate = true;
416
+ }
417
+ mesh.geometry.setDrawRange(0, cursor);
418
+ // Nothing resolved for this group, so nothing is submitted for it.
419
+ mesh.visible = cursor > 0;
420
+ this.#drawnTriangles += (cursor / 3) * group.copies.length;
421
+ }
422
+
423
+ /**
424
+ * Index slots the finest cut this distance band can ever need.
425
+ *
426
+ * A band spans `[d, d * distanceRatio)`, and the cut only gets coarser as the camera falls back
427
+ * through it, so the cut taken at the band's near edge bounds every cut the band will ever take.
428
+ * Half again as much on top covers the part that is not distance — two cameras the same distance
429
+ * away in different directions do not select quite the same clusters.
430
+ *
431
+ * This is sized once because replacing a geometry's index attribute leaks its GPU buffer: three
432
+ * releases `geometry.index` only when the geometry itself is disposed.
433
+ */
434
+ #capacityFor(group: IGroup, anchor: IPlaced, nearestDistance: number, scale: number): number {
435
+ const nearEdge =
436
+ this.#distanceRatio ** Math.floor(Math.log(nearestDistance) / Math.log(this.#distanceRatio));
437
+ const direction = this.#cameraLocal.clone().normalize();
438
+ const probe = direction.multiplyScalar(Math.max(nearEdge, MIN_DISTANCE));
439
+ const selected = selectClusterCut(
440
+ this.#options.table,
441
+ probe,
442
+ scale,
443
+ this.#options.errorPixels ?? DEFAULT_ERROR_PIXELS,
444
+ this.#selection,
445
+ );
446
+ let indices = 0;
447
+ for (let slot = 0; slot < selected; slot += 1)
448
+ indices += this.#options.table.ranges[(this.#selection[slot] as number) * 2 + 1] as number;
449
+ void group;
450
+ void anchor;
451
+ return Math.max(3, Math.ceil(indices * 1.5));
452
+ }
453
+
454
+ /**
455
+ * The group's mesh, created once and never disposed.
456
+ *
457
+ * A group's geometry shares the batch's vertex attributes *by reference* — only the index range
458
+ * differs between groups, and cloning would copy every position per group, which is the memory
459
+ * this design exists to avoid. That sharing is also why the geometry is never disposed:
460
+ * `BufferGeometry.dispose()` releases the attributes it holds, so freeing one group's geometry
461
+ * destroys the position buffer every other group is still drawing from. WebGPU said exactly that
462
+ * on the quarry's first virtual run — `[Buffer (unlabeled)] used in submit while destroyed`,
463
+ * hundreds of times a second. When a group outgrows its cut only the index attribute is replaced,
464
+ * and doubling bounds how often that happens.
465
+ */
466
+ #meshFor(group: IGroup, root: Object3D): InstancedMesh {
467
+ const existing = group.mesh;
468
+ if (existing !== null) {
469
+ if ((existing.geometry.getIndex()?.array as Uint32Array) !== group.cut)
470
+ existing.geometry.setIndex(new BufferAttribute(group.cut, 1));
471
+ return existing;
472
+ }
473
+ const geometry = new BufferGeometry();
474
+ for (const [name, attribute] of Object.entries(this.#options.geometry.attributes))
475
+ geometry.setAttribute(name, attribute);
476
+ geometry.boundingSphere = this.#options.geometry.boundingSphere;
477
+ geometry.boundingBox = this.#options.geometry.boundingBox;
478
+ // `BufferAttribute`, never `Uint32BufferAttribute`: the typed subclasses copy the array, which
479
+ // both hides every cut from the GPU and makes the identity check above replace the index every
480
+ // frame — three frees a geometry's index only on dispose, so that leaked one buffer a frame.
481
+ geometry.setIndex(new BufferAttribute(group.cut, 1));
482
+ const mesh = new InstancedMesh(geometry, this.#options.material, this.#placed.length);
483
+ const built = this.#built as IClusteredBatchBuildOptions;
484
+ mesh.castShadow = built.castShadow ?? false;
485
+ mesh.receiveShadow = built.receiveShadow ?? false;
486
+ mesh.frustumCulled = false;
487
+ mesh.name = `${built.name ?? ""}-group`;
488
+ root.add(mesh);
489
+ group.mesh = mesh;
490
+ return mesh;
491
+ }
492
+ }