@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,1216 @@
1
+ import {
2
+ Box3,
3
+ BufferGeometry,
4
+ DynamicDrawUsage,
5
+ InstancedBufferAttribute,
6
+ type InstancedMesh,
7
+ type Material,
8
+ Sphere,
9
+ Vector3,
10
+ } from "three";
11
+ import type { InstancedBatch } from "./instanced-batch.js";
12
+ import { currentWriteEpoch, pooledCapacity, pooledMesh } from "./render/mesh-pool.js";
13
+
14
+ /**
15
+ * Records a retired batch's instance buffer is shrunk to; see `SharedBatch.park`.
16
+ *
17
+ * A released batch holds no records, so what keeping it is buying is the uuid three built a node for,
18
+ * and the buffer is the whole of what that retention costs. At the batch's own ring capacity the
19
+ * walk's back-traffic costs more than the byte budget holds, so the budget evicts the very keys a
20
+ * walk is about to return to and the walk re-mints a mesh for each of them. Parked, a key costs
21
+ * `PARKED_SHARED_CAPACITY` records; `rebind` puts the capacity back before anything is written.
22
+ */
23
+ const PARKED_SHARED_CAPACITY = 1;
24
+
25
+ /**
26
+ * One asset part at one distance level, drawn for every resident cell by a single InstancedMesh.
27
+ *
28
+ * Each cell owns a block of the instance buffer, admitted as the count it needs and freed as one,
29
+ * so the draw object count is per asset part and level rather than per cell: a 25-cell ring of a
30
+ * 218-asset world was ~5,000 meshes and 20+ ms of CPU a frame in three's per-object render path.
31
+ *
32
+ * A shared batch packs its live instances at the front of the instance buffer, so `mesh.count` is
33
+ * the live total. It used to be `(the highest used segment + 1) * segmentSize`, which drew every
34
+ * zero-matrix slot of a partly filled segment and of every freed segment below the top one — tens of
35
+ * thousands of slots per pass — and each empty slot still ran the vertex shader over the whole mesh
36
+ * in the main pass and in every shadow pass. A block is now sized to its own cell's batch instead of
37
+ * to the asset's largest cell, and a freed or shortened block is compacted into the lowest hole, so
38
+ * the drawn range holds nothing but live records. The handles are opaque: `allocate` only hands one
39
+ * back to `write` and `clear`.
40
+ *
41
+ * A **main** batch is `clustered`, and that changes the packing: its blocks are laid out grouped by
42
+ * the world-grid square they sit in, the same square the caster clusters are keyed by, and
43
+ * {@link SharedBatch.cullFrom} narrows `mesh.count` to the squares the main camera's frustum covers.
44
+ * Three's whole-mesh frustum test cannot do this on its own — the bounds are the whole ring, so the
45
+ * test always passes and every instance behind or beside the camera is vertex-shaded. See
46
+ * {@link WorldCells.#cullMainPass} for which camera is allowed to decide.
47
+ */
48
+ /**
49
+ * A `SharedBatch`'s mesh plus the one field it publishes for a shadow level's size gate: the largest
50
+ * instance scale any live record carries. Duck-typed rather than augmented into `three`, the same as
51
+ * `isInstancedMesh` — `render/virtual-shadow.ts` reads it back off the mesh.
52
+ */
53
+ export interface ICasterScaleMesh extends InstancedMesh {
54
+ casterInstanceScale: number;
55
+ /**
56
+ * Whether the main pass will draw the records behind this caster half this frame; see
57
+ * {@link SharedBatch.setMainAdmitted}. Read by `VirtualShadowNode`'s probe beside the other two
58
+ * flags this class writes on a mesh.
59
+ */
60
+ mainAdmitted?: boolean;
61
+ }
62
+
63
+ /** One world-grid square's records in a clustered batch: how many of them there are. */
64
+ type ISquareSizes = Map<string, number>;
65
+
66
+ /**
67
+ * The one buffer a clustered regroup permutes through.
68
+ *
69
+ * A regroup is a permutation of `[0, drawn)`, and there is no in-place order for one: putting the
70
+ * visible squares at the front necessarily writes over squares that have not been copied out yet. A
71
+ * snapshot is the honest way to do it — read every block into here, then write the new layout back —
72
+ * and one buffer is enough for the whole world, because a regroup never nests and the largest
73
+ * main batch is the only bound on it. Module-level like the upload epoch, because there is one world
74
+ * drawing at a time.
75
+ */
76
+ let regroupScratch = new Float32Array(0);
77
+ let lodRangeScratch = new Float32Array(0);
78
+
79
+ const LOD_RANGE_ATTRIBUTE = "tnPublishedLodRange";
80
+ /** Floats per record in it: the levels published (min, max), the level a fade starts from (-1: none) and when. */
81
+ export const LOD_RANGE_STRIDE = 4;
82
+
83
+ function lodScratchFor(floats: number): Float32Array {
84
+ if (lodRangeScratch.length < floats) lodRangeScratch = new Float32Array(floats * 2);
85
+ return lodRangeScratch;
86
+ }
87
+
88
+ /** A scratch with room for `floats`, kept between regroups so a walk allocates it once. */
89
+ function scratchFor(floats: number): Float32Array {
90
+ if (regroupScratch.length < floats) regroupScratch = new Float32Array(floats * 2);
91
+ return regroupScratch;
92
+ }
93
+
94
+ /** Records a square's blocks hold, which is its share of the batch. */
95
+ function sizeOf(square: { blocks: Array<[number, number, number, string]> }): number {
96
+ let size = 0;
97
+ for (const block of square.blocks) size += block[2];
98
+ return size;
99
+ }
100
+
101
+ export function sameSquares(next: Set<string>, was: Set<string> | undefined): boolean {
102
+ if (was === undefined || was.size !== next.size) return false;
103
+ for (const cluster of next) if (!was.has(cluster)) return false;
104
+ return true;
105
+ }
106
+
107
+ export class SharedBatch {
108
+ mesh: ICasterScaleMesh;
109
+ #sourceGeometry: BufferGeometry;
110
+ readonly #rangeLevel: number;
111
+ #rangeAware: boolean;
112
+ /** The pass this batch draws in; see `#dressMesh`. Only `main` is clustered. */
113
+ readonly role: "cluster" | "key" | "main" | "wide";
114
+ /**
115
+ * Set by `WorldCells` from the asset's own bounds: a wide caster of ground cover goes on the
116
+ * finest level's small-caster layer rather than the wide one. Written after construction because
117
+ * `#segmentIn` re-dresses a grown mesh with nothing but the batch to hand, and a flag the batch
118
+ * carries is the one thing that survives that.
119
+ */
120
+ smallCaster = false;
121
+ /**
122
+ * Set when the GPU scene owns this batch's draw, with the key it was minted under. See
123
+ * `WorldCells#dressGpu`.
124
+ *
125
+ * It is a field rather than a name test because a dressed batch's `mesh.instanceMatrix` is the
126
+ * scene's shared compaction buffer, and everything below writes records into that attribute: a
127
+ * dressed batch keeps its bookkeeping and skips every byte of it, which is the whole of what the
128
+ * `gpu` guards in `write`, `clear`, `#settle`, `#touched` and `#publish` are.
129
+ */
130
+ gpu:
131
+ | {
132
+ readonly asset: string;
133
+ readonly level: number;
134
+ readonly part: number;
135
+ readonly key: string;
136
+ }
137
+ | undefined;
138
+ /**
139
+ * The instance count a GPU-dressed mesh is submitted with: its key's region capacity, written by
140
+ * `WorldCells#dressGpu`.
141
+ *
142
+ * A dressed mesh's own records are not what it draws — the dispatch appends survivors into the
143
+ * scene's shared buffer and the indirect record decides how many — so `#drawn` is not its count.
144
+ * Three skips the indirect draw entirely before the GPU ever reads the record when an
145
+ * `InstancedMesh.count` is zero (`RenderObject.getDrawParameters`), so the region's capacity is the
146
+ * submission bound: the record's own count draws what the GPU selected, and this only admits the
147
+ * submission. `0` until the mesh is dressed.
148
+ */
149
+ gpuCount = 0;
150
+ /**
151
+ * How many of this batch's live records the GPU scene holds a placement for, carried beside the
152
+ * buffer and the segments so admission is one comparison per caster half a frame. Incremented by
153
+ * `WorldCells#placeSources` and decremented by `#clearSegment`, where the asset's own `#gpuResident`
154
+ * count already moves; see {@link WorldCells.#publishCasterAdmission}.
155
+ */
156
+ gpuPlaced = 0;
157
+ /**
158
+ * Whether this batch's mesh is parented under one of the world's main record shards. Set by
159
+ * `WorldCells#bundleIn` and cleared by `#bundleOut`.
160
+ *
161
+ * It is a field rather than `mesh.parent` because a bundled mesh's `visible` is never written
162
+ * again: three fixes a bundle's render list when it records it, and the replay never re-reads
163
+ * visibility — so the two places that hide an empty batch have to know, and a mesh that has just
164
+ * been detached from the group by a retire has still been in the last recorded one.
165
+ */
166
+ bundled = false;
167
+ /**
168
+ * Last checked eligibility of this mesh. CPU draws revalidate bounded material graph snapshots
169
+ * and live object hooks each frame, so deep mutations can return the mesh to the per-object path.
170
+ */
171
+ bundlable = false;
172
+ bundleMaterialRevision = -1;
173
+ /**
174
+ * The instance count the world's last record of this mesh was cut at. A record freezes the draw's
175
+ * instance count, so a CPU-path batch's moving window is one re-record when this moves; a dressed
176
+ * batch submits its key's region capacity, which only the dress changes and which re-records there.
177
+ */
178
+ bundledCount = -1;
179
+ /**
180
+ * The same descriptor, recorded whether or not the GPU scene is on, which is the whole of what
181
+ * lets a mesh minted before the scene came up be dressed after it: `gpu` says the mesh draws from
182
+ * the scene's buffers, `main` says which key it would draw. A prewarm that mints a whole ring on a
183
+ * loading screen mints it with the scene off, and the first frame with a renderer turns it on.
184
+ */
185
+ main:
186
+ | {
187
+ readonly asset: string;
188
+ readonly level: number;
189
+ readonly part: number;
190
+ readonly key: string;
191
+ }
192
+ | undefined;
193
+ readonly #clustered: boolean;
194
+ readonly #segmentSize: number;
195
+ /** Block handle -> the block's first instance record. */
196
+ readonly #start = new Map<number, number>();
197
+ /** Block handle -> live records in it; the reserved count until `write` reports the real one. */
198
+ readonly #size = new Map<number, number>();
199
+ /** Block handle -> the world-grid square it sits in; only a clustered batch records it. */
200
+ readonly #blockCluster = new Map<number, string>();
201
+ /** World-grid square -> its records in the buffer, so the window can be summed. See `#regroup`. */
202
+ readonly #squareSizes: ISquareSizes = new Map();
203
+ /** The squares the last cull kept, how many records of the batch they are, and whether that is current. */
204
+ #visible: Set<string> | undefined;
205
+ /** The `visibleEpoch` this batch last laid itself out at; see {@link SharedBatch.cullFrom}. */
206
+ #packedEpoch = -1;
207
+ /** Reused across culls, so a repack allocates no set. */
208
+ #scratch: Set<string> = new Set();
209
+ #window = 0;
210
+ #narrowed = false;
211
+ /**
212
+ * A prewarmed batch whose first draw is still owed, so it is visible at count 0 until that draw
213
+ * counts. The draw is the whole of the prewarm; see {@link #publish}.
214
+ */
215
+ #awaitingPrewarm = false;
216
+ /**
217
+ * Whether the main pass will draw this batch's records this frame; a main batch is always
218
+ * admitted, so this only ever says something about a caster half. See
219
+ * {@link WorldCells.#publishCasterAdmission}.
220
+ */
221
+ #mainAdmitted = true;
222
+ /** Free record ranges `[from, to)`, sorted, disjoint and never adjacent. */
223
+ #free: Array<[number, number]> = [];
224
+ #handles = 0;
225
+ /** One past the last live record: the range the whole buffer holds. A clustered batch draws `#window`. */
226
+ #drawn = 0;
227
+ /** Block handle -> the AABB of the records it holds, and the union of those is the mesh's bounds. */
228
+ readonly #boxes = new Map<number, Box3>();
229
+ /** Block handle -> the largest instance scale in it; the union is published on the mesh. */
230
+ readonly #scales = new Map<number, number>();
231
+ /** Carried out of the last `#boxOf` pass, which already reads every record's basis. */
232
+ #maxScale = 0;
233
+ #localGeometry: BufferGeometry | undefined;
234
+ readonly #localCenter = new Vector3();
235
+ readonly #localHalf = new Vector3();
236
+ readonly #union = new Box3();
237
+ readonly #point = new Vector3();
238
+ /** This batch's own pending upload span, and the `update` it was opened in. See `#touched`. */
239
+ #pendingLow = 0;
240
+ #pendingHigh = 0;
241
+ #pendingEpoch = -1;
242
+
243
+ constructor(
244
+ geometry: BufferGeometry,
245
+ material: Material,
246
+ segmentSize: number,
247
+ segments: number,
248
+ name: string,
249
+ bounds: Box3,
250
+ role: "cluster" | "key" | "main" | "wide",
251
+ rangeLevel = 0,
252
+ ) {
253
+ this.role = role;
254
+ this.#sourceGeometry = geometry;
255
+ this.#rangeLevel = rangeLevel;
256
+ this.#rangeAware = material.userData.tnPublishedLodRange === true;
257
+ this.#clustered = role === "main";
258
+ this.#segmentSize = Math.max(1, segmentSize);
259
+ this.#bounds = bounds;
260
+ this.mesh = this.#meshFor(material, this.#segmentSize * segments, name, bounds);
261
+ this.#setGeometry(this.mesh.geometry);
262
+ this.#free = [[0, this.mesh.instanceMatrix.count]];
263
+ this.#ceiling = this.mesh.instanceMatrix.count;
264
+ this.#rebound();
265
+ }
266
+
267
+ /** This batch's own record ceiling; see {@link liveCeiling}. */
268
+ #ceiling = 0;
269
+
270
+ /** The package extent, the conservative fallback when a part's own box cannot be read. */
271
+ readonly #bounds: Box3;
272
+
273
+ #geometryFor(capacity: number): BufferGeometry {
274
+ if (this.#rangeAware === false) return this.#sourceGeometry;
275
+ const source = this.#sourceGeometry;
276
+ const view = new BufferGeometry();
277
+ for (const [name, attribute] of Object.entries(source.attributes))
278
+ view.setAttribute(name, attribute);
279
+ view.setIndex(source.index);
280
+ view.morphAttributes = source.morphAttributes;
281
+ view.morphTargetsRelative = source.morphTargetsRelative;
282
+ for (const group of source.groups) view.addGroup(group.start, group.count, group.materialIndex);
283
+ view.boundingBox = source.boundingBox;
284
+ view.boundingSphere = source.boundingSphere;
285
+ view.setDrawRange(source.drawRange.start, source.drawRange.count);
286
+ view.userData.tnPublishedLodRangeView = true;
287
+ const ranges = new InstancedBufferAttribute(
288
+ new Float32Array(capacity * LOD_RANGE_STRIDE),
289
+ LOD_RANGE_STRIDE,
290
+ );
291
+ ranges.setUsage(DynamicDrawUsage);
292
+ view.setAttribute(LOD_RANGE_ATTRIBUTE, ranges);
293
+ return view;
294
+ }
295
+
296
+ #setGeometry(geometry: BufferGeometry): void {
297
+ const previous = this.mesh.geometry;
298
+ this.mesh.geometry = geometry;
299
+ if (geometry.userData.tnPublishedLodRangeView === true) {
300
+ let views = this.mesh.userData.tnPublishedLodRangeViews as Set<BufferGeometry> | undefined;
301
+ if (views === undefined) {
302
+ views = new Set();
303
+ this.mesh.userData.tnPublishedLodRangeViews = views;
304
+ this.mesh.addEventListener("dispose", () => {
305
+ for (const view of views ?? []) view.dispose();
306
+ views?.clear();
307
+ });
308
+ }
309
+ views.add(geometry);
310
+ }
311
+ if (previous !== geometry && previous.userData.tnPublishedLodRangeView === true) {
312
+ (this.mesh.userData.tnPublishedLodRangeViews as Set<BufferGeometry> | undefined)?.delete(
313
+ previous,
314
+ );
315
+ previous.dispose();
316
+ }
317
+ }
318
+
319
+ #lodRangeAttribute(): InstancedBufferAttribute | undefined {
320
+ const attribute = this.mesh.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
321
+ return attribute instanceof InstancedBufferAttribute ? attribute : undefined;
322
+ }
323
+
324
+ /**
325
+ * Takes a pooled mesh with room for `capacity`, so a shared batch that outgrows its buffer keeps
326
+ * the uuid — and the node three built for it — instead of getting a new one. Every field a pooled
327
+ * mesh carries stale is written here, and the two shadow flags are set false because `grow` copies
328
+ * them off the mesh it replaces and the world sets them per level.
329
+ *
330
+ * The buffer the pool hands back is rounded up to a power of two, and this batch's ceiling is that
331
+ * buffer's count, so the LOD-range column is built from the same rounded count. Built from the
332
+ * request instead it is shorter than the records a full batch holds, and `#touched` then records a
333
+ * range past the end of the column's array: three's WebGPU backend turns that range into one
334
+ * `writeBuffer` larger than the buffer it made, which throws and stops the renderer drawing.
335
+ */
336
+ #meshFor(material: Material, capacity: number, name: string, bounds: Box3): ICasterScaleMesh {
337
+ const records = pooledCapacity(capacity);
338
+ const mesh = pooledMesh(this.#geometryFor(records), material, records) as ICasterScaleMesh;
339
+ mesh.name = name;
340
+ mesh.boundingBox = bounds.clone();
341
+ mesh.boundingSphere = bounds.getBoundingSphere(mesh.boundingSphere ?? new Sphere());
342
+ mesh.count = 0;
343
+ mesh.visible = false;
344
+ // Cullable, because the bounds are now this batch's own. Every camera three draws this mesh
345
+ // with — the main one and each virtual-shadow level's — asks first, which is what stops a 48 m
346
+ // shadow level from submitting every shared batch in the world.
347
+ mesh.frustumCulled = true;
348
+ mesh.castShadow = false;
349
+ mesh.receiveShadow = false;
350
+ (mesh.instanceMatrix.array as Float32Array).fill(0);
351
+ mesh.instanceMatrix.needsUpdate = true;
352
+ // A pooled mesh arrives carrying the last user's scale; nothing lives here yet.
353
+ mesh.casterInstanceScale = 0;
354
+ // Nor the last user's bundle membership: a mesh is only bundled while `WorldCells#bundleIn` says
355
+ // so, and the shadow node reads this marker to keep its texel gate off a bundled mesh.
356
+ mesh.userData.tnBundled = false;
357
+ // Nor the last caster's admission: a main batch is always admitted, and this mesh is not one.
358
+ mesh.mainAdmitted = true;
359
+ return mesh;
360
+ }
361
+
362
+ /** Point an empty batch at the parts a reload brought; see {@link rebind}. */
363
+ rebind(geometry: BufferGeometry, material: Material): this {
364
+ this.#sourceGeometry = geometry;
365
+ this.mesh.material = material;
366
+ this.#rangeAware = material.userData.tnPublishedLodRange === true;
367
+ this.#setGeometry(this.#geometryFor(this.mesh.instanceMatrix.count));
368
+ this.#localGeometry = undefined;
369
+ // A new surface is the one thing a rebind can bring that a mesh swap cannot, so what can be
370
+ // recorded has to be asked again: the answer cached for the old material is not this one's.
371
+ this.bundlable = false;
372
+ if (this.#parked > 1) this.#resize(this.#parked);
373
+ this.#rebound();
374
+ return this;
375
+ }
376
+
377
+ /**
378
+ * Swap the surface of a batch that may hold records. A range-aware surface reads the
379
+ * `tnPublishedLodRange` column, so a buffer without one gets it here, each record whole at this
380
+ * batch's level until the next write publishes its range: the terminal level's late gates turn a
381
+ * drawn batch range-aware, and the Wasm engine refuses a draw whose attribute is missing.
382
+ */
383
+ surface(material: Material): void {
384
+ this.mesh.material = material;
385
+ const aware = material.userData.tnPublishedLodRange === true;
386
+ if (aware === this.#rangeAware) return;
387
+ this.#rangeAware = aware;
388
+ this.#setGeometry(this.#geometryFor(this.mesh.instanceMatrix.count));
389
+ const ranges = this.#lodRangeAttribute();
390
+ if (ranges === undefined) return;
391
+ const values = ranges.array as Float32Array;
392
+ for (let at = 0; at < values.length; at += LOD_RANGE_STRIDE) {
393
+ values[at] = this.#rangeLevel;
394
+ values[at + 1] = this.#rangeLevel;
395
+ values[at + 2] = -1;
396
+ }
397
+ ranges.needsUpdate = true;
398
+ }
399
+
400
+ /** The capacity this batch had when it was parked; see {@link park}. */
401
+ #parked = 0;
402
+
403
+ /**
404
+ * Give up the instance buffer of a batch that holds no records, keeping the mesh.
405
+ *
406
+ * This is what makes a retained set affordable. Unparked, a walk's back-traffic costs a ring-sized
407
+ * buffer per key, so `RETIRED_SHARED_BYTES` could hold only the last few dozen keys of a world with
408
+ * hundreds of them, `#sharedFor` then found nothing to hand back, and the walk minted a second
409
+ * mesh for every key it returned to. Parked, the same keys cost `PARKED_SHARED_CAPACITY` records
410
+ * each and `rebind` gives the buffer back before the first record is written into it.
411
+ */
412
+ park(): this {
413
+ // The batch's own ceiling, never its mesh's `count`: a dressed batch's `instanceMatrix` is the
414
+ // GPU scene's shared compaction buffer, so its count is the whole world's, and parking by it
415
+ // turned one key's capacity into the whole buffer — `rebind` then resized every later batch
416
+ // against the world and the shared buffer regrew until the device refused it.
417
+ this.#parked = this.#ceiling;
418
+ // `gpu` too, not only a capacity over one: a dressed batch's `instanceMatrix` is the GPU scene's
419
+ // shared compaction buffer whatever its logical ceiling is, so a batch parked at a ceiling of one
420
+ // that skipped this resized nothing and left the retired mesh holding the whole world's records.
421
+ if (this.gpu !== undefined || this.#parked > PARKED_SHARED_CAPACITY)
422
+ this.#resize(PARKED_SHARED_CAPACITY);
423
+ return this;
424
+ }
425
+
426
+ /**
427
+ * Swap in an instance buffer of `capacity` records, and with it the free range and the drawn count
428
+ * the buffer is the record of. The mesh is off the world and holds no records when this runs, so
429
+ * `#start`, `#size` and `#boxes` are already empty and the one free range is the whole buffer.
430
+ */
431
+ #resize(capacity: number): void {
432
+ const mesh = this.mesh;
433
+ this.#setGeometry(this.#geometryFor(capacity));
434
+ mesh.instanceMatrix = new InstancedBufferAttribute(new Float32Array(capacity * 16), 16);
435
+ this.#ceiling = capacity;
436
+ this.#publish(0);
437
+ this.#free = [[0, capacity]];
438
+ this.#drawn = 0;
439
+ }
440
+
441
+ /**
442
+ * The mesh's own extent, the union of the blocks' boxes, written on every add and remove. A union
443
+ * over at most one box per resident cell is a few dozen comparisons, against a per-draw saving of
444
+ * every batch the camera does not overlap. `#compact` moves records between slots but never between
445
+ * blocks, so a block's box survives a compaction untouched.
446
+ */
447
+ #rebound(): void {
448
+ const box = this.#union;
449
+ let live = false;
450
+ for (const one of this.#boxes.values()) {
451
+ if (live === false) {
452
+ box.copy(one);
453
+ live = true;
454
+ } else box.union(one);
455
+ }
456
+ if (live === false) box.copy(this.#bounds);
457
+ (this.mesh.boundingBox as Box3).copy(box);
458
+ this.mesh.boundingSphere = this.mesh.boundingSphere ?? new Sphere();
459
+ box.getBoundingSphere(this.mesh.boundingSphere);
460
+ // The size a per-instance shadow gate reads, published next to the mesh rather than asked for
461
+ // again per level: the cluster's own sphere is ~24 m of grid square, so gating on it dropped
462
+ // nothing, while a fern is 0.3 m and every fern cluster clears every coarse level.
463
+ this.mesh.casterInstanceScale = live === false ? 0 : Math.max(...this.#scales.values());
464
+ }
465
+
466
+ /**
467
+ * The AABB of records `[from, from + count)` of the instance buffer, read from the bytes just
468
+ * written rather than from the batch that wrote them, so it is the same numbers the GPU gets. The
469
+ * half-extents are `|basis| * half`, which is the box a rotated or stretched instance of the part
470
+ * actually covers — a translate-only box would let a scaled trunk through the shadow cull.
471
+ */
472
+ #boxOf(from: number, count: number): Box3 {
473
+ const array = this.mesh.instanceMatrix.array as Float32Array;
474
+ const geometry = this.mesh.geometry;
475
+ if (this.#localGeometry !== geometry) {
476
+ this.#localGeometry = geometry;
477
+ if (geometry?.boundingBox === null || geometry?.boundingBox === undefined)
478
+ geometry?.computeBoundingBox?.();
479
+ const local = geometry?.boundingBox;
480
+ // No readable local box means no readable instances either; the package extent is the answer
481
+ // that cannot be wrong, and it is what these meshes carried before the blocks were sized.
482
+ if (local === undefined || local === null || local.isEmpty()) return this.#bounds;
483
+ this.#localCenter.copy(local.getCenter(this.#point));
484
+ this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
485
+ }
486
+ const cx = this.#localCenter.x;
487
+ const cy = this.#localCenter.y;
488
+ const cz = this.#localCenter.z;
489
+ const hx = this.#localHalf.x;
490
+ const hy = this.#localHalf.y;
491
+ const hz = this.#localHalf.z;
492
+ const out = new Box3();
493
+ let minX = Number.POSITIVE_INFINITY;
494
+ let minY = Number.POSITIVE_INFINITY;
495
+ let minZ = Number.POSITIVE_INFINITY;
496
+ let maxX = Number.NEGATIVE_INFINITY;
497
+ let maxY = Number.NEGATIVE_INFINITY;
498
+ let maxZ = Number.NEGATIVE_INFINITY;
499
+ let scale = 0;
500
+ for (let index = from; index < from + count; index += 1) {
501
+ const at = index * 16;
502
+ const m0 = array[at] as number;
503
+ const m1 = array[at + 1] as number;
504
+ const m2 = array[at + 2] as number;
505
+ const m4 = array[at + 4] as number;
506
+ const m5 = array[at + 5] as number;
507
+ const m6 = array[at + 6] as number;
508
+ const m8 = array[at + 8] as number;
509
+ const m9 = array[at + 9] as number;
510
+ const m10 = array[at + 10] as number;
511
+ const px = m0 * cx + m4 * cy + m8 * cz + (array[at + 12] as number);
512
+ const py = m1 * cx + m5 * cy + m9 * cz + (array[at + 13] as number);
513
+ const pz = m2 * cx + m6 * cy + m10 * cz + (array[at + 14] as number);
514
+ const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
515
+ const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
516
+ const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
517
+ if (px - ex < minX) minX = px - ex;
518
+ if (py - ey < minY) minY = py - ey;
519
+ if (pz - ez < minZ) minZ = pz - ez;
520
+ if (px + ex > maxX) maxX = px + ex;
521
+ if (py + ey > maxY) maxY = py + ey;
522
+ if (pz + ez > maxZ) maxZ = pz + ez;
523
+ // The largest column of the instance basis: the scale a fern or a trunk is drawn at.
524
+ const basis = Math.max(
525
+ Math.hypot(m0, m1, m2),
526
+ Math.hypot(m4, m5, m6),
527
+ Math.hypot(m8, m9, m10),
528
+ );
529
+ if (basis > scale) scale = basis;
530
+ }
531
+ this.#maxScale = scale;
532
+ out.min.set(minX, minY, minZ);
533
+ out.max.set(maxX, maxY, maxZ);
534
+ return out;
535
+ }
536
+
537
+ /** A handle for `count` free records, or `undefined` when the buffer has none and must grow. */
538
+ allocate(count: number, cluster?: string): number | undefined {
539
+ const at = this.#take(count);
540
+ if (at < 0) return undefined;
541
+ const handle = this.#handles;
542
+ this.#handles += 1;
543
+ this.#start.set(handle, at);
544
+ this.#size.set(handle, count);
545
+ // Only a clustered batch groups, so only it pays for the lookup. The square is the caller's
546
+ // cell's, and a cell's placements never move, so a record is only ever grouped when the cell
547
+ // holding it is admitted or evicted.
548
+ if (this.#clustered && cluster !== undefined) this.#blockCluster.set(handle, cluster);
549
+ return handle;
550
+ }
551
+
552
+ /**
553
+ * Doubles the buffer in a new mesh (same data), returning the one it replaces for the pool.
554
+ *
555
+ * The replacement comes from the pool, and what it replaces is offered back to it, so the pair
556
+ * costs one new uuid between them instead of one each. This used to push the old mesh onto an
557
+ * unbounded `retired` array that nothing ever read and nothing ever freed.
558
+ */
559
+ grow(): InstancedMesh | undefined {
560
+ const old = this.mesh;
561
+ if (this.gpu !== undefined) {
562
+ // A dressed batch's records are the GPU scene's, held in a buffer this batch must not copy,
563
+ // zero or regroup: its own share is the logical ceiling the next `#dressGpu` sizes the scene's
564
+ // region from, so growth is that number and nothing else. The live mesh is kept and nothing is
565
+ // returned: `#segmentIn` dresses, attaches and parks only a real replacement, and the next
566
+ // `#dressGpu` grows the region from this ceiling before the draw.
567
+ const was = this.#ceiling;
568
+ this.#ceiling = was * 2;
569
+ this.#hole(was, this.#ceiling);
570
+ return undefined;
571
+ }
572
+ const mesh = this.#meshFor(
573
+ old.material as Material,
574
+ old.instanceMatrix.count * 2,
575
+ old.name,
576
+ this.#bounds,
577
+ );
578
+ (mesh.instanceMatrix.array as Float32Array).set(old.instanceMatrix.array as Float32Array);
579
+ const oldRanges = old.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
580
+ const nextRanges = mesh.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
581
+ if (
582
+ oldRanges instanceof InstancedBufferAttribute &&
583
+ nextRanges instanceof InstancedBufferAttribute
584
+ ) {
585
+ (nextRanges.array as Float32Array).set(oldRanges.array as Float32Array);
586
+ nextRanges.needsUpdate = true;
587
+ }
588
+ mesh.castShadow = old.castShadow;
589
+ mesh.receiveShadow = old.receiveShadow;
590
+ this.mesh = mesh;
591
+ this.#setGeometry(mesh.geometry);
592
+ this.#ceiling = mesh.instanceMatrix.count;
593
+ this.#settle();
594
+ // The whole drawn range, because this is a different buffer. `#meshFor` left the new
595
+ // attribute's range list empty, and an empty list is how three is told "upload everything" — so
596
+ // before the coalescing below, this was the whole buffer by default and the records copied out
597
+ // of the old array reached the GPU. A narrow range here would leave the new buffer's first
598
+ // records as the zeros it was created with.
599
+ this.#touched(0, this.#drawn);
600
+ this.#rebound();
601
+ return old;
602
+ }
603
+
604
+ /**
605
+ * Swap in the object this batch draws with, and hand back the one it replaces.
606
+ *
607
+ * Every reference the batch holds is `this.mesh` read at the moment it is needed, so the swap is
608
+ * the field. What does not follow the field is what the batch derives rather than stores — the
609
+ * bounds, the instance scale, the count and the visibility published on the object, and the two
610
+ * containers a fresh object starts out without them in. Those are republished here from the
611
+ * batch's own records, so a replacement draws exactly what the object it replaced drew.
612
+ */
613
+ replaceMesh(next: ICasterScaleMesh): ICasterScaleMesh {
614
+ const old = this.mesh;
615
+ this.mesh = next;
616
+ this.#setGeometry(next.geometry);
617
+ this.mesh.boundingBox = this.mesh.boundingBox ?? new Box3();
618
+ this.mesh.boundingSphere = this.mesh.boundingSphere ?? new Sphere();
619
+ (next as { casterPrewarmOwed?: boolean }).casterPrewarmOwed = this.#awaitingPrewarm;
620
+ next.mainAdmitted = this.#mainAdmitted;
621
+ this.#rebound();
622
+ this.#publish(this.#drawn);
623
+ return old;
624
+ }
625
+
626
+ write(segment: number, batch: InstancedBatch, lodRanges?: Float32Array): void {
627
+ const start = this.#start.get(segment);
628
+ const reserved = this.#size.get(segment);
629
+ if (start === undefined || reserved === undefined) return;
630
+ if (this.gpu !== undefined) {
631
+ // The records themselves are the GPU scene's, written by its dispatch from the source buffer;
632
+ // what the coarse per-cell gate and the counters need is the per-square count and the total.
633
+ const cluster = this.#blockCluster.get(segment) ?? "";
634
+ this.#size.set(segment, batch.count);
635
+ this.#squareSizes.set(cluster, (this.#squareSizes.get(cluster) ?? 0) + batch.count);
636
+ this.#drawn += batch.count;
637
+ this.#publish(this.#drawn);
638
+ return;
639
+ }
640
+ const array = this.mesh.instanceMatrix.array as Float32Array;
641
+ const written = batch.writeMatrices(array, start);
642
+ const ranges = this.#lodRangeAttribute();
643
+ if (ranges !== undefined) {
644
+ const values = ranges.array as Float32Array;
645
+ if (lodRanges !== undefined)
646
+ values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), start * LOD_RANGE_STRIDE);
647
+ else
648
+ for (let index = 0; index < written; index += 1) {
649
+ const at = (start + index) * LOD_RANGE_STRIDE;
650
+ values[at] = this.#rangeLevel;
651
+ values[at + 1] = this.#rangeLevel;
652
+ values[at + 2] = -1;
653
+ values[at + 3] = 0;
654
+ }
655
+ values.fill(0, (start + written) * LOD_RANGE_STRIDE, (start + reserved) * LOD_RANGE_STRIDE);
656
+ ranges.needsUpdate = true;
657
+ }
658
+ array.fill(0, (start + written) * 16, (start + reserved) * 16);
659
+ if (written < reserved) this.#hole(start + written, start + reserved);
660
+ this.#size.set(segment, written);
661
+ // The block's extent, read from the records where they are now, because `#compact` is about to
662
+ // move them. The box is keyed by handle, so the move cannot falsify it.
663
+ if (written > 0) {
664
+ this.#boxes.set(segment, this.#boxOf(start, written));
665
+ this.#scales.set(segment, this.#maxScale);
666
+ } else {
667
+ this.#boxes.delete(segment);
668
+ this.#scales.delete(segment);
669
+ }
670
+ this.#settle();
671
+ this.#touched(start, written);
672
+ this.#rebound();
673
+ }
674
+
675
+ clear(segment: number): void {
676
+ const start = this.#start.get(segment);
677
+ if (start === undefined) return;
678
+ const size = this.#size.get(segment) ?? 0;
679
+ if (this.gpu !== undefined) {
680
+ // The mirrored half of `write`: the coarse gate and the live total follow the records that left,
681
+ // and no byte of the shared buffer is touched, because none of them were ever in it.
682
+ const cluster = this.#blockCluster.get(segment) ?? "";
683
+ this.#squareSizes.set(cluster, Math.max(0, (this.#squareSizes.get(cluster) ?? 0) - size));
684
+ this.#drawn -= size;
685
+ }
686
+ this.#start.delete(segment);
687
+ this.#size.delete(segment);
688
+ this.#blockCluster.delete(segment);
689
+ if (this.gpu !== undefined) {
690
+ // The block's range goes back to the free list, exactly as the CPU path's does below. Without
691
+ // this the GPU path's free list only ever shrank: a walk that streamed cells in and out
692
+ // exhausted it, `allocate` failed, `grow` doubled the batch's ceiling, and the scene's region
693
+ // — and with it the shared buffer — regrew for records that had already left.
694
+ this.#hole(start, start + size);
695
+ this.#publish(this.#drawn);
696
+ return;
697
+ }
698
+ (this.mesh.instanceMatrix.array as Float32Array).fill(0, start * 16, (start + size) * 16);
699
+ const ranges = this.#lodRangeAttribute();
700
+ if (ranges !== undefined) {
701
+ (ranges.array as Float32Array).fill(
702
+ 0,
703
+ start * LOD_RANGE_STRIDE,
704
+ (start + size) * LOD_RANGE_STRIDE,
705
+ );
706
+ ranges.needsUpdate = true;
707
+ }
708
+ this.#hole(start, start + size);
709
+ this.#settle();
710
+ // The drawn range, not nothing. `#compact` closed the hole by moving the topmost block down
711
+ // into it, so the bytes below `#drawn` changed and an empty range list is read by three as
712
+ // "upload the whole buffer" — a ring-sized write to zero a block that is no longer drawn.
713
+ this.#touched(0, this.#drawn);
714
+ this.#boxes.delete(segment);
715
+ this.#scales.delete(segment);
716
+ this.#rebound();
717
+ }
718
+
719
+ /** The first free range with room for `count` records, taken out of the list; -1 when there is none. */
720
+ #take(count: number): number {
721
+ for (let index = 0; index < this.#free.length; index += 1) {
722
+ const range = this.#free[index] as [number, number];
723
+ const size = range[1] - range[0];
724
+ if (size < count) continue;
725
+ if (size === count) this.#free.splice(index, 1);
726
+ else this.#free[index] = [range[0] + count, range[1]];
727
+ return range[0];
728
+ }
729
+ return -1;
730
+ }
731
+
732
+ /** Records `[from, to)` back as free, merged with every range it touches. */
733
+ #hole(from: number, to: number): void {
734
+ if (to <= from) return;
735
+ const free = this.#free;
736
+ free.push([from, to]);
737
+ free.sort((a, b) => a[0] - b[0]);
738
+ const merged: Array<[number, number]> = [];
739
+ for (const range of free) {
740
+ const last = merged[merged.length - 1];
741
+ if (last !== undefined && range[0] <= last[1]) {
742
+ if (range[1] > last[1]) last[1] = range[1];
743
+ continue;
744
+ }
745
+ merged.push(range);
746
+ }
747
+ this.#free = merged;
748
+ }
749
+
750
+ /**
751
+ * Closes every hole below the drawn range, so `mesh.count` is the live total: the topmost block
752
+ * moves into the lowest hole, or, when it does not fit, everything above the hole shifts down over
753
+ * it. Whatever sits past the topmost block is free again, so one cell's room serves the next cell
754
+ * instead of a `grow`, and the free list is left as the single tail range `[drawn, capacity)`.
755
+ */
756
+ #compact(): void {
757
+ const array = this.mesh.instanceMatrix.array as Float32Array;
758
+ for (;;) {
759
+ let drawn = 0;
760
+ let top = -1;
761
+ let topFrom = 0;
762
+ for (const [handle, start] of this.#start) {
763
+ const end = start + (this.#size.get(handle) ?? 0);
764
+ if (end <= drawn) continue;
765
+ drawn = end;
766
+ top = handle;
767
+ topFrom = start;
768
+ }
769
+ this.#drawn = drawn;
770
+ const lowest = this.#free[0];
771
+ if (top < 0 || lowest === undefined || lowest[0] >= drawn) break;
772
+ const [holeStart, holeEnd] = lowest;
773
+ const size = this.#size.get(top) ?? 0;
774
+ if (size <= holeEnd - holeStart) {
775
+ array.copyWithin(holeStart * 16, topFrom * 16, drawn * 16);
776
+ this.#lodRangeAttribute()?.array.copyWithin(
777
+ holeStart * LOD_RANGE_STRIDE,
778
+ topFrom * LOD_RANGE_STRIDE,
779
+ drawn * LOD_RANGE_STRIDE,
780
+ );
781
+ this.#start.set(top, holeStart);
782
+ if (holeEnd - holeStart > size) this.#free[0] = [holeStart + size, holeEnd];
783
+ else this.#free.shift();
784
+ this.#hole(topFrom, drawn);
785
+ this.#drawn = holeStart + size;
786
+ this.#touched(holeStart, size);
787
+ } else {
788
+ const shift = holeEnd - holeStart;
789
+ array.copyWithin(holeStart * 16, holeEnd * 16, drawn * 16);
790
+ this.#lodRangeAttribute()?.array.copyWithin(
791
+ holeStart * LOD_RANGE_STRIDE,
792
+ holeEnd * LOD_RANGE_STRIDE,
793
+ drawn * LOD_RANGE_STRIDE,
794
+ );
795
+ this.#free.shift();
796
+ for (const [handle, start] of this.#start) {
797
+ if (start >= holeEnd) this.#start.set(handle, start - shift);
798
+ }
799
+ for (const range of this.#free) {
800
+ if (range[0] >= holeEnd) {
801
+ range[0] -= shift;
802
+ range[1] -= shift;
803
+ }
804
+ }
805
+ this.#drawn = drawn - shift;
806
+ this.#touched(holeStart, this.#drawn - holeStart);
807
+ }
808
+ }
809
+ const capacity = this.mesh.instanceMatrix.count;
810
+ const free: Array<[number, number]> = [];
811
+ for (const [from, to] of this.#free) {
812
+ if (from < this.#drawn) free.push([from, to > this.#drawn ? this.#drawn : to]);
813
+ }
814
+ if (this.#drawn < capacity) free.push([this.#drawn, capacity]);
815
+ this.#free = free;
816
+ }
817
+
818
+ /**
819
+ * Close the holes a write, a clear or a grow left, the way this batch's role needs.
820
+ *
821
+ * A caster batch compacts: one square holds the key's records, so the lowest hole is where the
822
+ * topmost block belongs. A main batch regroups instead, because compaction would carry a block
823
+ * away from the square it belongs to and the frustum test reads the squares.
824
+ */
825
+ #settle(): void {
826
+ // A dressed batch's layout is the dispatch's: its `instanceMatrix` is the scene's shared buffer,
827
+ // so a compact or regroup here would read that buffer's count as this batch's capacity and
828
+ // shuffle the whole world's records. `write` and `clear` bypass this already; `grow` does too.
829
+ if (this.gpu !== undefined) return;
830
+ if (this.#clustered) {
831
+ this.#regroup();
832
+ // Records moved, so `mesh.count` is the live total again and the window has to be re-narrowed
833
+ // by the next draw — with no copy, because the regroup just put the squares in place.
834
+ this.#narrowed = false;
835
+ } else this.#compact();
836
+ }
837
+
838
+ /**
839
+ * Lay every live block out again, grouped by its world-grid square, `visible`'s squares first.
840
+ *
841
+ * A regroup is a permutation of `[0, drawn)` and there is no in-place order for one: writing the
842
+ * visible squares to the front necessarily lands on squares whose records have not been read out
843
+ * yet, in either direction. So every block is copied into {@link regroupScratch} and the new order
844
+ * is copied back — two passes over the drawn range, and only when a square entered or left the
845
+ * window, which on a settled camera is not once a frame.
846
+ *
847
+ * Squares keep their relative order within each half, so a residency change regroups in place and
848
+ * a cull that found the same set writes nothing. What each square holds is recorded here, because
849
+ * that is the only per-key data the window needs: the squares' world volumes belong to the grid,
850
+ * not to a key, and are derived once a frame for all of them. See {@link WorldCells.#cullMainPass}.
851
+ *
852
+ * Only the records that actually moved are handed to the upload, and on a walk that is usually the
853
+ * tail or nothing at all: the squares that stayed in the half they were in keep their offsets
854
+ * exactly, so a square crossing the boundary between the two halves moves the records from there
855
+ * to the boundary and leaves `[0, boundary)` byte-identical. Uploading `[0, drawn)` instead — which
856
+ * is what this did — re-sent a whole key's records to the GPU on every frame the window moved,
857
+ * which on a walking camera is most frames, and on the largest key in a 2 km walk measured
858
+ * **37 draws over 7 ms each**. An identity reorder now costs no bytes at all, and the rest costs
859
+ * the span that moved; `#touched` still widens a span over half the drawn range, so the ranges
860
+ * stay few and large rather than many and small.
861
+ */
862
+ #regroup(visible = this.#visible): void {
863
+ const array = this.mesh.instanceMatrix.array as Float32Array;
864
+ const rangeAttribute = this.#lodRangeAttribute();
865
+ const rangeArray = rangeAttribute?.array as Float32Array | undefined;
866
+ const squares = this.#squares();
867
+ let total = 0;
868
+ for (const square of squares) total += sizeOf(square);
869
+ const scratch = scratchFor(total * 16);
870
+ const rangeScratch =
871
+ rangeArray === undefined ? undefined : lodScratchFor(total * LOD_RANGE_STRIDE);
872
+ // The visible squares first. `filter` is stable, so both halves keep the order the buffer had
873
+ // them in and a residency change lays out exactly what the last one did.
874
+ const front = squares.filter((one) => visible?.has(one.cluster) ?? true);
875
+ const back = squares.filter((one) => !(visible?.has(one.cluster) ?? true));
876
+ let written = 0;
877
+ // Where the layout departed from the one the GPU holds: the first record written somewhere other
878
+ // than where it was read from, and the last one after it. `-1` until something moves, so an
879
+ // identity reorder touches nothing.
880
+ let movedFrom = -1;
881
+ let movedTo = 0;
882
+ this.#squareSizes.clear();
883
+ for (const square of [...front, ...back]) {
884
+ const union = new Box3();
885
+ for (const [handle, start, count] of square.blocks) {
886
+ scratch.set(array.subarray(start * 16, (start + count) * 16), written * 16);
887
+ if (rangeScratch !== undefined && rangeArray !== undefined)
888
+ rangeScratch.set(
889
+ rangeArray.subarray(start * LOD_RANGE_STRIDE, (start + count) * LOD_RANGE_STRIDE),
890
+ written * LOD_RANGE_STRIDE,
891
+ );
892
+ // Read before it is overwritten: a block written back to its own offset is a record the GPU
893
+ // already holds, and is the whole difference between a repack that costs nothing and one
894
+ // that re-uploads the key.
895
+ if (this.#start.get(handle) !== written) {
896
+ if (movedFrom < 0) movedFrom = written;
897
+ movedTo = written + count;
898
+ }
899
+ this.#start.set(handle, written);
900
+ const box = this.#boxes.get(handle);
901
+ // A fresh `Box3` is already empty, so the first block's box is the square's and every block
902
+ // after it unions into it.
903
+ if (box !== undefined) union.union(box);
904
+ written += count;
905
+ }
906
+ this.#squareSizes.set(square.cluster, sizeOf(square));
907
+ }
908
+ array.set(scratch.subarray(0, written * 16));
909
+ if (rangeArray !== undefined && rangeScratch !== undefined && rangeAttribute !== undefined) {
910
+ rangeArray.set(rangeScratch.subarray(0, written * LOD_RANGE_STRIDE));
911
+ rangeAttribute.needsUpdate = true;
912
+ }
913
+ this.#drawn = written;
914
+ const capacity = this.mesh.instanceMatrix.count;
915
+ this.#free = written < capacity ? [[written, capacity]] : [];
916
+ this.#window = this.#windowOf(visible);
917
+ // After `#drawn`, because `#touched` measures the span it may widen against the drawn range, and
918
+ // before the caller's own `#touched`, which the epoch unions with it rather than replacing it.
919
+ if (movedFrom >= 0) this.#touched(movedFrom, movedTo - movedFrom);
920
+ }
921
+
922
+ /**
923
+ * The live blocks, in buffer order and gathered into the squares they belong to.
924
+ *
925
+ * Buffer order is what "the squares keep their relative order" means, and it is not the order of
926
+ * `#start`, which is keyed by handle rather than by position. A square's blocks are only adjacent
927
+ * because the last regroup made them so — a cell admitted after that lands anywhere in the free
928
+ * tail — so the squares are gathered here and written out by {@link #regroup}, and it is these
929
+ * two orders that a residency change has to preserve.
930
+ */
931
+ #squares(): Array<{ cluster: string; blocks: Array<[number, number, number, string]> }> {
932
+ const blocks: Array<[number, number, number, string]> = [];
933
+ for (const [handle, start] of this.#start) {
934
+ const size = this.#size.get(handle) ?? 0;
935
+ if (size > 0) blocks.push([handle, start, size, this.#blockCluster.get(handle) ?? ""]);
936
+ }
937
+ blocks.sort((a, b) => a[1] - b[1]);
938
+ const squares: Array<{ cluster: string; blocks: typeof blocks }> = [];
939
+ const squareOf = new Map<string, number>();
940
+ for (const block of blocks) {
941
+ const cluster = block[3] as string;
942
+ const index = squareOf.get(cluster);
943
+ if (index === undefined) {
944
+ squareOf.set(cluster, squares.length);
945
+ squares.push({ cluster, blocks: [block] });
946
+ continue;
947
+ }
948
+ (squares[index] as { blocks: typeof blocks }).blocks.push(block);
949
+ }
950
+ return squares;
951
+ }
952
+
953
+ /** Records of the squares in `visible`, the count a clustered batch's `mesh.count` draws. */
954
+ #windowOf(visible: Set<string> | undefined): number {
955
+ if (visible === undefined) return this.#drawn;
956
+ let window = 0;
957
+ for (const [cluster, size] of this.#squareSizes) if (visible.has(cluster)) window += size;
958
+ return window;
959
+ }
960
+
961
+ /**
962
+ * Narrow the draw window to the visibility cells `visible` names, rewriting the instance buffer
963
+ * when this batch's own share of that set changed. `settled` when nothing had to be looked at,
964
+ * `narrowed` when the count was re-widened, `repacked` when records were copied.
965
+ *
966
+ * `visible` and `epoch` are the frame's answer, derived once for the whole main pass by
967
+ * {@link WorldCells.#cullMainPass}: one frustum, one set of visible visibility cells, and an epoch
968
+ * that only moves when that set did. A batch whose records have not moved since it last packed at
969
+ * that epoch answers `false` from two integer comparisons — no frustum, no set, no copy — which is
970
+ * the whole of a settled frame across the ~230 meshes of a 2 km walk. Before that it was every
971
+ * batch rebuilding a frustum from the same camera, allocating a set and re-testing its own per-key
972
+ * volumes: ~4 ms a frame of `compute` for an answer that had not changed.
973
+ *
974
+ * Three's whole-mesh test cannot do this at all: the mesh's bounds are every resident cell's, so on
975
+ * a 640 m ring the test always passes and every instance behind or beside the camera is
976
+ * vertex-shaded — which on a tree-heavy 2 km map is most of a 65 M-triangle main pass, and the
977
+ * whole cost of it is vertex work that half resolution does not touch.
978
+ *
979
+ * The cells are the main cull's own and the volumes are per placement (see
980
+ * {@link WorldCells.#cullMainPass}), which is what this narrowness is spent on: a cell's XZ is
981
+ * one world cell rather than a 128 m caster square, and its Y is the height its own placements
982
+ * reach rather than the whole map's terrain range.
983
+ *
984
+ * A draw that finds the same cells it found last time touches nothing at all: no copy, no
985
+ * `needsUpdate`, and therefore no attribute version — which is what a settled static draw watches
986
+ * to know it still has to scan.
987
+ */
988
+ cullFrom(visible: ReadonlySet<string>, epoch: number): "settled" | "narrowed" | "repacked" {
989
+ if (!this.#clustered) return "settled";
990
+ // A batch holding no square draws nothing whatever the camera found, so it is published empty
991
+ // and takes no set and no scan — a prewarmed batch sits in exactly this state.
992
+ if (this.#squareSizes.size === 0) {
993
+ this.#publish(0);
994
+ return "settled";
995
+ }
996
+ // Settled: the frame's set is the one this window was laid out at and no record joined or left
997
+ // since. O(1), and no allocation of any kind.
998
+ if (this.#narrowed && this.#packedEpoch === epoch) return "settled";
999
+ const next = this.#scratch;
1000
+ next.clear();
1001
+ for (const square of this.#squareSizes.keys()) if (visible.has(square)) next.add(square);
1002
+ // The same squares as the buffer holds: a residency change or a square elsewhere entering and
1003
+ // leaving the view. The layout is already right, so the window only has to be re-narrowed — a
1004
+ // residency change left `mesh.count` at the live total, and `#settle`'s regroup put the squares
1005
+ // in the window's order with no copy.
1006
+ if (sameSquares(next, this.#visible)) {
1007
+ this.#publish(this.#window);
1008
+ this.#narrowed = true;
1009
+ this.#packedEpoch = epoch;
1010
+ return "narrowed";
1011
+ }
1012
+ this.#regroup(next);
1013
+ // The reorder hands its own upload, over the records that actually moved — a window that moved
1014
+ // a square across the half boundary and left every record where it was costs nothing here, which
1015
+ // is the walking camera's common case. See `#regroup`.
1016
+ // The layout now belongs to the other set, so the two trade places and the next cull reuses the
1017
+ // one this batch is no longer holding.
1018
+ const was = this.#visible;
1019
+ this.#visible = next;
1020
+ this.#scratch = was ?? new Set();
1021
+ this.#scratch.clear();
1022
+ // `#publish` is what hides a window the camera narrowed to nothing, and what shows it again when
1023
+ // the camera turns back.
1024
+ this.#publish(this.#window);
1025
+ this.#narrowed = true;
1026
+ this.#packedEpoch = epoch;
1027
+ return "repacked";
1028
+ }
1029
+
1030
+ /** Live records this batch holds, whether the camera is drawing them or not. */
1031
+ get live(): number {
1032
+ return this.#drawn;
1033
+ }
1034
+
1035
+ /**
1036
+ * The record ceiling of this batch's *own* buffer, which is what a key's GPU region is sized from:
1037
+ * the same ring-sized ceiling the CPU path stops growing at. Held rather than read, because a
1038
+ * dressed batch's `mesh.instanceMatrix` is the GPU scene's shared buffer and its count is that
1039
+ * buffer's, not this key's.
1040
+ */
1041
+ get liveCeiling(): number {
1042
+ return this.#ceiling;
1043
+ }
1044
+
1045
+ /** Records `mesh.count` draws: every live one, until a cull narrows the window. */
1046
+ get drawn(): number {
1047
+ return this.#clustered ? this.#window : this.#drawn;
1048
+ }
1049
+
1050
+ /**
1051
+ * One coalesced upload per mesh, not one per moved, written or zeroed record range. Three's WebGPU
1052
+ * backend turns each entry of `updateRanges` into its own `GPUQueue.writeBuffer`, so the
1053
+ * per-range bookkeeping here was the walk's largest CPU cost: thousands of sub-1 KB vertex writes
1054
+ * per frame, over a second of a short walk spent on the queue. The dirty span is accumulated here
1055
+ * across every write, compact and clear of one update, so a frame that touches a mesh from
1056
+ * several directions still issues one writeBuffer. A span over half the drawn range becomes the
1057
+ * whole drawn range, which is never more bytes than the two halves it replaced.
1058
+ */
1059
+ #touched(from: number, count: number): void {
1060
+ // A dressed batch's records were never in this attribute, so there is nothing to upload and
1061
+ // nothing to put back in charge of culling: the dispatch decided what it drew.
1062
+ if (this.gpu !== undefined) return;
1063
+ const matrix = this.mesh.instanceMatrix;
1064
+ // A record is 16 array elements, and that is the unit `updateRanges` is in: three reads them
1065
+ // as element offsets into `array`, not as bytes.
1066
+ const drawn = this.#drawn * 16;
1067
+ const low0 = from * 16;
1068
+ const high0 = (from + count) * 16;
1069
+ // The pending span is ours, and it lasts one update. Three's WebGPU path uploads through the
1070
+ // interleaved buffer it derives from `instanceMatrix.array` and only that buffer's ranges are
1071
+ // cleared after the write, so the ranges on `instanceMatrix` are never consumed: they were
1072
+ // unioned in here forever, and after one wide write every later write re-uploaded the whole
1073
+ // drawn range. The epoch moves once per `update()`, and the render at the end of an update is
1074
+ // what consumes the span, so a fresh epoch is a fresh span.
1075
+ let low = low0;
1076
+ let high = high0;
1077
+ const epoch = currentWriteEpoch();
1078
+ if (this.#pendingEpoch === epoch) {
1079
+ if (this.#pendingLow < low) low = this.#pendingLow;
1080
+ if (this.#pendingHigh > high) high = this.#pendingHigh;
1081
+ }
1082
+ if (low > 0 && (high - low) * 2 > drawn) {
1083
+ low = 0;
1084
+ high = drawn;
1085
+ }
1086
+ this.#pendingLow = low;
1087
+ this.#pendingHigh = high;
1088
+ this.#pendingEpoch = epoch;
1089
+ matrix.clearUpdateRanges();
1090
+ if (high > low) matrix.addUpdateRange(low, high - low);
1091
+ matrix.needsUpdate = true;
1092
+ const ranges = this.#lodRangeAttribute();
1093
+ if (ranges !== undefined) {
1094
+ ranges.clearUpdateRanges();
1095
+ if (high > low)
1096
+ ranges.addUpdateRange(
1097
+ (low / 16) * LOD_RANGE_STRIDE,
1098
+ ((high - low) / 16) * LOD_RANGE_STRIDE,
1099
+ );
1100
+ ranges.needsUpdate = true;
1101
+ }
1102
+ this.#publish(this.#drawn);
1103
+ // Records are real, so the bounds are the ones `#rebound` just wrote and the mesh goes back to
1104
+ // being culled.
1105
+ this.mesh.frustumCulled = true;
1106
+ }
1107
+
1108
+ /**
1109
+ * The one place `mesh.count` is written, so a batch that would draw nothing is not submitted.
1110
+ *
1111
+ * In three r185's WebGPU path an `InstancedMesh` with `count === 0` still runs the whole per-draw
1112
+ * JS chain — nodes, bindings, pipeline, attributes — and only the backend's `getDrawParameters`
1113
+ * finally answers null. A walk census measured 322 of 871 main batch meshes and 437 of 1,574
1114
+ * caster meshes at count 0, so every empty batch was ~17 µs of CPU a frame for nothing drawn.
1115
+ * `visible` is the one flag three reads before any of that, so a batch with nothing to draw is
1116
+ * hidden here and shown again by the first write that gives it a record: a placement add, a
1117
+ * rebind of a retained batch, a residency change, or the main cull's window opening again.
1118
+ *
1119
+ * The exception is a batch still owed its prewarm draw, which stays visible *because* it is empty:
1120
+ * that one draw is what builds the node and the pipeline the loading screen exists to pay for,
1121
+ * and hiding it would hand the build to the first walk frame that wants the key. It hides as soon
1122
+ * as the draw is counted — see {@link prewarmDrew} — so this costs one zero-count draw per
1123
+ * prewarmed batch over the whole load, which is the cost the prewarm is for.
1124
+ */
1125
+ #publish(count: number): void {
1126
+ // A shadow key is submitted every render of a map that covers it: its own records are the
1127
+ // dispatch's, so an empty-looking key is one this map draws nothing of, not one to hide.
1128
+ if (this.role === "key") {
1129
+ this.mesh.count = this.gpuCount;
1130
+ this.mesh.visible = true;
1131
+ return;
1132
+ }
1133
+ // A dressed batch's instances are the GPU scene's, and its own `count` says nothing about how
1134
+ // many the dispatch kept — a zero there makes three skip the indirect draw before the GPU reads
1135
+ // the record at all. So the mesh is submitted at its region's capacity and the record decides
1136
+ // what draws; the per-asset coarse gate in `#cullMainPass` runs after this every frame and is
1137
+ // what shows it. Until then the prewarm draw is the one reason to stay visible *because* it is
1138
+ // empty: that submission is what builds the node and the pipeline.
1139
+ if (this.gpu !== undefined) {
1140
+ this.mesh.count = this.gpuCount;
1141
+ if (this.bundled === false) this.mesh.visible = this.#awaitingPrewarm;
1142
+ return;
1143
+ }
1144
+ this.mesh.count = count;
1145
+ this.mesh.visible = count > 0 || this.#awaitingPrewarm;
1146
+ }
1147
+
1148
+ /**
1149
+ * The GPU-driven main pass's coarse gate, asked per key and answered per asset: whether any of
1150
+ * this batch's CPU grid squares is in `visible`, or it still owes the draw that builds its node.
1151
+ *
1152
+ * It is deliberately *not* the draw decision. A key's squares are the level the CPU picked from the
1153
+ * follow point when it built them, and the dispatch re-picks the level from the camera every frame
1154
+ * — so a key holding no cell can be the one the dispatch draws, and hiding on its own empty answer
1155
+ * is how a tree disappeared on approach. The caller unions this across every level and part of the
1156
+ * asset and hands the asset's answer back; see `WorldCells#cullMainPass` and `applyGpuVisible`.
1157
+ */
1158
+ seenIn(visible: ReadonlySet<string>): boolean {
1159
+ if (this.#awaitingPrewarm) return true;
1160
+ for (const square of this.#squareSizes.keys()) if (visible.has(square)) return true;
1161
+ return false;
1162
+ }
1163
+
1164
+ /**
1165
+ * Apply the asset's conservative visibility answer to this dressed mesh, and publish the count a
1166
+ * draw and the census read. A bundled mesh is shown by its recorded bundle and never asked.
1167
+ */
1168
+ applyGpuVisible(shown: boolean): void {
1169
+ // The region's capacity, not this batch's own records: an empty-looking key — one the CPU built
1170
+ // at another level — must still submit its indirect draw, and the record inside it draws nothing
1171
+ // when the dispatch selected none. See `gpuCount`.
1172
+ this.mesh.count = this.gpuCount;
1173
+ this.mesh.visible = shown;
1174
+ }
1175
+
1176
+ /**
1177
+ * Owe this batch its prewarm draw, and show it: empty, unsubmitted work is not what a prewarm
1178
+ * wants, one submission is.
1179
+ *
1180
+ * The flag on the mesh is what `VirtualShadowNode`'s `#probe` reads: a caster is drawn by a level,
1181
+ * and a level picks one of the two caster layers, so a level that finds an owed caster renders
1182
+ * both — otherwise the half it did not pick would leave its prewarm casters unbuilt for the whole
1183
+ * walk. Engine bookkeeping on the mesh, beside the `casterInstanceScale` the probe already reads.
1184
+ */
1185
+ awaitPrewarmDraw(): void {
1186
+ this.#awaitingPrewarm = true;
1187
+ (this.mesh as { casterPrewarmOwed?: boolean }).casterPrewarmOwed = true;
1188
+ this.#publish(this.drawn);
1189
+ }
1190
+
1191
+ /**
1192
+ * Publish this batch's admission for the frame, on the mesh beside the other two flags the shadow
1193
+ * probe reads off it. A `main` batch has nothing to say — it is the truth the caster halves are
1194
+ * measured against — and writes its own mesh, which is on layer 0 and no level ever draws.
1195
+ */
1196
+ setMainAdmitted(admitted: boolean): void {
1197
+ if (this.role === "main" || this.#mainAdmitted === admitted) return;
1198
+ this.#mainAdmitted = admitted;
1199
+ this.mesh.mainAdmitted = admitted;
1200
+ }
1201
+
1202
+ /**
1203
+ * The owed draw is counted, or it can never come, so the batch follows the count again and hides
1204
+ * if no placement ever gave it a record. Only `visible` is written: the count three is submitting
1205
+ * this frame is the right one, and `#publish` would replace it with a window no cull has run for.
1206
+ */
1207
+ prewarmDrew(): void {
1208
+ this.#awaitingPrewarm = false;
1209
+ (this.mesh as { casterPrewarmOwed?: boolean }).casterPrewarmOwed = false;
1210
+ // A bundled mesh is in a render list three fixed when it recorded the bundle, and the replay
1211
+ // never re-reads visibility — so hiding it here would not save this frame's draw and would lose
1212
+ // the mesh from every record after the next structural change. See `bundled`.
1213
+ if (this.bundled === true) return;
1214
+ this.mesh.visible = this.mesh.count > 0;
1215
+ }
1216
+ }