@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,714 @@
1
+ import {
2
+ type Box3,
3
+ type Camera,
4
+ Frustum,
5
+ type InstancedMesh,
6
+ type Material,
7
+ Matrix4,
8
+ type Object3D,
9
+ Vector3,
10
+ } from "three";
11
+ import { renderGroup, uniform } from "three/tsl";
12
+ import type { BundleGroup } from "three/webgpu";
13
+ import { lodChainOf } from "./model-lod.js";
14
+ import {
15
+ VIRTUAL_SHADOW_KEY_LAYER,
16
+ VIRTUAL_SHADOW_SMALL_CASTER_LAYER,
17
+ } from "./render/virtual-shadow-layers.js";
18
+ import {
19
+ type ITemporalLod,
20
+ advanceTemporalLod,
21
+ worldLodMaterial,
22
+ } from "./render/world-impostor-surface.js";
23
+ import type { IRendererLike } from "./renderer.js";
24
+ import { markStatic } from "./static-transform.js";
25
+ import type { ICasterScaleMesh, SharedBatch } from "./world-cell-batches.js";
26
+ import { levelTriangles } from "./world-cell-chunks.js";
27
+ import type { IAssetPart, IBatchShape, ICellBatch, IKeyDescriptor } from "./world-cell-data.js";
28
+ import { cullDistance, isAlphaFoliage } from "./world-cell-impostors.js";
29
+ import type { IAssetState } from "./world-cell-models.js";
30
+ import {
31
+ UNDITHERED_LOD_WIDTH,
32
+ assertSlotFree,
33
+ freshMeshFor,
34
+ indirectView,
35
+ redressMaterial,
36
+ } from "./world-cell-render-util.js";
37
+ import type { ICellRenderHost } from "./world-cell-render.js";
38
+ import {
39
+ VIRTUAL_SHADOW_CASTER_LAYER,
40
+ VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
41
+ } from "./world-chunk-shadow.js";
42
+ import {
43
+ DRAW_ARGS_BYTES,
44
+ type IAssetSlot,
45
+ type ILiveAsset,
46
+ type IMeshDraw,
47
+ type IShadowLevel,
48
+ type WorldGpuScene,
49
+ liveKeyInstances,
50
+ } from "./world-gpu-scene.js";
51
+
52
+ /**
53
+ * The mesh a key draws: its shape, its level's material, and the dress that points it at the GPU
54
+ * scene's own buffers once the scene can run.
55
+ *
56
+ * A key's mesh is a view over shared storage, not a copy of the world: the same attributes, a fresh
57
+ * object (three binds the `instanceMatrix` an object held when it built its node), and an indirect
58
+ * record that names the region the dispatch compacts into. Everything here is that translation, plus
59
+ * the gate table the dispatch reads for the asset the key belongs to.
60
+ */
61
+
62
+ /** The gate table one asset publishes to the dispatch: its slots plus the part offsets it draws. */
63
+ export interface IPublishedGpuGates extends IAssetSlot {
64
+ readonly locals: readonly (readonly Float32Array[])[];
65
+ }
66
+
67
+ /** What a dress needs from the renderer it dresses for. */
68
+ export interface ICellGpuDressHost {
69
+ // The render host, by the names this module calls.
70
+ add(object: Object3D): void;
71
+ asset(id: string): IAssetState | undefined;
72
+ camera(): Camera | undefined;
73
+ canonical(id: string): string;
74
+ carryPrewarm(old: ICasterScaleMesh, next: ICasterScaleMesh): void;
75
+ isBundleHome(shared: SharedBatch): boolean;
76
+ renderer(): IRendererLike | undefined;
77
+
78
+ // The batches, the scene and the state the dress shares with the rest of the renderer.
79
+ shared(): Map<string, SharedBatch>;
80
+ retired(): Map<string, SharedBatch>;
81
+ resident(): Map<string, number>;
82
+ gpuScene(): WorldGpuScene;
83
+ lodMaterials(): Map<string, { readonly source: Material; readonly material: Material }>;
84
+ /** The adaptive LOD bias the kernel and the materials scale distance by. */
85
+ lodDistanceBias(): Parameters<typeof worldLodMaterial>[6];
86
+ lodHysteresis(): number;
87
+ lodTransition(): "band" | "none" | "temporal";
88
+ lodSpatial(): boolean;
89
+ receiveShadow(): boolean;
90
+ preserveAuthoredParts(): boolean;
91
+ freshCount(): number;
92
+ extentBounds(): Box3;
93
+ visibleSquares(): Set<string>;
94
+ freshAllowance(): number;
95
+
96
+ // The bundle record and the shadow claims, asked through the facade.
97
+ attach(shared: SharedBatch): void;
98
+ bumpBundle(group: BundleGroup): void;
99
+ bundleIn(shared: SharedBatch, reuseSafety?: boolean): void;
100
+ bundleOut(shared: SharedBatch): void;
101
+ shardOf(shared: SharedBatch): BundleGroup;
102
+ shadowFloorOf(assetId: string): number;
103
+ shadowKeyFor(key: IKeyDescriptor, part: IAssetPart): void;
104
+ }
105
+
106
+ /** The scratch a draw's own planes are built in, reused per frame. */
107
+ const _gpuEye = new Vector3();
108
+ const _cullFrustum = new Frustum();
109
+ const _cullProjScreen = new Matrix4();
110
+
111
+ export class CellGpuDress {
112
+ readonly #host: ICellGpuDressHost;
113
+
114
+ constructor(host: ICellGpuDressHost) {
115
+ this.#host = host;
116
+ }
117
+
118
+ readonly #publishedGpuGates = new Map<string, IPublishedGpuGates>();
119
+ readonly #gpuLevelKeys = new Map<string, Array<{ firstKey: number; parts: number }>>();
120
+ readonly #gpuPlanes = new Float32Array(24);
121
+
122
+ readonly #lodEye = uniform(new Vector3()).setGroup(renderGroup);
123
+
124
+ /** UE's two lagged view origins and their blend, for `lodTransition: "temporal"`. */
125
+ readonly #temporalLod: ITemporalLod = {
126
+ from: new Vector3(),
127
+ to: new Vector3(),
128
+ fromTime: Number.NaN,
129
+ toTime: Number.NaN,
130
+ alpha: 1,
131
+ };
132
+
133
+ readonly #lodFrom = uniform(this.#temporalLod.from).setGroup(renderGroup);
134
+
135
+ readonly #lodTo = uniform(this.#temporalLod.to).setGroup(renderGroup);
136
+
137
+ readonly #lodAlpha = uniform(1).setGroup(renderGroup);
138
+
139
+ /** Seconds since this renderer started; a swap stamps it so `worldLodMaterial` can fade the change. */
140
+ readonly #lodClock = uniform(0).setGroup(renderGroup);
141
+
142
+ readonly #lodClockOrigin = performance.now();
143
+
144
+ /**
145
+ * The shape the coarse wide half draws for one `(level, part)`, or `fallback` when the level has no
146
+ * honest coarse counterpart. Shared by {@link #shapeFor} and the prewarm, so the mesh minted behind
147
+ * the gate carries the same geometry the swap would later ask for — a prewarm built from the
148
+ * coarsest level's part 0 and then handed back unchanged is the wrong shape for good.
149
+ */
150
+ wideShape(
151
+ asset: IAssetState | undefined,
152
+ level: number,
153
+ part: number,
154
+ fallback: IBatchShape,
155
+ ): IBatchShape {
156
+ if (this.#host.preserveAuthoredParts()) return fallback;
157
+ const terminal = asset?.levels.at(-1);
158
+ // The whole-asset impostor is the one case where a part index has no meaning: it is a single
159
+ // representation of every LOD0 part, so every part routes through it. `terminal?.[0]` is only
160
+ // that shape. On the source-only path the terminal must have a part at this index with the same
161
+ // role — an alpha slot drawn with an opaque part's shape (or vice versa) is a different object,
162
+ // and a terminal with fewer parts must not fall back to part 0's, which duplicates it.
163
+ if (asset?.impostor !== undefined) {
164
+ const coarse = terminal?.[0];
165
+ if (coarse !== undefined) return coarse;
166
+ }
167
+ const coarse = terminal?.[part];
168
+ const source = asset?.levels[level]?.[part];
169
+ if (
170
+ coarse !== undefined &&
171
+ source !== undefined &&
172
+ isAlphaFoliage(source.material) === isAlphaFoliage(coarse.material)
173
+ )
174
+ return coarse;
175
+ return fallback;
176
+ }
177
+
178
+ shapeFor(
179
+ entry: ICellBatch,
180
+ role: "cluster" | "key" | "main" | "wide",
181
+ level = entry.level,
182
+ ): IBatchShape {
183
+ // A batch cast at a finer level than its own (`#castLevelOf`) draws that level's part.
184
+ const own =
185
+ level === entry.level
186
+ ? { geometry: entry.batch.geometry, material: entry.batch.material }
187
+ : (this.#host.asset(entry.asset)?.levels[level]?.[entry.part] as IAssetPart);
188
+ const shape =
189
+ role === "wide"
190
+ ? this.wideShape(this.#host.asset(entry.asset), level, entry.part, {
191
+ geometry: own.geometry,
192
+ material: own.material,
193
+ })
194
+ : { geometry: own.geometry, material: own.material };
195
+ return {
196
+ ...shape,
197
+ material: this.#lodSurface(entry.asset, level, entry.part, shape.material),
198
+ };
199
+ }
200
+
201
+ #lodSurface(assetId: string, level: number, partIndex: number, source: Material): Material {
202
+ assertSlotFree(source, assetId);
203
+ const asset = this.#host.asset(assetId);
204
+ const part = asset?.levels[level]?.[partIndex];
205
+ if (this.#host.lodHysteresis() <= 0 || !asset || !part || asset.distances.length < 2)
206
+ return source;
207
+ const publishedRanges = !this.#host.gpuScene().on;
208
+ const floor = this.#host.shadowFloorOf(assetId);
209
+ const key = `${assetId}:${level}:${partIndex}:${asset.distances.length}:${publishedRanges ? 1 : 0}:${floor}`;
210
+ let cached = this.#host.lodMaterials().get(key);
211
+ if (cached !== undefined && cached.source !== source) {
212
+ cached.material.dispose();
213
+ this.#host.lodMaterials().delete(key);
214
+ cached = undefined;
215
+ }
216
+ if (cached === undefined) {
217
+ const material = worldLodMaterial(
218
+ source,
219
+ part.local,
220
+ asset.distances,
221
+ level,
222
+ // Outside "band" the gate is too thin to cover a pixel step: each placement takes one level.
223
+ this.#host.lodTransition() === "band" ? this.#host.lodHysteresis() : UNDITHERED_LOD_WIDTH,
224
+ this.#lodEye,
225
+ this.#host.lodDistanceBias(),
226
+ this.#host.lodSpatial(),
227
+ publishedRanges,
228
+ // "none" pops: no clock, so a late refilter does not dissolve either.
229
+ this.#host.lodTransition() === "none" ? undefined : this.#lodClock,
230
+ this.#host.lodTransition() === "temporal"
231
+ ? { from: this.#lodFrom, to: this.#lodTo, alpha: this.#lodAlpha }
232
+ : undefined,
233
+ floor,
234
+ );
235
+ cached = { source, material };
236
+ this.#host.lodMaterials().set(key, cached);
237
+ }
238
+ return cached.material;
239
+ }
240
+
241
+ updateLodEye(x: number, y: number, z: number): void {
242
+ this.#lodEye.value.set(x, y, z);
243
+ this.#lodClock.value = (performance.now() - this.#lodClockOrigin) / 1000;
244
+ if (this.#host.lodTransition() !== "temporal") return;
245
+ advanceTemporalLod(this.#temporalLod, this.#lodEye.value, this.#lodClock.value);
246
+ this.#lodAlpha.value = this.#temporalLod.alpha;
247
+ }
248
+
249
+ refreshLodMaterials(asset: IAssetState): void {
250
+ for (const shared of this.#host.shared().values()) {
251
+ if (!shared.mesh.name.startsWith(`${asset.id}:`)) continue;
252
+ const [levelText, partText] = shared.mesh.name.slice(asset.id.length + 1).split(":");
253
+ const level = Number(levelText);
254
+ const partIndex = Number(partText?.split("@")[0]);
255
+ const part = asset.levels[level]?.[partIndex];
256
+ if (part !== undefined) {
257
+ const material = this.#lodSurface(asset.id, level, partIndex, part.material);
258
+ if (
259
+ material.userData.tnPublishedLodRange === true &&
260
+ shared.mesh.geometry.getAttribute("tnPublishedLodRange") === undefined &&
261
+ shared.mesh.count === 0
262
+ )
263
+ shared.rebind(part.geometry, material);
264
+ else shared.surface(material);
265
+ this.#host.bundleOut(shared);
266
+ this.#host.bundleIn(shared);
267
+ }
268
+ }
269
+ }
270
+
271
+ impostorDrawn(): number {
272
+ let drawn = 0;
273
+ for (const shared of this.#host.shared().values()) {
274
+ if (
275
+ shared.role === "main" &&
276
+ shared.mesh.visible &&
277
+ Reflect.get(shared.mesh.material, "userData")?.tnWholeAssetImpostor === true
278
+ )
279
+ drawn += shared.live;
280
+ }
281
+ return drawn;
282
+ }
283
+
284
+ /**
285
+ * The shadow half of the split, and the two granularities of it. A caster mesh lives alone on
286
+ * `VIRTUAL_SHADOW_CASTER_LAYER` — one per world-grid square, which a level whose window is a
287
+ * fraction of the ring culls down to the squares it covers — and a wide mesh alone on
288
+ * `VIRTUAL_SHADOW_WIDE_CASTER_LAYER`, one per key, which a level whose window covers the ring
289
+ * submits once. The level cameras draw one of the two layers and never both, so a key costs the
290
+ * main pass one draw, a fine level a few and a wide level one. Neither receives: nothing but a
291
+ * shadow level ever sees either. A main mesh keeps layer 0 and casts nothing, because its records
292
+ * reach the shadow maps only through a caster half.
293
+ */
294
+ dressMesh(shared: SharedBatch, receiveShadow: boolean): void {
295
+ const mesh = shared.mesh;
296
+ const role = shared.role;
297
+ // Every role's records are written into the instance buffer, never moved in the world, and the
298
+ // mesh is created and released per role — so this is the one place that covers a fresh mesh, a
299
+ // rebound one and the three roles. Static here is only safe because every write announces
300
+ // itself: `instanceMatrix.needsUpdate` bumps the attribute's version, which is what a settled
301
+ // draw watches to know it still has to scan.
302
+ markStatic(mesh);
303
+ if (role !== "main") {
304
+ mesh.layers.set(
305
+ role === "cluster"
306
+ ? VIRTUAL_SHADOW_CASTER_LAYER
307
+ : role === "key"
308
+ ? VIRTUAL_SHADOW_KEY_LAYER
309
+ : shared.smallCaster
310
+ ? VIRTUAL_SHADOW_SMALL_CASTER_LAYER
311
+ : VIRTUAL_SHADOW_WIDE_CASTER_LAYER,
312
+ );
313
+ mesh.castShadow = true;
314
+ mesh.receiveShadow = false;
315
+ return;
316
+ }
317
+ mesh.layers.set(0);
318
+ mesh.castShadow = false;
319
+ mesh.receiveShadow = receiveShadow;
320
+ // The origin a draw of this mesh is counted under until the GPU scene dresses it
321
+ // (`RenderPassBudget`). `#dressGpu` runs straight after this and overwrites it with `gpuScene`
322
+ // when the key really is dressed, so what survives here is a main batch the CPU path draws per
323
+ // object — a backend with no compute, `gpuScene: false`, or a dress that gave up. A caster half
324
+ // returns above and keeps no origin: it lives off layer 0, so the main pass never counts it.
325
+ mesh.userData.tnDrawSource = "instanced";
326
+ // Nothing to hang off a main mesh: the window is narrowed by `#cullMainPass` for the whole set,
327
+ // because a batch that drew nothing is hidden and three never reaches an invisible mesh's own
328
+ // hooks — a mesh that could only re-narrow itself in its `onBeforeRender` would stay hidden for
329
+ // as long as the camera looked away. That leaves `onBeforeRender` to the prewarm borrow alone.
330
+ }
331
+
332
+ /**
333
+ * Name one main key to the GPU scene, and dress its mesh against the scene's live buffers.
334
+ *
335
+ * A caster or wide key is named `@x,z` or `@*` and belongs to the shadow passes, which the GPU scene
336
+ * does not touch, so those are left exactly as they were.
337
+ *
338
+ * The key is recorded whether or not the scene is on, because a prewarm mints a whole ring before
339
+ * the first frame that can answer whether this backend can run the scene, and a key recorded only
340
+ * when the dress happened is a key the scene is never told about. `#seedGpuKeys` comes back for
341
+ * those; see there.
342
+ */
343
+ adoptGpu(shared: SharedBatch, assetId: string, key: string, level: number, part: number): void {
344
+ if (shared.role !== "main") return;
345
+ const named = { asset: this.#host.canonical(assetId), key, level, part };
346
+ shared.main = named;
347
+ if (this.#host.gpuScene().on === false) return;
348
+ shared.gpu = named;
349
+ this.dressGpu(shared, named);
350
+ }
351
+
352
+ /**
353
+ * The coarse gate for the GPU-dressed main pass, computed per asset and reused across every level
354
+ * and part of it.
355
+ *
356
+ * A key's own CPU squares are the level the follow point picked when it built them, and the
357
+ * dispatch re-picks the level from the camera every frame — so a key the CPU never gave a cell to
358
+ * can be exactly the one the dispatch draws, and a per-key answer hid it: a tree walked into at a
359
+ * level it was not built at disappeared. One conservative answer per asset — any key holds a
360
+ * visible cell, or still owes its prewarm draw — is what shows all of them, and the indirect
361
+ * record decides what each one actually draws.
362
+ */
363
+ applyGpuMain(dressed: readonly { asset: string; shared: SharedBatch }[]): void {
364
+ const shown = new Map<string, boolean>();
365
+ for (const { asset, shared } of dressed) {
366
+ if (shown.get(asset) === true || shared.seenIn(this.#host.visibleSquares()))
367
+ shown.set(asset, true);
368
+ else if (shown.has(asset) === false) shown.set(asset, false);
369
+ }
370
+ for (const { asset, shared } of dressed) shared.applyGpuVisible(shown.get(asset) === true);
371
+ }
372
+
373
+ /**
374
+ * Point one main key's mesh at the GPU scene's buffers, and hand the asset's gate table over.
375
+ *
376
+ * The mesh's `instanceMatrix` becomes the shared compacted matrix buffer, its geometry a clone that
377
+ * shares the part's own attributes and carries this key's indirect record, and its whole-mesh
378
+ * frustum test is off — the dispatch already tested every instance against the camera's six
379
+ * planes, and the mesh's own bounds are the whole resident ring. Idempotent: a settled frame's
380
+ * buffers are the ones it was dressed against, and a regrow, a rebind or a `grow` replaces them,
381
+ * which is the only thing that brings a dressed mesh back through here.
382
+ *
383
+ * A key whose placements outgrew its region is regrown here rather than silently dropping instances
384
+ * against the capacity guard, which is what a fixed ceiling did to any key a walk filled past.
385
+ *
386
+ * The buffers are read after `scene.key` rather than before it, because minting the first key is
387
+ * what allocates them: a dress that gave up on their absence was a dress that never happened, and
388
+ * the only frame that would have retried it was one whose fast path had already found the mesh
389
+ * dressed. A regrow replaces them, so the attribute handed to the mesh is the one a draw will read.
390
+ */
391
+ dressGpu(shared: SharedBatch, key: IKeyDescriptor): void {
392
+ const scene = this.#host.gpuScene();
393
+ const asset = this.#host.asset(key.asset);
394
+ const part = asset?.levels[key.level]?.[key.part];
395
+ if (asset === undefined || part === undefined) return;
396
+ // The asset's own resident placements, not one level's share of them: a placement's level is
397
+ // decided per frame from where the camera is, so every level's region has to hold all of them.
398
+ const capacity = Math.max(shared.liveCeiling, this.#host.resident().get(key.asset) ?? 0);
399
+ const settled = scene.drawn;
400
+ const held = scene.regionOf(key.key);
401
+ // The args buffer and the drawn buffer are allocated and grown independently: minting a key
402
+ // grows `args` and leaves `drawn` the object it was, so the mesh's `instanceMatrix` and its
403
+ // indirect record can point at two different generations. The fast path used to watch only
404
+ // `drawn`, and a mesh left holding an old args record was one the dispatch no longer wrote —
405
+ // a forest that drew nothing while the readback said the counts were correct.
406
+ const geometry = shared.mesh.geometry;
407
+ const liveArgs = scene.args;
408
+ const bound =
409
+ liveArgs !== undefined &&
410
+ geometry.indirect === liveArgs &&
411
+ geometry.indirectOffset === (held?.argsIndex ?? -1) * DRAW_ARGS_BYTES;
412
+ if (
413
+ settled !== undefined &&
414
+ shared.mesh.instanceMatrix === settled &&
415
+ shared.mesh.frustumCulled === false &&
416
+ (held?.capacity ?? 0) >= capacity &&
417
+ bound &&
418
+ // Where the mesh hangs is part of what this pass owns: a batch that was retired and handed back
419
+ // by a rebind is a child of the world again, and the bundle that last recorded it no longer
420
+ // draws it. Without this the walk would re-mint a key into a bundle that is missing it.
421
+ this.#host.isBundleHome(shared)
422
+ ) {
423
+ // A sibling may have grown the level's capacity without moving this mesh, so the submission
424
+ // bound follows the live region rather than the dress that wrote it. See `gpuCount`.
425
+ shared.gpuCount = held?.capacity ?? shared.gpuCount;
426
+ this.#host.shadowKeyFor(key, part);
427
+ return;
428
+ }
429
+ const region = scene.key(key.key, new Float32Array(part.local.elements), capacity, {
430
+ group: `${key.asset}:${String(key.level)}`,
431
+ part: key.part,
432
+ // The whole run at once, so a part minted later lands in the slot `firstKey + part` names
433
+ // rather than at the end of the key space, where another level's key is in between.
434
+ parts: (asset.levels[key.level] as readonly IAssetPart[]).length,
435
+ });
436
+ if (region === undefined) return;
437
+ const levels = this.#gpuLevelKeys.get(key.asset) ?? [];
438
+ levels[key.level] = {
439
+ firstKey: region - key.part,
440
+ parts: asset.levels[key.level]?.length ?? 0,
441
+ };
442
+ this.#gpuLevelKeys.set(key.asset, levels);
443
+ const drawn = scene.drawn;
444
+ const args = scene.args;
445
+ const args2 = scene.regionOf(key.key);
446
+ if (drawn === undefined || args === undefined || args2 === undefined) return;
447
+ // Before the mesh is dressed, so the republish a replacement does takes the dressed branch and
448
+ // submits at this bound rather than at a zero the CPU never drew. See `gpuCount`.
449
+ shared.gpuCount = args2.capacity;
450
+ // Before the mesh is dressed, so the republish a replacement does takes the dressed branch: a
451
+ // batch that draws from the scene's buffers is shown by the per-asset gate in `#cullMainPass`,
452
+ // not by its own count.
453
+ shared.gpu = key;
454
+ const mesh = shared.mesh;
455
+ // Its own geometry object, so the indirect record is this mesh's, over the SAME attributes: the
456
+ // original is the shape the caster halves and a rebind still draw with. `clone()` would copy
457
+ // every vertex buffer of every key a second time.
458
+ const view = indirectView(mesh.geometry, args, args2.argsIndex * DRAW_ARGS_BYTES);
459
+ // A mesh three has already compiled cannot be re-dressed by writing fields onto it: its node
460
+ // binds the `instanceMatrix` the object held at that compile, and three keeps that binding for
461
+ // the object's whole life. A regrow is the same case — a new `drawn` attribute is a new binding
462
+ // for the same reason — so both take the same road: a fresh object carrying everything the old
463
+ // one had, and the old one let go. Measured on machinefall, where the prewarm had compiled every
464
+ // main batch on the CPU path: 3,724 indirect draws submitted in 2 s over records that were
465
+ // correct at draw time, and a dressed forest that drew nothing, until the meshes were fresh
466
+ // objects; a material of its own (below) never changed that on its own.
467
+ if (mesh.instanceMatrix !== drawn) {
468
+ const next = freshMeshFor(mesh, view, mesh.count) as ICasterScaleMesh;
469
+ redressMaterial(next);
470
+ this.#host.carryPrewarm(mesh, next);
471
+ this.seat(shared.replaceMesh(next), next);
472
+ next.instanceMatrix = drawn;
473
+ next.frustumCulled = false;
474
+ } else {
475
+ mesh.geometry = view;
476
+ mesh.instanceMatrix = drawn;
477
+ mesh.frustumCulled = false;
478
+ }
479
+ // What the record has to say for the draw to name a triangle: the view's own index count, which
480
+ // is the shape this key draws. The scene is told rather than left to guess, so its validation can
481
+ // hold the record against it.
482
+ scene.indexCount(key.key, view.index?.count ?? 0);
483
+ // The asset's gate table is built from the keys minted so far, so a level whose key is not minted
484
+ // yet carries no parts and the dispatch draws that level nowhere. Re-registering is a no-op while
485
+ // the table holds, and a rewrite when a key joined it.
486
+ scene.slot(key.asset, this.gatesOf(key.asset, asset));
487
+ // The origin this key's main-pass draws are counted under, read off the object at the draw
488
+ // (`RenderPassBudget`). Written after the mesh swap above, so a re-dressed fresh object carries
489
+ // it, and before `#bundleIn`, which supersedes it with `tnBundled` for a world with bundles on.
490
+ shared.mesh.userData.tnDrawSource = "gpuScene";
491
+ // The bundle the last settled frame replayed is now wrong: this pass minted or regrown a key,
492
+ // swapped the geometry, or took a fresh mesh object onto the scene's new buffers. Reaching here
493
+ // is one of the three, which is why this is the only place a re-record happens — the fast path
494
+ // above is every other frame of the walk.
495
+ this.#host.bundleIn(shared);
496
+ if (shared.bundled === true) this.#host.bumpBundle(this.#host.shardOf(shared));
497
+ // The shadow twin of this key, minted and dressed on the same pass that named the main one: a
498
+ // level that draws keys finds its mesh in the same frame the main pass found its buffer, and a
499
+ // regrown twin is re-dressed here rather than left on the buffer the dispatch replaced.
500
+ this.#host.shadowKeyFor(key, part);
501
+ }
502
+
503
+ /**
504
+ * The replacement takes the old object's place, and the old one is let go: `InstancedMesh.dispose`
505
+ * frees nothing the replacement shares — the vertex buffers and the part's own material belong to
506
+ * the refcount path that made them.
507
+ *
508
+ * Through `add` and `removeFromParent` rather than by writing `parent` and `children`, because
509
+ * three fires `childadded`/`childremoved` on the way and the clustered-mesh tracker answers the
510
+ * world's arrivals and departures by those alone. The old slot is restored afterwards, so the
511
+ * parent's traversal order — and so every draw's order within a frame — is what it was.
512
+ */
513
+ seat(old: InstancedMesh, next: InstancedMesh): void {
514
+ const parent = old.parent;
515
+ if (parent === null) this.#host.add(next);
516
+ else {
517
+ const at = parent.children.indexOf(old);
518
+ old.removeFromParent();
519
+ parent.add(next);
520
+ const here = parent.children.indexOf(next);
521
+ if (at >= 0 && here >= 0) {
522
+ parent.children.splice(here, 1);
523
+ parent.children.splice(at, 0, next);
524
+ }
525
+ }
526
+ old.dispose();
527
+ }
528
+
529
+ /**
530
+ * The asset's own gates, as the kernel reads them: the CPU path's switch distances and cull
531
+ * distance, and the scene key each level's parts draw into. A level with no minted key has no parts,
532
+ * so the dispatch draws nothing at that level rather than reading a key that is not there.
533
+ */
534
+ publishGpuGates(asset: IAssetState): void {
535
+ const gates = this.gatesOf(asset.id, asset);
536
+ this.#publishedGpuGates.set(asset.id, {
537
+ cull: gates.cull,
538
+ distances: [...gates.distances],
539
+ impostor: gates.impostor,
540
+ shadowFallback: gates.shadowFallback,
541
+ levels: gates.levels.map((level) => ({ ...level })),
542
+ locals: asset.levels.map((parts) =>
543
+ parts.map((part) => Float32Array.from(part.local.elements)),
544
+ ),
545
+ });
546
+ }
547
+
548
+ gatesOf(id: string, asset: IAssetState): IAssetSlot {
549
+ const gates: { firstKey: number; parts: number }[] = [];
550
+ // The level's own contiguous run, which is what the kernel's `firstKey + part` addresses. The
551
+ // owner records it when dressing the key; reading it back from the scene would make the mesh
552
+ // check agree with a corrupted GPU gate table instead of checking that table independently.
553
+ const keyed = this.#gpuLevelKeys.get(id);
554
+ for (const [level] of asset.levels.entries())
555
+ gates.push(keyed?.[level] ?? { firstKey: 0, parts: 0 });
556
+ return {
557
+ cull: cullDistance(asset.definition.maxDistance),
558
+ distances: asset.distances,
559
+ // A generated terminal gate is based on the unit asset sphere and scales per placement. An
560
+ // authored impostorDistance is already a world-metre cutoff and stays fixed across scales.
561
+ impostor: asset.impostor !== undefined && asset.definition.impostorDistance === undefined,
562
+ shadowFallback: asset.definition.lods === undefined,
563
+ levels: gates,
564
+ };
565
+ }
566
+
567
+ /**
568
+ * Dress every main batch the world already holds, the mirror of {@link #seedGpuSources} for the
569
+ * keys rather than the sources: the keys a prewarm minted on the loading screen were minted with
570
+ * the scene off, and a key is only named at mint time, so a ring built that way came up with an
571
+ * empty region table and every batch still drawing from its own buffer. The dispatch was drawing
572
+ * 21,094 placements into no region at all, and the validation marker said so — `compared=0` — for
573
+ * a scene that reported itself on.
574
+ *
575
+ * The pool is seeded with the rest: a retained key's mesh is handed back by a rebind rather than
576
+ * re-minted, and rebinding replaces the instance buffer, so a parked batch is undressed by the
577
+ * park and dressing it here is what leaves the walk with a key that is already in the table. From
578
+ * here every main batch carries `gpu`, which is what puts it on the dispatch's per-instance answer
579
+ * and off the CPU repack and the refilter.
580
+ */
581
+ seedGpuKeys(): void {
582
+ for (const shared of [...this.#host.shared().values()]) this.seedGpuKey(shared);
583
+ for (const shared of this.#host.retired().values()) this.seedGpuKey(shared);
584
+ }
585
+
586
+ /** Dress one undressed main batch, or leave a batch the scene does not touch. */
587
+ seedGpuKey(shared: SharedBatch): void {
588
+ // `main` is the key; `gpu` is the mesh pointing at the scene's buffers. A dressed mesh is left
589
+ // alone, and `#dressGpu` says so itself — it is idempotent against the buffers it was given.
590
+ if (shared.main === undefined || shared.gpu !== undefined) return;
591
+ this.dressGpu(shared, shared.main);
592
+ }
593
+
594
+ /**
595
+ * The main meshes the scene owns and the main meshes the world holds, live and pooled, which is
596
+ * the `dressed=N/M` the marker carries. A scene reporting itself on over a ring it never dressed
597
+ * read `dressed=0/21094` on nothing, so the number is the owner's: the scene cannot see the meshes.
598
+ */
599
+ gpuCensus(): { readonly dressed: number; readonly meshes: number } {
600
+ let dressed = 0;
601
+ let meshes = 0;
602
+ for (const batch of [...this.#host.shared().values(), ...this.#host.retired().values()]) {
603
+ if (batch.role !== "main") continue;
604
+ meshes += 1;
605
+ if (batch.gpu !== undefined) dressed += 1;
606
+ }
607
+ return { dressed, meshes };
608
+ }
609
+
610
+ /**
611
+ * Every dressed main mesh's own draw, and what this class's **live** state says it must be holding.
612
+ *
613
+ * The scene's own validation mirrors its own kernel, so a key, a record, a gate table and a mesh
614
+ * that do not correspond are one both sides reproduce and a check that reports `ok` over a forest
615
+ * drawn with another tree's geometry. These are the three numbers that are not the scene's: the
616
+ * mesh's own name, the record its own geometry points at (`indirectOffset`, which a dress wrote),
617
+ * and the instances the owner's own state selects for that name — `asset.distances` as
618
+ * {@link levelAt} reads it right now, `cullDistance(definition.maxDistance)`, the camera's own six
619
+ * planes over the scene's own placements, and each part's own offset composed in exactly as the
620
+ * dispatch composes it.
621
+ *
622
+ * Not the per-cell records this path's own refilter left behind: the GPU scene bypasses that
623
+ * refilter, so the moment it does, the records a mesh is checked against are a snapshot of a
624
+ * level selection that no longer applies. A far placement is then compared against a set that
625
+ * counted it at its near level, and the check reads `ok` over the picture it cannot see.
626
+ */
627
+ gpuDraws(): readonly IMeshDraw[] {
628
+ const camera = this.#host.camera();
629
+ if (camera === undefined) return [];
630
+ const lives = this.liveGates();
631
+ if (lives.size === 0) return [];
632
+ // The dispatch's own camera, its own planes: this is asked for inside the dispatch that is
633
+ // running, so the eye and the six planes are the ones the kernel is reading now.
634
+ const planes = this.#gpuPlanes;
635
+ _cullFrustum.setFromProjectionMatrix(
636
+ _cullProjScreen.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
637
+ );
638
+ for (const [index, plane] of _cullFrustum.planes.entries()) {
639
+ const at = index * 4;
640
+ planes[at] = plane.normal.x;
641
+ planes[at + 1] = plane.normal.y;
642
+ planes[at + 2] = plane.normal.z;
643
+ planes[at + 3] = plane.constant;
644
+ }
645
+ _gpuEye.setFromMatrixPosition(camera.matrixWorld);
646
+ const expected = liveKeyInstances(
647
+ this.#host.gpuScene().placements,
648
+ (slot) => {
649
+ const id = this.#host.gpuScene().slotAsset(slot);
650
+ return id === undefined ? undefined : lives.get(id);
651
+ },
652
+ { planes, x: _gpuEye.x, y: _gpuEye.y, z: _gpuEye.z },
653
+ );
654
+ const draws: IMeshDraw[] = [];
655
+ const args = this.#host.gpuScene().args;
656
+ for (const shared of this.#host.shared().values()) {
657
+ if (shared.role !== "main" || shared.gpu === undefined) continue;
658
+ const geometry = shared.mesh.geometry;
659
+ // `indirectOffset` is typed as an offset or a list of them; a scene's own record is one
660
+ // number, and a list is not a record this check can name, so it is not compared.
661
+ const offset = geometry.indirectOffset;
662
+ if (geometry.indirect === undefined || typeof offset !== "number") continue;
663
+ const region = this.#host.gpuScene().regionOf(shared.mesh.name);
664
+ draws.push({
665
+ // The actual binding, asked of the mesh and the scene at this turn, not the record number:
666
+ // an offset can name the right record while the mesh reads an older args buffer with the
667
+ // same layout, and the field is what lets the check see a stale binding at all.
668
+ bound:
669
+ args !== undefined &&
670
+ geometry.indirect === args &&
671
+ offset === (region?.argsIndex ?? -1) * DRAW_ARGS_BYTES,
672
+ instances: expected.get(shared.mesh.name) ?? new Float32Array(0),
673
+ name: shared.mesh.name,
674
+ record: offset / DRAW_ARGS_BYTES,
675
+ });
676
+ }
677
+ return draws;
678
+ }
679
+
680
+ /**
681
+ * Every adopted asset's own gates as they stand right now, keyed by id.
682
+ *
683
+ * The part offsets are copied out of each part's `Matrix4` once per check, because the composition
684
+ * reads them as `Float32Array`s and a part's matrix is what the dispatch already composed with.
685
+ */
686
+ liveGates(): Map<string, ILiveAsset> {
687
+ const out = new Map<string, ILiveAsset>();
688
+ const slots = this.#host.gpuScene().gates();
689
+ for (const [slot] of slots.entries()) {
690
+ const id = this.#host.gpuScene().slotAsset(slot);
691
+ const asset = id === undefined ? undefined : this.#host.asset(id);
692
+ const published = id === undefined ? undefined : this.#publishedGpuGates.get(id);
693
+ if (asset === undefined || published === undefined) continue;
694
+ out.set(asset.id, {
695
+ cull: published.cull,
696
+ distances: published.distances,
697
+ id: asset.id,
698
+ impostor: published.impostor,
699
+ locals: published.locals,
700
+ });
701
+ }
702
+ return out;
703
+ }
704
+ /** Give back the gate tables, which a lost device makes stale. */
705
+ release(): void {
706
+ this.#publishedGpuGates.clear();
707
+ this.#gpuLevelKeys.clear();
708
+ }
709
+
710
+ /** The clock a swap stamps a rebuilt key's ranges with, in seconds since this renderer started. */
711
+ get clockSeconds(): number {
712
+ return this.#lodClock.value as number;
713
+ }
714
+ }