@threenative/core 0.3.11 → 0.3.13

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