@threenative/core 0.3.10 → 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 (158) 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 +10565 -22533
  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-camera-cull.ts +32 -1
  84. package/src/render-pass-budget.ts +34 -7
  85. package/src/renderProjection.ts +22 -0
  86. package/src/renderer.ts +92 -37
  87. package/src/snow-field.ts +1 -1
  88. package/src/spells/cast-pool.ts +361 -0
  89. package/src/spells/index.ts +177 -0
  90. package/src/spells/mechanisms.ts +295 -0
  91. package/src/spells/reaction-field.ts +415 -0
  92. package/src/spells/spell-lights.ts +139 -0
  93. package/src/spells/spell-world.ts +187 -0
  94. package/src/spells/spell.ts +397 -0
  95. package/src/spells/spells.ts +283 -0
  96. package/src/spells/ultra/engine/camera.ts +184 -0
  97. package/src/spells/ultra/engine/quality.ts +96 -0
  98. package/src/spells/ultra/index.ts +52 -0
  99. package/src/spells/ultra/main.ts +305 -0
  100. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  101. package/src/spells/ultra/spells/cast.ts +233 -0
  102. package/src/spells/ultra/spells/fire.ts +1267 -0
  103. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  104. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  105. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  106. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  107. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  108. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  109. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  110. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  111. package/src/spells/ultra/vfx/common.ts +1195 -0
  112. package/src/spells/ultra/vfx/noise.ts +441 -0
  113. package/src/startup-readiness.ts +128 -34
  114. package/src/version.ts +1 -1
  115. package/src/warmup.ts +56 -8
  116. package/src/water-surface.ts +9 -3
  117. package/src/world-bundle-safety.ts +401 -0
  118. package/src/world-cell-batches.ts +1216 -0
  119. package/src/world-cell-chunks.ts +1132 -0
  120. package/src/world-cell-data.ts +995 -0
  121. package/src/world-cell-impostors.ts +1449 -0
  122. package/src/world-cell-lod-bias.ts +151 -0
  123. package/src/world-cell-models.ts +1074 -0
  124. package/src/world-cell-options.ts +189 -0
  125. package/src/world-cell-placements.ts +694 -0
  126. package/src/world-cell-prewarm.ts +557 -0
  127. package/src/world-cell-readiness.ts +357 -0
  128. package/src/world-cell-render-bundles.ts +459 -0
  129. package/src/world-cell-render-gpu-dress.ts +714 -0
  130. package/src/world-cell-render-main-cull.ts +484 -0
  131. package/src/world-cell-render-shadow-claims.ts +198 -0
  132. package/src/world-cell-render-util.ts +246 -0
  133. package/src/world-cell-render.ts +1493 -0
  134. package/src/world-cell-residency.ts +745 -0
  135. package/src/world-cells.ts +1318 -10418
  136. package/src/world-chunk-shadow.ts +308 -0
  137. package/src/world-collar.ts +315 -0
  138. package/src/world-gpu-flags.ts +163 -0
  139. package/src/world-gpu-readback.ts +881 -0
  140. package/src/world-gpu-reference.ts +510 -0
  141. package/src/world-gpu-scene.ts +214 -2264
  142. package/src/world-gpu-shadow.ts +190 -0
  143. package/src/world-gpu-types.ts +381 -0
  144. package/src/world-gpu-validation.ts +518 -0
  145. package/src/world-heightfield.ts +802 -0
  146. package/src/world-load-limiter.ts +106 -0
  147. package/src/world-noise.ts +241 -0
  148. package/src/world-package.ts +42 -0
  149. package/src/world-region.ts +1 -1
  150. package/src/world-terrain-splat.ts +365 -149
  151. package/src/world-tile-budget.ts +256 -0
  152. package/src/world-tile-geometry.ts +469 -0
  153. package/src/world-tile-lod.ts +408 -0
  154. package/src/world-tile-observation.ts +566 -0
  155. package/src/world-tile-stitch.ts +166 -0
  156. package/src/world-tiles.ts +170 -1745
  157. package/src/world-water-bodies.ts +359 -0
  158. package/src/world.ts +35 -741
@@ -1,3 +1,44 @@
1
+ import {
2
+ DRAW_ARGS_WORDS,
3
+ LIVE_MATRIX,
4
+ LOCAL_WORDS,
5
+ MATRIX_REPORTED_KEYS,
6
+ MATRIX_TOLERANCE,
7
+ MEMORY_FIELDS,
8
+ VALIDATE_REPORTED_KEYS,
9
+ compareMeshDraws,
10
+ compose,
11
+ sameGates,
12
+ sameLocal,
13
+ sameMatrices,
14
+ validationReport,
15
+ word,
16
+ xyz,
17
+ zeroComparisonProbe,
18
+ } from "./world-gpu-validation.js";
19
+
20
+ import type {
21
+ GpuSceneMemory,
22
+ GpuSceneVerdict,
23
+ IGpuSceneComparison,
24
+ IGpuSceneValidation,
25
+ IMeshDraw,
26
+ } from "./world-gpu-validation.js";
27
+
28
+ export type {
29
+ IMeshDraw,
30
+ IMeshDrawComparison,
31
+ GpuSceneVerdict,
32
+ IGpuSceneValidation,
33
+ GpuSceneMemoryField,
34
+ GpuSceneMemory,
35
+ IValidationNearest,
36
+ IValidationProbe,
37
+ IGpuSceneComparison,
38
+ } from "./world-gpu-validation.js";
39
+
40
+ export { compareMeshDraws, validationReport } from "./world-gpu-validation.js";
41
+
1
42
  import {
2
43
  type BufferAttribute,
3
44
  type Camera,
@@ -41,6 +82,104 @@ import {
41
82
  } from "./render/depth-pyramid.js";
42
83
  import type { IRendererLike } from "./renderer.js";
43
84
 
85
+ // The split's modules, re-exported here so every importer of this file keeps its imports: the types
86
+ // and layout constants, the CPU reference, and the launch flags all answer from where they always
87
+ // did.
88
+ export type {
89
+ BufferName,
90
+ IAssetSlot,
91
+ IGpuPlacement,
92
+ IGpuSceneBufferFootprint,
93
+ IGpuSceneBuffers,
94
+ IKernelInput,
95
+ IKernelResult,
96
+ ILevelGroup,
97
+ ILevelKey,
98
+ IRegion,
99
+ IValidationReadbacks,
100
+ IValidationSnapshot,
101
+ StorageType,
102
+ } from "./world-gpu-types.js";
103
+ export {
104
+ DRAW_ARGS_BYTES,
105
+ NO_LOCAL,
106
+ PLACEMENT_WORDS,
107
+ PlacementStruct,
108
+ SLOT_NONE,
109
+ SOURCE_FLOOR,
110
+ STORAGE_PLAIN,
111
+ STORAGE_WORDS,
112
+ TALLY_EVERY,
113
+ VEC4_WORDS,
114
+ VALIDATE_EVERY,
115
+ addRange,
116
+ argsWords,
117
+ growBuffer,
118
+ storageAttribute,
119
+ storageElementBytes,
120
+ } from "./world-gpu-types.js";
121
+ export type { ILiveAsset, IShadowLevel } from "./world-gpu-reference.js";
122
+ export {
123
+ COARSEST_SHADOW_LEVEL,
124
+ cullAndSelect,
125
+ cullAndSelectShadow,
126
+ levelAtGates,
127
+ liveKeyInstances,
128
+ } from "./world-gpu-reference.js";
129
+ export {
130
+ BUNDLE_FLAG,
131
+ GPU_SCENE_FLAG,
132
+ GPU_SCENE_VALIDATE_FLAG,
133
+ SHADOW_GPU_KEYS_FLAG,
134
+ bundlesAsked,
135
+ bundlesRequested,
136
+ gpuSceneRequested,
137
+ gpuSceneValidationRequested,
138
+ lodFromFollowRequested,
139
+ shadowGpuKeysRequested,
140
+ } from "./world-gpu-flags.js";
141
+
142
+ import { shadowGpuKeysRequested } from "./world-gpu-flags.js";
143
+ import { type IOcclusionReport, WorldGpuReadback } from "./world-gpu-readback.js";
144
+ import {
145
+ COARSEST_SHADOW_LEVEL,
146
+ type IShadowLevel,
147
+ buildCullKernel,
148
+ cullAndSelect,
149
+ levelAtGates,
150
+ } from "./world-gpu-reference.js";
151
+ import { type IShadowBuffers, buildShadowKernel } from "./world-gpu-shadow.js";
152
+ import {
153
+ type BufferName,
154
+ type IAssetSlot,
155
+ type IDeviceLike,
156
+ type IGpuKernel,
157
+ type IGpuPlacement,
158
+ type IGpuSceneBufferFootprint,
159
+ type IGpuSceneBuffers,
160
+ type IKernelInput,
161
+ type IKernelResult,
162
+ type ILevelGroup,
163
+ type ILevelKey,
164
+ type IRegion,
165
+ type IValidationReadbacks,
166
+ type IValidationSnapshot,
167
+ NO_LOCAL,
168
+ PLACEMENT_WORDS,
169
+ PlacementStruct,
170
+ SLOT_NONE,
171
+ SOURCE_FLOOR,
172
+ STORAGE_PLAIN,
173
+ type StorageType,
174
+ TALLY_EVERY,
175
+ VALIDATE_EVERY,
176
+ VEC4_WORDS,
177
+ addRange,
178
+ argsWords,
179
+ growBuffer,
180
+ storageAttribute,
181
+ } from "./world-gpu-types.js";
182
+
44
183
  /**
45
184
  * The GPU-driven main pass of a streamed world: one compute dispatch culls and LOD-selects every
46
185
  * resident placement, appends the survivors into a shared compacted matrix buffer, and each main
@@ -52,988 +191,13 @@ import type { IRendererLike } from "./renderer.js";
52
191
  * and nothing at all per instance per frame.
53
192
  *
54
193
  * The per-instance logic exists twice on purpose: {@link cullAndSelect} is the reference, in plain
55
- * TypeScript, and the TSL kernel below mirrors it line for line. The tests run in node with no GPU,
56
- * so the reference is what is proved against the CPU path; the kernel is compiled in the browser.
57
- */
58
-
59
- /** Words one placement record holds: `mat4` + `centre` (xyz, radius) + `info` (asset slot, …; not `meta`, a reserved WGSL keyword). */
60
- const PLACEMENT_WORDS = 24;
61
- /** `DrawIndexedIndirect`: indexCount, instanceCount, firstIndex, baseVertex, firstInstance. */
62
- const DRAW_ARGS_WORDS = 5;
63
- /** The same record in bytes, which is the unit `BufferGeometry.setIndirect` takes its offset in. */
64
- export const DRAW_ARGS_BYTES = DRAW_ARGS_WORDS * 4;
65
-
66
- /**
67
- * How many words the args buffer holds for `keys` keys: one indirect record each, plus one word
68
- * each of measured-occlusion tally past the last record.
69
- *
70
- * The tally rides this buffer rather than a buffer of its own so a measured run reads the two out
71
- * of the one readback the GPU-selected tally already issues on its own clock — a second readback on
72
- * a second buffer is a second queue submission per window for eight bytes.
73
- */
74
- function argsWords(keys: number): number {
75
- return keys * DRAW_ARGS_WORDS + keys;
76
- }
77
- /** One `vec4` per key, per asset slot and per level gate. */
78
- const VEC4_WORDS = 4;
79
- /** `mat4` per key: the part's own offset inside the model, the same matrix the CPU composes. */
80
- const LOCAL_WORDS = 16;
81
- /** Slots a placement may name before the kernel is refused rather than read out of bounds. */
82
- const SLOT_NONE = -1;
83
-
84
- /**
85
- * One element of every WGSL type this module declares a storage buffer as, in array words.
86
- *
87
- * A storage binding's minimum size is one element of its declared type: a `mat4` buffer is 64 bytes
88
- * whether it holds one matrix or a thousand, and a bound buffer under that is not a wrong picture but
89
- * a refused pipeline — every dispatch on it is invalid, silently, and only the device complains. So
90
- * the element count and the element size are not two independent numbers here: they are written down
91
- * together, once, and every buffer is allocated from this table and nowhere else.
92
- */
93
- const STORAGE_WORDS = {
94
- /** `mat4` + `centre` (vec4) + `info` (vec4), so one placement is 96 bytes and one stride. */
95
- // quality-allow: the object key is the WGSL type name the kernel reads, so it keeps that spelling.
96
- // biome-ignore lint/style/useNamingConvention: the key is the WGSL type, spelled as the kernel declares it.
97
- GpuPlacement: PLACEMENT_WORDS,
98
- /** `mat4`, one per key: the part's own offset inside the model, the same one the CPU composes. */
99
- mat4: LOCAL_WORDS,
100
- /** `DrawIndexedIndirect`'s five words; `uint` is one word, so the element count is the word count. */
101
- uint: 1,
102
- /** One `vec4` per key, per asset slot and per level gate. */
103
- vec4: VEC4_WORDS,
104
- } as const;
105
-
106
- /** A WGSL type the cull kernel declares a storage buffer as, and {@link STORAGE_WORDS}'s key. */
107
- export type StorageType = keyof typeof STORAGE_WORDS;
108
-
109
- /** Bytes one element of `type` occupies, which is what a storage binding of it must be at least. */
110
- export function storageElementBytes(type: StorageType): number {
111
- return STORAGE_WORDS[type] * 4;
112
- }
113
-
114
- /**
115
- * One storage attribute holding `count` elements — at least one, because a zero-element binding is
116
- * a zero-byte buffer and zero bytes is under every declared type — of the WGSL `type` the kernel
117
- * binds it as.
118
- *
119
- * The class and the array class are parameters because three's three storage attributes differ only
120
- * in what the renderer does with them, and this module needs all three: a plain one, the instanced
121
- * buffer a dressed batch's `instanceMatrix` is, and the indirect records `BufferGeometry.setIndirect`
122
- * reads. Handing the item size in by hand is how `drawn` was allocated four words wide and bound as
123
- * a `mat4`: a one-element, 16-byte buffer against a 64-byte requirement, so the cull kernel never
124
- * ran on a real GPU at all. The size is not a free choice here, so it is not written at a call site.
125
- */
126
- function storageAttribute<A extends BufferAttribute>(
127
- ctor: new (count: Float32Array | Uint32Array, itemSize: number) => A,
128
- type: StorageType,
129
- count: number,
130
- array: Float32ArrayConstructor | Uint32ArrayConstructor = Float32Array,
131
- ): A {
132
- const words = STORAGE_WORDS[type];
133
- return new ctor(new array(Math.max(1, count) * words), words);
134
- }
135
- /** Dispatches between readbacks: a mapped buffer is a queue submission, so not every frame. */
136
- const VALIDATE_EVERY = 30;
137
- /**
138
- * Dispatches between the tally's own readbacks, on the same budget as a validation.
139
- *
140
- * The tally reads the same indirect args buffer a validation reads, so it reuses that readback path
141
- * and the renderer's one staging buffer rather than adding a second copy: when validation is on its
142
- * landed bytes feed the tally, and when it is off this is the interval alone.
143
- */
144
- const TALLY_EVERY = 30;
145
- /** Keys a mismatch line names before the rest are counted and not printed. */
146
- const VALIDATE_REPORTED_KEYS = 10;
147
- /** Keys a matrix or indirect-record line names, which carry more numbers than a count line does. */
148
- const MATRIX_REPORTED_KEYS = 5;
149
- /** Meshes a `mesh=` line names, on the same budget as the record lines above. */
150
- const MESH_REPORTED_MESHES = 5;
151
- /** Two matrices within this of each other are the same one written through a `mat4` product. */
152
- const MATRIX_TOLERANCE = 1e-3;
153
- /** Characters of a cause a `cause=` line carries, so one message cannot own the report. */
154
- const CAUSE_CHARS = 160;
155
-
156
- /**
157
- * A `mat4` world matrix, the placement's bounding-sphere centre and radius, and the asset slot whose
158
- * gates pick its level. One stride, so the CPU's `Float32Array` is the GPU's storage buffer with no
159
- * repacking and no type punning: the radius and the slot are small and exactly representable.
160
- */
161
- const PlacementStruct = struct({ matrix: "mat4", centre: "vec4", info: "vec4" }, "GpuPlacement");
162
-
163
- /** One resident placement as the source buffer holds it. */
164
- export interface IGpuPlacement {
165
- readonly matrix: Float32Array;
166
- /** X, Y, Z and the bounding-sphere radius; the frustum test reads the first three. */
167
- readonly centre: Float32Array;
168
- /** The asset slot in `0`; `SLOT_NONE` for a record whose cell has left the ring. */
169
- slot: number;
170
- /**
171
- * The placement's uniform scale, in `info.y`: the whole-asset impostor's terminal gate is the
172
- * base-sphere projected distance scaled by this, so a placement scaled ten times does not switch
173
- * to the atlas until it is ten times as far. `1` when a caller does not carry one.
174
- */
175
- scale?: number;
176
- }
177
-
178
- /** One asset's slots: its level gates and the keys each level's parts draw into. */
179
- export interface IAssetSlot {
180
- /** Level switch distances, ascending, `0` first; the same numbers the CPU path crosses at. */
181
- readonly distances: readonly number[];
182
- /** `maxDistance` less its eighth, or `undefined` for an asset with no cull distance. */
183
- readonly cull: number | undefined;
184
- /** Per level: the first key its parts draw into and how many parts it has. */
185
- readonly levels: readonly { readonly firstKey: number; readonly parts: number }[];
186
- /**
187
- * Whether the last level is a whole-asset impostor: its gate is the base-sphere projected
188
- * distance, and the placement's own scale is applied to it at selection. The reference and the
189
- * kernel both read it, so an impostor terminal and an authored one cannot be crossed differently.
190
- */
191
- readonly impostor?: boolean;
192
- /** Derived LODs keep the last casting shape; authored LODs may opt out. Defaults to true. */
193
- readonly shadowFallback?: boolean;
194
- }
195
-
196
- /** One key's region of the shared drawn buffer, and the args record that counts it. */
197
- export interface IRegion {
198
- /** Where this key's survivors are written. Moves only in a re-layout, which rewrites every record. */
199
- start: number;
200
- /** Instances this region holds. Grows only in a re-layout, which resizes the whole level. */
201
- capacity: number;
202
- readonly argsIndex: number;
203
- /** The part's own offset inside the model; drawn as `placement * local`, as the CPU does. */
204
- readonly local: Float32Array;
205
- /** The main key this region is, which is what the validation marker names a mismatch by. */
206
- readonly name?: string;
207
- /**
208
- * The dressed geometry's own index count, which the record's `indexCount` has to say for the draw
209
- * to name a triangle at all. The owner records it when it dresses the mesh — the scene does not
210
- * know what shape a key draws — and the validation holds the record against it.
211
- */
212
- indexCount: number;
213
- /**
214
- * This key has no shadow twin (its level is past the world's `castLevels`), so a shadow map drops
215
- * a placement the main pass draws here. The GPU twin reads the same fact as `keys.w`, which only a
216
- * minted twin sets.
217
- */
218
- readonly uncast?: boolean;
219
- }
220
-
221
- /**
222
- * One storage attribute widened by doubling until it holds `needed`, or itself when it already does.
223
- * The contents are carried over and marked as one upload range, which is what makes a regrow a copy
224
- * rather than a fresh zeroed buffer.
225
- */
226
- function growBuffer<A extends BufferAttribute>(
227
- current: A,
228
- needed: number,
229
- make: (count: number) => A,
230
- ): A {
231
- if (current.count >= needed) return current;
232
- let capacity = Math.max(1, current.count);
233
- while (capacity < needed) capacity *= 2;
234
- const grown = make(capacity);
235
- grown.array.set(current.array as Uint32Array);
236
- grown.addUpdateRange(0, current.array.length);
237
- return grown;
238
- }
239
-
240
- /** Adds an update range, extending the last one when the new range touches or overlaps it. */
241
- export function addRange(
242
- attribute: {
243
- updateRanges: { start: number; count: number }[];
244
- addUpdateRange(start: number, count: number): void;
245
- },
246
- start: number,
247
- count: number,
248
- ): void {
249
- const last = attribute.updateRanges[attribute.updateRanges.length - 1];
250
- if (last === undefined || start > last.start + last.count || start + count < last.start) {
251
- attribute.addUpdateRange(start, count);
252
- return;
253
- }
254
- const newStart = Math.min(last.start, start);
255
- // Set the count first. It is measured from the old start.
256
- last.count = Math.max(last.start + last.count, start + count) - newStart;
257
- last.start = newStart;
258
- }
259
-
260
- /** One level's parts and the single capacity all of them are sized from. */
261
- interface ILevelGroup {
262
- capacity: number;
263
- /**
264
- * The key index the level's run starts at, claimed whole at its first key and never moved, so
265
- * `firstKey + part` names that part's own key however the parts were minted. The run is claimed
266
- * rather than appended to because keys are not minted in level order: a prewarm mints every level
267
- * and part of one asset before the next, a walk that arrives mid-prewarm mints whatever its cell
268
- * needs, and the keys minted in between are not this level's. A run built by appending is a run
269
- * with another asset's keys inside it, and a gate table that names it draws that asset's placements
270
- * through this level's parts and this level's placements through the other's — which is a forest
271
- * drawn with another tree's geometry, and a check that reproduces the same addressing reads it as
272
- * agreement.
273
- */
274
- firstKey: number;
275
- /** How many parts the level has, which is the width of the run the gate table names. */
276
- parts: number;
277
- /** Part index to the region that part draws into; laid out in this order. */
278
- readonly minted: Map<number, number>;
279
- }
280
-
281
- /**
282
- * Which of a level's parts a key is, so the parts of one level stay the contiguous run the kernel
283
- * and the gate table both address as `firstKey + part`. `undefined` mints a key of its own, which
284
- * is every key a caller that has no level to be a part of wants.
285
- */
286
- export interface ILevelKey {
287
- /** The level this part belongs to — one group, however many parts it has. */
288
- readonly group: string;
289
- /** The part's own index in that level, which is the order the group is laid out in. */
290
- readonly part: number;
291
- /**
292
- * How many parts the level has altogether, so the run is claimed once and in full. The caller knows
293
- * it: the level is an array of parts, and every part of it will be asked for. A part outside the
294
- * run the level declared is refused rather than laid over another level's key.
295
- */
296
- readonly parts: number;
297
- }
298
-
299
- /** The offset a part that has not been minted yet draws with: none at all, and nowhere to draw. */
300
- const NO_LOCAL = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
301
-
302
- /** What the kernel reads, and the whole of what a dispatch touches. */
303
- export interface IKernelInput {
304
- readonly placements: readonly IGpuPlacement[];
305
- readonly count: number;
306
- readonly camera: {
307
- readonly planes: Float32Array;
308
- readonly x: number;
309
- readonly y: number;
310
- readonly z: number;
311
- };
312
- readonly slots: readonly IAssetSlot[];
313
- readonly regions: readonly IRegion[];
314
- readonly regionCount: number;
315
- /**
316
- * The hierarchical-depth occlusion test, when a launch asked for one. Absent, the frustum is the
317
- * whole visibility rule; present, every placement the frustum kept is reprojected into the
318
- * pyramid's own frame and tested. See {@link IKernelOcclusion}.
319
- */
320
- readonly occlusion?: IKernelOcclusion;
321
- }
322
-
323
- /** What one dispatch produced: the compacted survivors and the per-key instance counts. */
324
- export interface IKernelResult {
325
- /** `DRAW_ARGS_WORDS` per region, `1` the instance count; everything else is the CPU's. */
326
- readonly args: Uint32Array;
327
- readonly drawn: Float32Array;
328
- /** Instances drawn per region, which is what the args record's count must say. */
329
- readonly counts: Uint32Array;
330
- /**
331
- * What the pyramid test hid, and only when one ran: the instances and the triangles of every
332
- * placement it would have dropped. Absent is "no test ran", never "the test hid nothing" — a
333
- * measured run reads these while drawing every one of them.
334
- */
335
- readonly occluded?: { readonly instances: number; readonly triangles: number };
336
- }
337
-
338
- /**
339
- * One dispatch's own copy of everything its kernel read, taken while that dispatch runs, plus the
340
- * attribute the readback has to name.
341
- *
342
- * A streamed world changes its placement set, its gate table and its region layout between one frame
343
- * and the next, so a reference computed when a readback lands describes the frames that followed the
344
- * dispatch that produced the bytes — which is how a check that compared nothing came to report
345
- * `compared=0` over 21,147 resident placements. Copied at dispatch time, the reference is a pure
346
- * function of the snapshot and nothing that happens afterwards can change it.
347
- */
348
- interface IValidationSnapshot extends IKernelInput {
349
- /** The indirect records this dispatch wrote, which is what its readback must name. */
350
- readonly args: unknown;
351
- /** The shared matrix buffer this dispatch compacted into, which its other readback must name. */
352
- readonly drawn: unknown;
353
- /** Resident placements the scene held when this dispatch ran. */
354
- readonly placed: number;
355
- }
356
-
357
- interface IValidationReadbacks {
358
- readonly args: ReadbackBuffer;
359
- readonly drawn: ReadbackBuffer;
360
- }
361
-
362
- /**
363
- * The level one placement draws with, from an asset's gate table and the placement's own scale.
364
- *
365
- * Every gate but a whole-asset impostor's terminal is an authored world-metre distance, compared
366
- * directly. The impostor's terminal gate is the base-sphere *projected* distance: the atlas is
367
- * built for the asset's own LOD0 size, so a placement scaled ten times reaches the atlas ten times
368
- * as far — its threshold is `base * |scale|`, floored by the last source gate it must stay strictly
369
- * beyond. The floor is nudged one representable step past that gate: sharing the gate's own switch
370
- * distance would let the terminal overwrite the last source level at every distance past it, so the
371
- * source level would never draw. Read by {@link cullAndSelect} and mirrored by the kernel and the
372
- * CPU path, so all three cross the same switch.
373
- */
374
- export function levelAtGates(
375
- slot: Pick<IAssetSlot, "distances" | "impostor">,
376
- distance: number,
377
- scale: number,
378
- ): number {
379
- const last = slot.distances.length - 1;
380
- const magnitude = Number.isFinite(scale) ? Math.abs(scale) : 1;
381
- let level = 0;
382
- for (let index = 1; index < slot.distances.length; index += 1) {
383
- const gate = slot.distances[index] as number;
384
- const threshold =
385
- slot.impostor === true && index === last && last >= 1
386
- ? Math.max(strictlyAfterGate(slot.distances[last - 1] as number), gate * magnitude)
387
- : gate;
388
- if (distance > threshold) level = index;
389
- }
390
- return level;
391
- }
392
-
393
- /**
394
- * The last level at or below `level` that the scene can actually draw, which is where a placement
395
- * goes when the gates name one the prewarm has not minted keys for.
396
- *
397
- * `WorldCells#gatesOf` names every level of an asset from the moment it is adopted and fills in the
398
- * keys minted so far, so a chain that has widened holds `parts: 2,0,0,0` while the loading screen is
399
- * up. The CPU path draws `asset.levels[level]` whatever the gates name and always has a shape there;
400
- * a dispatch that took the named level would loop its zero keys and draw the placement nowhere, and
401
- * with the bias raised the placements past the last source gate are exactly the far ones — a forest
402
- * 80-300 m out standing in its own shadows, while the shadow halves, which take no bias and key
403
- * themselves, still draw. One level down is the finest shape the scene holds, which is the level the
404
- * prewarm is one frame from minting.
405
- */
406
- function drawableLevel(slot: Pick<IAssetSlot, "levels">, level: number): number {
407
- for (let at = level; at > 0; at -= 1) if ((slot.levels[at]?.parts ?? 0) > 0) return at;
408
- return 0;
409
- }
410
-
411
- /**
412
- * The level a shadow map draws a placement at, or -1 when no level of its asset casts. A placement
413
- * whose main level casts nothing falls back only when its asset permits it: derived chains past
414
- * `castLevels` keep their shadow, drawn in the last shape that has a twin, rather than
415
- * leaving a hole in the map (PRD-541). The level is then floored at the map's base and clamped to
416
- * the last level that casts, so a coarse map draws the coarsest shape that has a twin. `base` past
417
- * the chain is clamped by the chain length first.
418
- */
419
- function shadowLevel(
420
- slot: Pick<IAssetSlot, "levels" | "shadowFallback">,
421
- regions: readonly IRegion[],
422
- drawn: number,
423
- base: number,
424
- ): number {
425
- const casts = (at: number): boolean => {
426
- const gate = slot.levels[at];
427
- return gate !== undefined && gate.parts > 0 && regions[gate.firstKey]?.uncast !== true;
428
- };
429
- if (slot.shadowFallback === false && casts(drawn) === false) return -1;
430
- // At or below `drawn` any casting level qualifies, above it only up to the map's base, so the
431
- // last casting level in `[0, max(drawn, base)]` is both rules at once.
432
- const last = Math.max(drawn, Math.min(base, slot.levels.length - 1));
433
- let level = -1;
434
- for (let at = 0; at <= last; at += 1) if (casts(at)) level = at;
435
- return level;
436
- }
437
-
438
- /**
439
- * One representable Float32 step past a gate: `g * (1 + 2^-22)`, two f32 ULPs at `g`'s exponent.
440
- *
441
- * A floored terminal gate must start strictly after the source gate it is floored by and must stay
442
- * so once the threshold is stored and compared in f32, which a bare `g` does not: the terminal
443
- * shares `g`'s switch distance and the later gate wins every comparison, starving the source level.
444
- * A relative step, not a fixed metre margin, so the ordering holds at every authored scale.
445
- */
446
- const GATE_STEP = 2 ** -22;
447
-
448
- function strictlyAfterGate(gate: number): number {
449
- return gate + Math.abs(gate) * GATE_STEP;
450
- }
451
-
452
- /**
453
- * One shadow map's own three numbers, which is the whole of what a level render knows that the main
454
- * camera does not.
455
- *
456
- * They are the level's, never the camera's: a map's frustum is the light's window, its gate is the
457
- * texel size it can resolve, and its base is the chain level the cluster path hands it — `#probe`
458
- * swaps a coarse level's geometry for the coarsest shape, so a coarse map draws that shape whatever a
459
- * placement's own distance would have selected. The distance itself is the main pass's, from the
460
- * eye: a placement's shape and its cast come from the key the main pass draws it in.
461
- */
462
- export interface IShadowLevel {
463
- /** The six frustum planes of this map's own shadow camera. */
464
- readonly planes: Float32Array;
465
- /** This map's texel gate in world metres: a placement narrower than it casts nothing here. */
466
- readonly gate: number;
467
- /**
468
- * The chain level this map draws at, floored over the placement's own. 0 is the placement's own
469
- * LOD by distance — what the finest map draws — and the coarsest index is what every level past
470
- * the first draws. A base whose keys are not minted draws nothing, which is why a caller settling
471
- * the prewarm first is the contract rather than a fallback.
472
- *
473
- * {@link COARSEST_SHADOW_LEVEL} is past every chain, and means the coarsest shape an asset has: a
474
- * map that coarsens its casters does not know how long each asset's chain is, and the floor is
475
- * clamped per asset, so one number asks every chain for its own coarsest level.
476
- */
477
- readonly base: number;
478
- }
479
-
480
- /**
481
- * A {@link IShadowLevel.base} past every chain: the map draws every asset's coarsest shape, whatever
482
- * distance selected it. Clamped to each asset's own last level, so an owner with no level count to
483
- * hand — `VirtualShadowNode`, which coarsens a coarse level's casters without knowing an asset —
484
- * can still ask.
485
- */
486
- export const COARSEST_SHADOW_LEVEL = 1 << 20;
487
-
488
- /**
489
- * The per-instance kernel, in plain TypeScript. The TSL kernel in {@link WorldGpuScene} is this
490
- * loop with the same branches, and the test proves this one against the CPU path.
491
- *
492
- * One placement, in the order the source buffer holds them: a released record and a record whose
493
- * asset is unknown are skipped, the bounding sphere is tested against the camera's six planes, the
494
- * XZ distance picks the level through the asset's own gates and culls a record beyond its cull
495
- * distance, and each part of that level takes the next free slot in its key's region and writes
496
- * `placement * part offset` there. A region that is full is a dropped instance, never a write past
497
- * the end of the buffer.
498
- */
499
- export function cullAndSelect(input: IKernelInput): IKernelResult {
500
- return select(input, undefined);
501
- }
502
-
503
- /**
504
- * The same kernel with a shadow map's own four numbers in place of the camera's, and nothing else
505
- * changed: same regions, same keys, same `placement * part offset`, same capacity guard.
506
- *
507
- * The gate is applied to the placement's own diameter, where the cluster path applies it to the
508
- * whole mesh and drops the square with it — so on a uniform-size fixture the two sets are the same
509
- * set, and where a square mixes sizes this one is the finer of the two.
510
- */
511
- export function cullAndSelectShadow(input: IKernelInput, level: IShadowLevel): IKernelResult {
512
- return select(input, level);
513
- }
514
-
515
- /**
516
- * The one loop both references share. `shadow` is what makes the second one a variant rather than a
517
- * fork: the main camera's planes, eye, no gate and no base are the degenerate case, so the two can
518
- * never disagree by having been edited apart.
519
- */
520
- function select(input: IKernelInput, shadow: IShadowLevel | undefined): IKernelResult {
521
- const { placements, camera, regions, slots } = input;
522
- // A shadow map has no main camera to reproject into, so the test is the main pass's alone — a
523
- // caster the eye cannot see still casts.
524
- const occlusion = shadow === undefined ? input.occlusion : undefined;
525
- const planes = shadow?.planes ?? camera.planes;
526
- const metres = shadow?.gate ?? 0;
527
- const base = shadow?.base ?? 0;
528
- const counts = new Uint32Array(input.regionCount);
529
- const args = new Uint32Array(input.regionCount * DRAW_ARGS_WORDS);
530
- // The drawn buffer is the regions' own, so the reference allocates exactly what the GPU holds.
531
- const capacity = regions.reduce(
532
- (sum, region) => Math.max(sum, region.start + region.capacity),
533
- 0,
534
- );
535
- const matrix = new Float32Array(capacity * LOCAL_WORDS);
536
- for (const region of regions) {
537
- args[region.argsIndex * DRAW_ARGS_WORDS + 4] = region.start;
538
- }
539
- let occludedInstances = 0;
540
- let occludedTriangles = 0;
541
- for (let index = 0; index < input.count; index += 1) {
542
- const placement = placements[index];
543
- if (placement === undefined || placement.slot < 0) continue;
544
- const slot = slots[placement.slot];
545
- if (slot === undefined) continue;
546
- const at = placement.centre;
547
- const radius = at[3] as number;
548
- let visible = true;
549
- for (let plane = 0; plane < 6; plane += 1) {
550
- const offset = plane * 4;
551
- const signed =
552
- (planes[offset] as number) * (at[0] as number) +
553
- (planes[offset + 1] as number) * (at[1] as number) +
554
- (planes[offset + 2] as number) * (at[2] as number) +
555
- (planes[offset + 3] as number);
556
- if (signed < -radius) {
557
- visible = false;
558
- break;
559
- }
560
- }
561
- if (visible === false) continue;
562
- // Sub-texel, exactly as `#probe` decides it for a mesh: a caster this map cannot resolve casts
563
- // no shadow a fragment could tell from ground cover.
564
- if (radius * 2 < metres) continue;
565
- const distance = Math.hypot((at[0] as number) - camera.x, (at[2] as number) - camera.z);
566
- if (slot.cull !== undefined && distance > slot.cull) continue;
567
- // Cull above is the authored distance; the level below is the biased one for the main pass — the
568
- // same multiplier the kernel's uniform carries, so the reference and the dispatch cross a switch
569
- // together. A shadow map takes the main pass's own level, from the eye: that is the key a
570
- // placement is drawn in, and the cluster path casts each key's placements from that key's mesh.
571
- const drawn = drawableLevel(
572
- slot,
573
- levelAtGates(slot, biasedLodDistance(distance), placement.scale ?? 1),
574
- );
575
- const level = shadow === undefined ? drawn : shadowLevel(slot, regions, drawn, base);
576
- if (level < 0) continue;
577
- const gate = slot.levels[level];
578
- if (gate === undefined) continue;
579
- const hidden =
580
- occlusion !== undefined && occludedBy(occlusion, at, radius) ? occlusion : undefined;
581
- for (let part = 0; part < gate.parts; part += 1) {
582
- const region = regions[gate.firstKey + part];
583
- if (region === undefined) continue;
584
- // Counted either way: a measured run draws what it hides, so the count is the only place the
585
- // answer can live.
586
- if (hidden !== undefined) {
587
- occludedInstances += 1;
588
- occludedTriangles += region.indexCount / 3;
589
- if (hidden.cull) continue;
590
- }
591
- const taken = counts[gate.firstKey + part] as number;
592
- if (taken >= region.capacity) continue;
593
- counts[gate.firstKey + part] = taken + 1;
594
- args[region.argsIndex * DRAW_ARGS_WORDS + 1] = taken + 1;
595
- compose(placement.matrix, region.local, matrix, (region.start + taken) * LOCAL_WORDS);
596
- }
597
- }
598
- return {
599
- args,
600
- counts,
601
- drawn: matrix,
602
- ...(occlusion === undefined
603
- ? {}
604
- : { occluded: { instances: occludedInstances, triangles: occludedTriangles } }),
605
- };
606
- }
607
-
608
- /**
609
- * One asset's gates as its owner last published them: the source representation and its
610
- * `asset.distances`/`cullDistance(definition.maxDistance)` snapshot at the completed swap boundary.
611
- *
612
- * Deliberately not an {@link IAssetSlot}. A slot is what this class wrote into its own table, and a
613
- * table written before the owner's model widened its chain is the exact thing the check exists to
614
- * catch — feeding it back in as the reference is the check agreeing with itself.
615
- */
616
- export interface ILiveAsset {
617
- /** The asset id a main key is named `asset:level:part` with, which is the owner's own convention. */
618
- readonly id: string;
619
- /** Level switch distances, ascending, `0` first — the CPU publication snapshot. */
620
- readonly distances: readonly number[];
621
- /** `maxDistance` less its eighth, or `undefined`. */
622
- readonly cull: number | undefined;
623
- /** Index-aligned with `distances`; each level's parts, each part's own offset inside the model. */
624
- readonly locals: readonly (readonly Float32Array[])[];
625
- /** Whether the last level is a whole-asset impostor whose gate the placement's scale scales. */
626
- readonly impostor?: boolean;
627
- }
628
-
629
- /**
630
- * Every placement's own answer, from the owner's live gates, as the instances each main key must be
631
- * holding: the same six-plane sphere test, the same `cull`, the same ascending `distance > gate`
632
- * level test and the same `placement * part offset` composition {@link cullAndSelect} runs — over
633
- * gates this file did not write.
634
- *
635
- * This is the one reference in the module that is not a mirror of the kernel's inputs. `cullAndSelect`
636
- * reads the gate table out of the same class the kernel's buffer is written from, so a table holding
637
- * the wrong distances makes both agree; here the caller passes the owner's own `distances`, so a
638
- * table that was written before the chain widened, or before the last `maxDistance`, answers
639
- * differently from the picture the CPU path draws.
640
- */
641
- export function liveKeyInstances(
642
- placements: readonly IGpuPlacement[],
643
- asset: (slot: number) => ILiveAsset | undefined,
644
- camera: {
645
- readonly planes: Float32Array;
646
- readonly x: number;
647
- readonly y: number;
648
- readonly z: number;
649
- },
650
- ): Map<string, Float32Array> {
651
- const words = new Map<string, number[]>();
652
- for (const placement of placements) {
653
- if (placement.slot < 0) continue;
654
- const held = asset(placement.slot);
655
- if (held === undefined) continue;
656
- const at = placement.centre;
657
- const radius = at[3] as number;
658
- let visible = true;
659
- for (let plane = 0; plane < 6; plane += 1) {
660
- const offset = plane * 4;
661
- const signed =
662
- (camera.planes[offset] as number) * (at[0] as number) +
663
- (camera.planes[offset + 1] as number) * (at[1] as number) +
664
- (camera.planes[offset + 2] as number) * (at[2] as number) +
665
- (camera.planes[offset + 3] as number);
666
- if (signed < -radius) {
667
- visible = false;
668
- break;
669
- }
670
- }
671
- if (visible === false) continue;
672
- const distance = Math.hypot((at[0] as number) - camera.x, (at[2] as number) - camera.z);
673
- if (held.cull !== undefined && distance > held.cull) continue;
674
- // The dispatch's own bias and the same gate rule: this reference is what the dressed mesh's
675
- // instances are checked against, so it must cross the impostor switch exactly as the kernel does.
676
- const level = levelAtGates(held, biasedLodDistance(distance), placement.scale ?? 1);
677
- const locals = held.locals[level];
678
- if (locals === undefined) continue;
679
- for (const [part, local] of locals.entries()) {
680
- const key = `${held.id}:${String(level)}:${String(part)}`;
681
- let run = words.get(key);
682
- if (run === undefined) {
683
- run = [];
684
- words.set(key, run);
685
- }
686
- compose(placement.matrix, local, LIVE_MATRIX, 0);
687
- for (const word of LIVE_MATRIX) run.push(word);
688
- }
689
- }
690
- return new Map([...words].map(([key, run]) => [key, Float32Array.from(run)]));
691
- }
692
-
693
- /** The one matrix `liveKeyInstances` composes into, reused per placement as the kernel's own is. */
694
- const LIVE_MATRIX = new Float32Array(LOCAL_WORDS);
695
-
696
- /**
697
- * Whether two gate tables are the same one, so a level key minted after the table was written
698
- * rewrites it and a swap that arrives with nothing new does not. A level the world has not minted a
699
- * key for carries `parts: 0`, which is what the kernel's own loop then draws for it: nothing.
700
- */
701
- function sameGates(one: IAssetSlot, other: IAssetSlot): boolean {
702
- if (one.cull !== other.cull) return false;
703
- if ((one.shadowFallback === false) !== (other.shadowFallback === false)) return false;
704
- if ((one.impostor === true) !== (other.impostor === true)) return false;
705
- if (one.distances.length !== other.distances.length) return false;
706
- for (const [index, distance] of one.distances.entries())
707
- if (distance !== other.distances[index]) return false;
708
- if (one.levels.length !== other.levels.length) return false;
709
- for (const [index, level] of one.levels.entries()) {
710
- const gate = other.levels[index];
711
- if (gate === undefined || gate.firstKey !== level.firstKey || gate.parts !== level.parts)
712
- return false;
713
- }
714
- return true;
715
- }
716
-
717
- /** One word of an indirect readback, out of range being the zero a record that was never written holds. */
718
- function word(readback: Uint32Array, at: number): number {
719
- return (readback[at] ?? 0) as number;
720
- }
721
-
722
- /** The translation of the `mat4` at slot `at`, which is what a draw places and a line can name. */
723
- function xyz(matrices: Float32Array, at: number): string {
724
- const matrix = at * LOCAL_WORDS;
725
- if (matrix + LOCAL_WORDS > matrices.length) return "[]";
726
- return (
727
- `[${(matrices[matrix + 12] as number).toFixed(3)},` +
728
- `${(matrices[matrix + 13] as number).toFixed(3)},` +
729
- `${(matrices[matrix + 14] as number).toFixed(3)}]`
730
- );
731
- }
732
-
733
- /**
734
- * Whether two runs of `mat4` hold the same matrices, as a set and not as a sequence.
735
- *
736
- * The kernel appends through an atomic, so the order two dispatches fill a region's run in is the
737
- * order the device scheduled them in and is not the order the reference walked the placements. The
738
- * counts agree over a set that agrees; a set that does not is a run one slot out, a matrix that was
739
- * never written, or a `firstInstance` the draw reads from a different place — none of which a count
740
- * can see. Sorted by translation, because that is what orders a placement, and compared with a
741
- * tolerance, because a matrix written through a product of two floats is not bit-equal to either.
742
- */
743
- function sameMatrices(
744
- gpu: Float32Array,
745
- gpuStart: number,
746
- gpuCount: number,
747
- cpu: Float32Array,
748
- cpuStart: number,
749
- cpuCount: number,
750
- tolerance: number,
751
- ): boolean {
752
- const one = sorted(gpu, gpuStart, gpuCount);
753
- const other = sorted(cpu, cpuStart, cpuCount);
754
- if (one.length !== other.length) return false;
755
- for (const [index, matrix] of one.entries()) {
756
- const against = other[index] as Float32Array;
757
- for (let word = 0; word < LOCAL_WORDS; word += 1)
758
- if (Math.abs((matrix[word] as number) - (against[word] as number)) > tolerance) return false;
759
- }
760
- return true;
761
- }
762
-
763
- /**
764
- * Whether two part offsets are the same matrix word for word. A re-dress copies the part's `Matrix4`
765
- * into a fresh array, so a re-registration of the same key is the same `local` by value and not by
766
- * reference; comparing the bytes is what makes it a no-op.
767
- */
768
- function sameLocal(one: Float32Array, other: Float32Array): boolean {
769
- if (one.length !== other.length) return false;
770
- for (let word = 0; word < one.length; word += 1)
771
- if ((one[word] as number) !== (other[word] as number)) return false;
772
- return true;
773
- }
774
-
775
- /** One run of `mat4` as views, ordered by translation, and short reads truncated rather than read past. */
776
- function sorted(matrices: Float32Array, start: number, count: number): Float32Array[] {
777
- const out: Float32Array[] = [];
778
- for (let taken = 0; taken < count; taken += 1) {
779
- const at = (start + taken) * LOCAL_WORDS;
780
- if (at < 0 || at + LOCAL_WORDS > matrices.length) break;
781
- out.push(matrices.subarray(at, at + LOCAL_WORDS));
782
- }
783
- out.sort(
784
- (one, other) =>
785
- (one[12] as number) - (other[12] as number) || (one[14] as number) - (other[14] as number),
786
- );
787
- return out;
788
- }
789
-
790
- /** `out * into` at `at`, column-major, which is the element order both matrices are written in. */ function compose(
791
- out: Float32Array,
792
- into: Float32Array,
793
- target: Float32Array,
794
- at: number,
795
- ): void {
796
- for (let column = 0; column < 4; column += 1)
797
- for (let row = 0; row < 4; row += 1) {
798
- let sum = 0;
799
- for (let k = 0; k < 4; k += 1)
800
- sum += (out[k * 4 + row] as number) * (into[column * 4 + k] as number);
801
- target[at + column * 4 + row] = sum;
802
- }
803
- }
804
-
805
- /**
806
- * One dressed main mesh's draw, as the owner's own live state says it, and nothing from this file's
807
- * tables.
808
- *
809
- * This is the check that cannot be wrong in the same way the kernel is. {@link cullAndSelect}
810
- * addresses a level's parts as `levels[gate.x + level].y + part`, and the gate table holds the
811
- * `firstKey` the source owner registered for that level, so a key/record/mesh mapping that is
812
- * wrong is reproduced on both sides of the comparison and reads as agreement: a real WebGPU walk
813
- * printed `ok` over a forest it was drawing with another tree's geometry. The three numbers here
814
- * come from the other side of the seam — the mesh's own `geometry.indirect` record, the mesh's own
815
- * name, and the instances the owner's own gates and the camera's own planes select for that name —
816
- * so the one question they can answer is the one that matters: does the record this mesh draws from
817
- * hold exactly the instances that mesh's key is owed.
818
- */
819
- export interface IMeshDraw {
820
- /** The dressed mesh's own name, which is the main key: `asset:level:part`. */
821
- readonly name: string;
822
- /** `geometry.indirectOffset / DRAW_ARGS_BYTES` — the record the draw reads, not one the tables name. */
823
- readonly record: number;
824
- /**
825
- * Every instance the owner's live gates and the camera's planes select for this key, `mat4` after
826
- * `mat4`: the whole answer, and never the per-cell records this path's own refilter left behind.
827
- */
828
- readonly instances: Float32Array;
829
- /**
830
- * Whether the mesh's own geometry reads the args buffer the readback came from, at the record above:
831
- * `geometry.indirect === scene.args` and `geometry.indirectOffset === region.argsIndex *
832
- * DRAW_ARGS_BYTES`, answered by the owner from the actual mesh. A record offset can agree with the
833
- * live buffer while the mesh still points at an older buffer with the same numeric offset — the
834
- * args buffer is allocated independently of `drawn`, and a mint can replace it under a dressed mesh
835
- * — so an offset check alone reads `ok` over a mesh drawing a buffer nothing writes. A missing value
836
- * is not a pass: only `true` is bound.
837
- */
838
- readonly bound?: boolean;
839
- }
840
-
841
- /** What the independent per-mesh check found, in the shape the report folds in. */
842
- export interface IMeshDrawComparison {
843
- /** Meshes whose own record was read back and held against the live-state instances. */
844
- readonly compared: number;
845
- readonly mismatched: number;
846
- readonly mismatches: readonly string[];
847
- }
848
-
849
- /**
850
- * Every dressed main mesh's own record, against the instances its own key is owed, as a set rather
851
- * than a sequence — the kernel appends through an atomic, so a device's order is not the CPU's.
852
- *
853
- * Equality, and not containment, because the reference is now the whole answer: the owner's gates
854
- * and the camera's planes over the scene's own placements, which is everything the dispatch reads.
855
- * Containment was the right relation when the other side was the CPU path's per-cell records, which
856
- * are the records a refilter left and go stale the moment the GPU scene bypasses it — a reference
857
- * that can be a superset cannot name a level selected at the wrong distance, and a far tree drawn
858
- * at its near level is what that looks like in the picture.
859
- */
860
- export function compareMeshDraws(
861
- gpu: Uint32Array,
862
- drawn: Float32Array,
863
- draws: readonly IMeshDraw[],
864
- regions: readonly IRegion[],
865
- ): IMeshDrawComparison {
866
- const mismatches: string[] = [];
867
- let mismatched = 0;
868
- for (const draw of draws) {
869
- const record = draw.record * DRAW_ARGS_WORDS;
870
- const landed = word(gpu, record + 1);
871
- const first = word(gpu, record + 4);
872
- // A stale binding is a mismatch the counts and matrices cannot see: the mesh's own geometry
873
- // points at an args buffer the readback did not come from, so whatever this record holds is not
874
- // what that mesh draws. Only an explicit `true` is bound, so a caller that forgets the field
875
- // fails closed rather than reading as agreement.
876
- if (draw.bound !== true) {
877
- mismatched += 1;
878
- if (mismatches.length >= MESH_REPORTED_MESHES) continue;
879
- const owner = regions.find((region) => region.argsIndex === draw.record);
880
- mismatches.push(
881
- `mesh=${draw.name} record=${String(draw.record)} ` +
882
- `region=${owner?.name ?? "none"} indirect=stale count gpu=${String(landed)} ` +
883
- `live=${String(draw.instances.length / LOCAL_WORDS)}`,
884
- );
885
- continue;
886
- }
887
- if (
888
- sameMatrices(
889
- drawn,
890
- first,
891
- landed,
892
- draw.instances,
893
- 0,
894
- draw.instances.length / LOCAL_WORDS,
895
- MATRIX_TOLERANCE,
896
- )
897
- )
898
- continue;
899
- mismatched += 1;
900
- if (mismatches.length >= MESH_REPORTED_MESHES) continue;
901
- // The region that owns the record the mesh read, which is the name that says whether the mesh
902
- // and the scene ever agreed on which record this key is.
903
- const owner = regions.find((region) => region.argsIndex === draw.record);
904
- mismatches.push(
905
- `mesh=${draw.name} record=${String(draw.record)} ` +
906
- `region=${owner?.name ?? "none"} count gpu=${String(landed)} ` +
907
- `live=${String(draw.instances.length / LOCAL_WORDS)} ` +
908
- `firstMatrix gpu=${xyz(drawn, first)} live=${xyz(draw.instances, 0)}`,
909
- );
910
- }
911
- return { compared: draws.length, mismatched, mismatches };
912
- }
913
-
914
- /** What one landed readback concluded, in the three words a log line can carry. */
915
- export type GpuSceneVerdict = "ok" | "mismatch" | "error";
916
-
917
- /** One landed readback's verdict, its one line, and the detail lines under it. */
918
- export interface IGpuSceneValidation {
919
- readonly verdict: GpuSceneVerdict;
920
- readonly line: string;
921
- readonly lines: readonly string[];
922
- }
923
-
924
- /**
925
- * The memory numbers a validation line can carry, all of them optional.
926
- *
927
- * The first seven are three's `info.memory` fields (`WebGPURenderer`, 0.185); a backend that tracks
928
- * none of them reports none, which is why every field is optional and only finite numbers are
929
- * printed — an absent reading is not a zero. `footprintBytes` is the sum of this scene's own storage
930
- * buffer `footprint()` bytes, the one number here Three did not write.
194
+ * TypeScript, in `world-gpu-reference.ts`, and the TSL kernel below mirrors it line for line. The
195
+ * tests run in node with no GPU, so the reference is what is proved against the CPU path; the
196
+ * kernel is compiled in the browser. The types, layout constants and launch flags it shares with the
197
+ * validation module live in `world-gpu-types.ts` and `world-gpu-flags.ts`, which is what keeps this
198
+ * file and `world-gpu-validation.ts` from importing each other.
931
199
  */
932
- export type GpuSceneMemoryField =
933
- | "storageAttributes"
934
- | "storageAttributesSize"
935
- | "indirectStorageAttributes"
936
- | "indirectStorageAttributesSize"
937
- | "readbackBuffers"
938
- | "readbackBuffersSize"
939
- | "total"
940
- | "footprintBytes";
941
-
942
- /** One validation's memory reading; a field is absent when the backend did not offer a finite one. */
943
- export type GpuSceneMemory = Partial<Record<GpuSceneMemoryField, number>>;
944
-
945
- const MEMORY_FIELDS = [
946
- "storageAttributes",
947
- "storageAttributesSize",
948
- "indirectStorageAttributes",
949
- "indirectStorageAttributesSize",
950
- "readbackBuffers",
951
- "readbackBuffersSize",
952
- "total",
953
- "footprintBytes",
954
- ] as const satisfies readonly GpuSceneMemoryField[];
955
-
956
- /**
957
- * The one placement nearest the camera (in XZ) a zero/zero comparison was handed, as the dispatch's
958
- * own snapshot held it. Every number is the snapshot's, never the live scene's: the camera's eye and
959
- * this placement's sphere, root translation, slot, slot cull, horizontal distance and the margin to
960
- * the nearest of the six frustum planes are what say whether the snapshot held no live source or
961
- * held one the camera, sphere, range or frustum rejected. A field is omitted, not printed as a fake
962
- * zero, when the snapshot has no finite number for it.
963
- */
964
- export interface IValidationNearest {
965
- /** The bounding sphere: X, Y, Z and the radius. */
966
- readonly centre: readonly [number, number, number];
967
- readonly radius: number;
968
- /** The placement matrix's translation, which is what a draw places. */
969
- readonly root: readonly [number, number, number];
970
- /** The asset slot the placement names. */
971
- readonly slot: number;
972
- /** The slot's authored cull distance, or absent when it has none. */
973
- readonly cull?: number;
974
- /** `hypot(cx - eye.x, cz - eye.z)`, the distance the level and cull gates read. */
975
- readonly distance: number;
976
- /** The least `plane·centre + plane.constant + radius` over the six planes: negative is rejected. */
977
- readonly margin: number;
978
- }
979
-
980
- /**
981
- * Why a comparison that landed both counts at zero was handed nothing: the snapshot's own camera eye,
982
- * how many placements it held and how many of them were live, and the one live placement nearest the
983
- * camera in XZ. Taken from the snapshot, so nothing that streams while the bytes are in flight can
984
- * rewrite the answer. Attached only when `instancesGpu` and `instancesCpu` are both zero.
985
- */
986
- export interface IValidationProbe {
987
- readonly eye: readonly [number, number, number];
988
- /** Placements the snapshot held, live and released. */
989
- readonly snapshot: number;
990
- /** Placements whose slot was not `SLOT_NONE`, the only ones the kernel considers. */
991
- readonly live: number;
992
- /** Absent when the snapshot held no live placement to name. */
993
- readonly nearest?: IValidationNearest;
994
- }
995
-
996
- /** What a landed readback is judged on, gathered from the scene before it is formatted. */
997
- export interface IGpuSceneComparison {
998
- /** Keys whose GPU instance count was read back and held against the reference. */
999
- readonly compared: number;
1000
- readonly instancesGpu: number;
1001
- readonly instancesCpu: number;
1002
- /** Up to {@link VALIDATE_REPORTED_KEYS} `name gpu=… cpu=…` lines; the count is the whole total. */
1003
- readonly mismatches: readonly string[];
1004
- readonly mismatched: number;
1005
- /**
1006
- * Keys whose drawn matrices, `firstInstance` or `indexCount` disagreed, and up to
1007
- * {@link MATRIX_REPORTED_KEYS} of them by name. The counts above are what the dispatch promised;
1008
- * these are what the draw reads, which is a different question and the one the picture answers.
1009
- */
1010
- readonly matricesMismatched: number;
1011
- readonly matrixMismatches: readonly string[];
1012
- /**
1013
- * Dressed main meshes whose own record was read back and held against the CPU path's own records
1014
- * for that mesh's key, and up to {@link MESH_REPORTED_MESHES} of them by name. This is the check
1015
- * the reference above cannot make: a key/record/mesh mapping that is wrong is one both sides
1016
- * reproduce, and a mesh drawing another asset's placements out of its own record is the picture
1017
- * that proves it.
1018
- */
1019
- readonly meshMismatched: number;
1020
- readonly meshMismatches: readonly string[];
1021
- /** Resident placements the scene held when the readback was issued. */
1022
- readonly placed: number;
1023
- /** The device's last uncaptured error, or `""` for none since the last check reported one. */
1024
- readonly deviceError: string;
1025
- /** What stopped the check — a rejected readback, say. Non-empty is an `error` on its own. */
1026
- readonly cause?: string;
1027
- /**
1028
- * What the device and this scene held when the check reported. Absent when neither offered a
1029
- * finite number, and a field is omitted rather than printed as zero when its backend has none.
1030
- */
1031
- readonly memory?: GpuSceneMemory;
1032
- /** The snapshot's own camera and nearest live placement, when both instance totals landed zero. */
1033
- readonly probe?: IValidationProbe;
1034
- }
1035
200
 
1036
- /** One completed manual frame check, identified by the caller's frame and this scene's dispatch. */
1037
201
  export interface IWorldGpuFrameValidation extends IGpuSceneComparison {
1038
202
  /** The caller's rendered-frame identity, never inferred from readback timing. */
1039
203
  readonly frame: number;
@@ -1042,166 +206,6 @@ export interface IWorldGpuFrameValidation extends IGpuSceneComparison {
1042
206
  readonly verdict: GpuSceneVerdict;
1043
207
  }
1044
208
 
1045
- /**
1046
- * The verdict and the lines one landed readback reports, as `TN_WORLD_GPU_SCENE_VALIDATE`.
1047
- *
1048
- * `ok` is a claim that the GPU drew what the reference draws, so it takes three things: every key's
1049
- * count landing equal, every key's record and matrices landing where the reference put them, and
1050
- * something to land. A dispatch the device refused leaves the args buffer holding what the clear
1051
- * pass wrote, which compares equal to a scene with nothing in it — a real WebGPU run printed
1052
- * `ok keys=0` 956 times while the cull pipeline was being refused for a binding 48 bytes short, which
1053
- * is a check that reports success precisely when the kernel does nothing. So comparing nothing while
1054
- * placements exist is an `error`, and a device that raised anything uncaptured is an `error`
1055
- * whatever the counts say, because every count in a buffer the device has already invalidated is not
1056
- * evidence of anything.
1057
- *
1058
- * The three mismatch families are counted apart and all are a `mismatch`: a key that drew the right
1059
- * number of instances at the wrong place or through a record naming no triangle is the failure a
1060
- * count cannot see, and a walk that printed `mismatched=0` over a forest it never drew is what that
1061
- * reads like. The third is the one the two above cannot find at all: every key the reference names
1062
- * and every record it reads is named by this same file, so a key/record/mesh mapping that is wrong is
1063
- * one they both reproduce, and the dressed mesh's own record, against the CPU path's own records,
1064
- * is the only pair of numbers here that were not written by the same hand.
1065
- *
1066
- * An `error` always names its cause on one `cause=` line: the checks that fail here fail silently
1067
- * otherwise, and a line reading `error` with nothing after it is the report that hid a refused
1068
- * pipeline in the first place.
1069
- */
1070
- /** One `[x,y,z]` at three decimals, the precision `xyz` names a matrix translation with. */
1071
- function triple(values: readonly [number, number, number]): string {
1072
- return (
1073
- `[${(values[0] as number).toFixed(3)},` +
1074
- `${(values[1] as number).toFixed(3)},${(values[2] as number).toFixed(3)}]`
1075
- );
1076
- }
1077
-
1078
- /** The `key=value` fields a zero/zero comparison's probe adds after the memory fields. */
1079
- function probeFields(probe: IValidationProbe): string[] {
1080
- const out = [
1081
- `eye=${triple(probe.eye)}`,
1082
- `snapshot=${String(probe.snapshot)}`,
1083
- `live=${String(probe.live)}`,
1084
- ];
1085
- const near = probe.nearest;
1086
- if (near === undefined) return out;
1087
- out.push(
1088
- `nearSphere=${triple(near.centre)}`,
1089
- `nearRadius=${near.radius.toFixed(3)}`,
1090
- `nearRoot=${triple(near.root)}`,
1091
- `nearSlot=${String(near.slot)}`,
1092
- );
1093
- if (near.cull !== undefined) out.push(`nearCull=${near.cull.toFixed(3)}`);
1094
- out.push(`nearXZ=${near.distance.toFixed(3)}`, `nearMargin=${near.margin.toFixed(3)}`);
1095
- return out;
1096
- }
1097
-
1098
- /**
1099
- * The snapshot's own camera and nearest live placement, for a comparison both of whose counts landed
1100
- * zero. The scan only picks the nearest; the six-plane margin is computed for that one placement
1101
- * alone, not for every placement the reference walked, and a field the snapshot has no finite number
1102
- * for is omitted rather than printed as a fake zero.
1103
- */
1104
- function zeroComparisonProbe(snapshot: IValidationSnapshot): IValidationProbe {
1105
- const eye: readonly [number, number, number] = [
1106
- snapshot.camera.x,
1107
- snapshot.camera.y,
1108
- snapshot.camera.z,
1109
- ];
1110
- let live = 0;
1111
- let nearest: IGpuPlacement | undefined;
1112
- let nearestDistance = Number.POSITIVE_INFINITY;
1113
- for (const placement of snapshot.placements) {
1114
- if (placement.slot < 0) continue;
1115
- live += 1;
1116
- const at = placement.centre;
1117
- const distance = Math.hypot(
1118
- (at[0] as number) - snapshot.camera.x,
1119
- (at[2] as number) - snapshot.camera.z,
1120
- );
1121
- if (Number.isFinite(distance) && distance < nearestDistance) {
1122
- nearestDistance = distance;
1123
- nearest = placement;
1124
- }
1125
- }
1126
- const probe: IValidationProbe = { eye, live, snapshot: snapshot.count };
1127
- if (nearest === undefined) return probe;
1128
- const at = nearest.centre;
1129
- const radius = at[3] as number;
1130
- const centre: readonly [number, number, number] = [
1131
- at[0] as number,
1132
- at[1] as number,
1133
- at[2] as number,
1134
- ];
1135
- const root: readonly [number, number, number] = [
1136
- nearest.matrix[12] as number,
1137
- nearest.matrix[13] as number,
1138
- nearest.matrix[14] as number,
1139
- ];
1140
- let margin = Number.POSITIVE_INFINITY;
1141
- for (let plane = 0; plane < 6; plane += 1) {
1142
- const offset = plane * 4;
1143
- const signed =
1144
- (snapshot.camera.planes[offset] as number) * (at[0] as number) +
1145
- (snapshot.camera.planes[offset + 1] as number) * (at[1] as number) +
1146
- (snapshot.camera.planes[offset + 2] as number) * (at[2] as number) +
1147
- (snapshot.camera.planes[offset + 3] as number);
1148
- margin = Math.min(margin, signed + radius);
1149
- }
1150
- const numbers = [...centre, ...root, radius, nearestDistance, margin];
1151
- if (numbers.some((value) => !Number.isFinite(value))) return probe;
1152
- const cull = snapshot.slots[nearest.slot]?.cull;
1153
- return {
1154
- ...probe,
1155
- nearest: {
1156
- centre,
1157
- distance: nearestDistance,
1158
- margin,
1159
- radius,
1160
- root,
1161
- slot: nearest.slot,
1162
- ...(cull === undefined ? {} : { cull }),
1163
- },
1164
- };
1165
- }
1166
-
1167
- export function validationReport(input: IGpuSceneComparison): IGpuSceneValidation {
1168
- const blind = input.compared === 0 && input.placed > 0;
1169
- const cause =
1170
- input.deviceError !== ""
1171
- ? `device-error ${input.deviceError}`
1172
- : (input.cause ?? (blind ? `compared-0-with-placed=${String(input.placed)}` : ""));
1173
- const verdict: GpuSceneVerdict =
1174
- cause !== ""
1175
- ? "error"
1176
- : input.mismatched > 0 || input.matricesMismatched > 0 || input.meshMismatched > 0
1177
- ? "mismatch"
1178
- : "ok";
1179
- const memory: string[] = [];
1180
- if (input.memory !== undefined)
1181
- for (const name of MEMORY_FIELDS) {
1182
- const value = input.memory[name];
1183
- if (typeof value === "number" && Number.isFinite(value))
1184
- memory.push(`${name}=${String(value)}`);
1185
- }
1186
- const details = [...memory, ...(input.probe === undefined ? [] : probeFields(input.probe))];
1187
- const suffix = details.length === 0 ? "" : ` ${details.join(" ")}`;
1188
- const line =
1189
- `TN_WORLD_GPU_SCENE_VALIDATE ${verdict} compared=${String(input.compared)} ` +
1190
- `instancesGpu=${String(input.instancesGpu)} instancesCpu=${String(input.instancesCpu)} ` +
1191
- `mismatched=${String(input.mismatched)} matricesMismatched=${String(input.matricesMismatched)} ` +
1192
- `meshMismatched=${String(input.meshMismatched)}${suffix}`;
1193
- const lines: string[] = [...input.mismatches, ...input.matrixMismatches, ...input.meshMismatches];
1194
- if (cause !== "") lines.push(`cause=${cause.slice(0, CAUSE_CHARS)}`);
1195
- return { verdict, line, lines };
1196
- }
1197
-
1198
- /** The message an uncaptured WebGPU error event carries, flattened to one line. */
1199
- function uncapturedMessage(event: unknown): string {
1200
- const error = (event as { error?: { message?: string; constructor?: { name?: string } } }).error;
1201
- const kind = error?.constructor?.name ?? "GPUError";
1202
- return `${kind}: ${(error?.message ?? "no message").replace(/\s+/gu, " ").trim()}`;
1203
- }
1204
-
1205
209
  /**
1206
210
  * What `TN_WORLD_GPU_SCENE` reports, and what `stats().gpuScene` carries.
1207
211
  *
@@ -1230,79 +234,7 @@ export interface IWorldGpuSceneReport {
1230
234
  * counts and `occlusion.gpuTriangles` come from one landed dispatch, even if a later tally
1231
235
  * was skipped for occlusion.
1232
236
  */
1233
- readonly occlusion?: {
1234
- readonly mode: OcclusionMode;
1235
- readonly reason: string;
1236
- /** Pyramid levels and the dispatches that rebuild them each frame. */
1237
- readonly levels: number;
1238
- readonly buildDispatches: number;
1239
- /** The last landed sample, and the mean over every sample that landed. */
1240
- readonly instances: number;
1241
- readonly triangles: number;
1242
- readonly meanInstances: number;
1243
- readonly meanTriangles: number;
1244
- readonly samples: number;
1245
- /** `triangles / gpuTriangles` of the same sample, which is what the go/no-go multiplies. */
1246
- readonly share: number;
1247
- readonly gpuTriangles: number;
1248
- readonly ageFrames: number;
1249
- };
1250
- }
1251
-
1252
- /**
1253
- * The shadow twins' two buffers: a record per key and a run per key, at the layout the main pass
1254
- * already gave each key. Allocated only once a provider has registered — see
1255
- * {@link WorldGpuScene.shadowKeysFrom}.
1256
- */
1257
- interface IShadowBuffers {
1258
- readonly args: IndirectStorageBufferAttribute;
1259
- readonly drawn: StorageInstancedBufferAttribute;
1260
- /** Key name to the main key index it twins, so a missing twin is a missing draw, not a crash. */
1261
- readonly keys: Map<string, number>;
1262
- /** The same indices the other way, so a record write knows whether this key has a twin at all. */
1263
- readonly held: Set<number>;
1264
- }
1265
-
1266
- interface IGpuSceneBuffers {
1267
- readonly args: IndirectStorageBufferAttribute;
1268
- readonly drawn: StorageInstancedBufferAttribute;
1269
- readonly gates: StorageBufferAttribute;
1270
- readonly keys: StorageBufferAttribute;
1271
- readonly levels: StorageBufferAttribute;
1272
- readonly locals: StorageBufferAttribute;
1273
- readonly source: StorageBufferAttribute;
1274
- }
1275
-
1276
- /** One of the scene's own storage buffers, by the name it is allocated and grown under. */
1277
- type BufferName = keyof IGpuSceneBuffers;
1278
-
1279
- /**
1280
- * The declared WGSL type of every buffer that is a plain `StorageBufferAttribute` in
1281
- * {@link IGpuSceneBuffers}. `args` and `drawn` are absent because each needs a three class of its own,
1282
- * so `#growOf` names those two literally; the other five share one.
1283
- */
1284
- const STORAGE_PLAIN: Record<Exclude<BufferName, "args" | "drawn">, StorageType> = {
1285
- gates: "vec4",
1286
- keys: "vec4",
1287
- levels: "vec4",
1288
- locals: "mat4",
1289
- source: "GpuPlacement",
1290
- };
1291
-
1292
- /** Resident placements the source buffer is sized to hold before the first reallocation. */
1293
- const SOURCE_FLOOR = 16;
1294
-
1295
- /** One storage buffer as the check reads it: the type the kernel declares and what was allocated. */
1296
- export interface IGpuSceneBufferFootprint {
1297
- readonly type: StorageType;
1298
- readonly count: number;
1299
- /** `array.byteLength` — the size WebGPU compares against one element of `type`. */
1300
- readonly bytes: number;
1301
- }
1302
-
1303
- /** The slice of a `GPUDevice` the validation seam reads, so a test can stand in a fake. */
1304
- interface IDeviceLike {
1305
- onuncapturederror?: ((event: unknown) => void) | null;
237
+ readonly occlusion?: IOcclusionReport;
1306
238
  }
1307
239
 
1308
240
  /**
@@ -1343,7 +275,6 @@ function cameraPlanes(camera: Camera, out: Float32Array): void {
1343
275
  const _proj = new Matrix4();
1344
276
  const _cullFrustum = new Frustum();
1345
277
  const _eye = new Vector3();
1346
- const _view = new Matrix4();
1347
278
 
1348
279
  /** Camera travel in one dispatch that the occlusion test reads as a cut rather than a turn. */
1349
280
  const OCCLUSION_CUT_METRES = 2;
@@ -1358,173 +289,6 @@ function sameProjection(left: Matrix4, right: Matrix4): boolean {
1358
289
  return true;
1359
290
  }
1360
291
 
1361
- /**
1362
- * A TSL node this module pokes at through the swizzles and the `.element()` chain.
1363
- *
1364
- * Three's node types are precise about which swizzle a `vec4` answers and deliberately vague about
1365
- * what a struct member or an atomic result resolves to, and the kernel is the one place in core
1366
- * that has to read a struct member and an atomic's return value. The cast is confined here so the
1367
- * kernel reads as the plain shader it is.
1368
- */
1369
- // quality-allow: the kernel is a typed handle onto three's TSL nodes, which resolve to `any` in 0.185.
1370
- // biome-ignore lint/suspicious/noExplicitAny: three's TSL types refuse the swizzles this kernel reads.
1371
- type Kernel = Record<string, any>;
1372
-
1373
- /** `storage(...)` results reach the kernel through this, once. */
1374
- function nodes(value: unknown): Kernel {
1375
- return value as Kernel;
1376
- }
1377
-
1378
- /** The launch flag. */
1379
- export const GPU_SCENE_FLAG = "TN_GPU_SCENE";
1380
-
1381
- /**
1382
- * Did this launch ask for `flag` to be **off**? The environment variable, the query string and the
1383
- * global a test sets are the three ways one is asked, and `0` and `false` are the only answers that
1384
- * count: an unset or empty variable is the same as no variable, and a saved URL that used to enable
1385
- * a switch still says "off".
1386
- */
1387
- function askedOff(flag: string, parameter: string, globalName: string): boolean {
1388
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
1389
- string,
1390
- unknown
1391
- >;
1392
- const fromEnv = host.process?.env?.[flag];
1393
- if (fromEnv === "0" || fromEnv === "false") return true;
1394
- const query = globalThis.location?.search;
1395
- if (
1396
- typeof query === "string" &&
1397
- new RegExp(`[?&]${parameter}=(?:0|false)(?:&|$)`, "u").test(query)
1398
- )
1399
- return true;
1400
- const set = host[globalName];
1401
- return set === false || set === 0 || set === "0" || set === "false";
1402
- }
1403
-
1404
- /**
1405
- * Did this launch ask for `flag` to be **on**? The mirror of {@link askedOff}, for the switches that
1406
- * are opt-in: the environment variable, the query string and the global a test sets, and only
1407
- * `1` and `true` count. An unset or empty variable is the same as no variable, so an old URL that
1408
- * never mentioned the switch stays off.
1409
- */
1410
- function askedOn(flag: string, parameter: string, globalName: string): boolean {
1411
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
1412
- string,
1413
- unknown
1414
- >;
1415
- const fromEnv = host.process?.env?.[flag];
1416
- if (fromEnv === "1" || fromEnv === "true") return true;
1417
- const query = globalThis.location?.search;
1418
- if (
1419
- typeof query === "string" &&
1420
- new RegExp(`[?&]${parameter}=(?:1|true)(?:&|$)`, "u").test(query)
1421
- )
1422
- return true;
1423
- return host[globalName] === true || host[globalName] === 1 || host[globalName] === "1";
1424
- }
1425
-
1426
- /**
1427
- * Whether the GPU-driven main pass should run on this launch, on by default where the backend can.
1428
- *
1429
- * @situation debug a walk whose main pass culls and LOD-selects on the GPU
1430
- * @constraint on unless a launch asks for the CPU path: `gpuScene: false`, `?tnGpuScene=0` or
1431
- * `TN_GPU_SCENE=0` turn it off, and a backend without compute, storage buffers and
1432
- * `drawIndexedIndirect` falls back on its own
1433
- * @example WorldCells.load({ ...options, gpuScene: gpuSceneRequested() });
1434
- *
1435
- * Read the way `renderListValidationRequested` and `terrainValidationRequested` read their own: a
1436
- * native launch sets the environment variable, a browser asks with the query string, and a test
1437
- * sets the global. Measured on machinefall at 863f83258, so it flipped from opt-in to default.
1438
- */
1439
- export function gpuSceneRequested(): boolean {
1440
- return askedOff(GPU_SCENE_FLAG, "tnGpuScene", "__tnGpuScene") === false;
1441
- }
1442
-
1443
- /** The launch flag. */
1444
- export const BUNDLE_FLAG = "TN_BUNDLES";
1445
-
1446
- /**
1447
- * What this launch asked for about world draw bundles: `on`, `off`, or `default` when it said
1448
- * nothing.
1449
- *
1450
- * @situation tell a run that set the option itself apart from one that took the default
1451
- * @example WorldCells.load({ ...options, bundles: bundlesAsked() !== "off" });
1452
- *
1453
- * Read the way {@link gpuSceneRequested} reads its own: a native launch sets the environment
1454
- * variable, a browser asks with the query string, and a test sets the global.
1455
- */
1456
- export function bundlesAsked(): "default" | "off" | "on" {
1457
- if (askedOn(BUNDLE_FLAG, "tnBundles", "__tnBundles")) return "on";
1458
- return askedOff(BUNDLE_FLAG, "tnBundles", "__tnBundles") ? "off" : "default";
1459
- }
1460
-
1461
- /**
1462
- * Whether world draw bundles should be recorded and replayed. On by default, and off unless a launch
1463
- * asks for the CPU path.
1464
- *
1465
- * @situation debug a walk whose main batches are replayed from a recorded bundle
1466
- * @constraint on unless a launch asks otherwise: `bundles: false`, `?tnBundles=0` or `TN_BUNDLES=0`
1467
- * turn it off. The default followed a measurement, not a preference — PRD-494 AC-2 took the walking
1468
- * `draw` span from a 6.0 ms p50 median to 0.6 ms against develop over 3 interleaved runs, on a
1469
- * picture a blind world gate called equal, so the answer that used to be "off, it gave no CPU
1470
- * p50/p95 gain" is now "on, it is 5 ms of the walking p95". `bundles: true`, `?tnBundles=1` or
1471
- * `TN_BUNDLES=1` still say so explicitly. See PRD-473 phase 2 and PRD-494 phase 2.
1472
- * @example WorldCells.load({ ...options, bundles: bundlesRequested() });
1473
- */
1474
- export function bundlesRequested(): boolean {
1475
- return bundlesAsked() !== "off";
1476
- }
1477
-
1478
- /** The validation flag. */
1479
- export const GPU_SCENE_VALIDATE_FLAG = "TN_GPU_SCENE_VALIDATE";
1480
-
1481
- /**
1482
- * Whether the GPU scene should hold every dispatch's indirect args against the CPU reference.
1483
- *
1484
- * @situation find the keys a real WebGPU dispatch draws fewer instances of than `cullAndSelect` does
1485
- * @constraint off by default and never on a measured walk: a readback is a queue submission and a
1486
- * mapped buffer, so the mode exists to answer "which key" and not to be fast
1487
- * @example WorldCells.load({ ...options, gpuScene: true, gpuSceneValidate: gpuSceneValidationRequested() });
1488
- *
1489
- * Read the way `gpuSceneRequested` reads its own: a native launch sets the environment variable, a
1490
- * browser asks with `?tnGpuSceneValidate=1`, and a test sets the global.
1491
- */
1492
- export function gpuSceneValidationRequested(): boolean {
1493
- const host = globalThis as {
1494
- process?: { env?: Record<string, unknown> };
1495
- __tnGpuSceneValidate?: unknown;
1496
- };
1497
- const fromEnv = host.process?.env?.[GPU_SCENE_VALIDATE_FLAG];
1498
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
1499
- return true;
1500
- const query = globalThis.location?.search;
1501
- if (
1502
- typeof query === "string" &&
1503
- /[?&]tnGpuSceneValidate=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query)
1504
- )
1505
- return true;
1506
- return host.__tnGpuSceneValidate === true || host.__tnGpuSceneValidate === "1";
1507
- }
1508
-
1509
- /** The launch flag. */
1510
- export const SHADOW_GPU_KEYS_FLAG = "TN_SHADOW_GPU_KEYS";
1511
-
1512
- /**
1513
- * Whether a shadow level may select its own set of GPU-scene keys. Opt-in, and off by default.
1514
- *
1515
- * @situation debug a walk whose shadow maps draw GPU-scene keys instead of cluster meshes
1516
- * @constraint off unless a launch asks for it: without a provider nothing is allocated and no
1517
- * dispatch is submitted, so the flag alone cannot change a frame — `shadowGpuKeys: true`,
1518
- * `?tnShadowGpuKeys=1` or `TN_SHADOW_GPU_KEYS=1` turns it on. See PRD-478 phase 2.
1519
- * @example world.gpuScene.shadowKeysFrom(() => keyNames);
1520
- *
1521
- * Read the way {@link bundlesRequested} reads its own: a native launch sets the environment
1522
- * variable, a browser asks with the query string, and a test sets the global.
1523
- */
1524
- export function shadowGpuKeysRequested(): boolean {
1525
- return askedOn(SHADOW_GPU_KEYS_FLAG, "tnShadowGpuKeys", "__tnShadowGpuKeys");
1526
- }
1527
-
1528
292
  /**
1529
293
  * The GPU scene, owned by one `WorldCells`.
1530
294
  *
@@ -1545,7 +309,7 @@ export class WorldGpuScene {
1545
309
  */
1546
310
  #shadow: IShadowBuffers | undefined;
1547
311
  #shadowProvider: (() => Iterable<string>) | undefined;
1548
- #shadowKernel: { readonly cull: unknown; readonly clear: unknown } | undefined;
312
+ #shadowKernel: IGpuKernel | undefined;
1549
313
  readonly #slotsByAsset = new Map<string, IAssetSlot>();
1550
314
  /** One level's parts per `asset:level`, which is what keeps them the run the kernel addresses. */
1551
315
  readonly #groups = new Map<string, ILevelGroup>();
@@ -1564,7 +328,7 @@ export class WorldGpuScene {
1564
328
  /** Bumped by every buffer swap, so a mesh re-dressed once knows if it still points at live data. */
1565
329
  #version = 0;
1566
330
  /** The kernel, rebuilt whenever a capacity changed under it. */
1567
- #kernel: { readonly cull: unknown; readonly clear: unknown } | undefined;
331
+ #kernel: IGpuKernel | undefined;
1568
332
  #planes = new Float32Array(24);
1569
333
 
1570
334
  /**
@@ -1579,9 +343,7 @@ export class WorldGpuScene {
1579
343
  tally = false,
1580
344
  occlusion: OcclusionMode = "off",
1581
345
  ): boolean {
1582
- this.#validate = validate;
1583
- this.#tally = tally || occlusion !== "off";
1584
- this.#occlusion = occlusion;
346
+ this.#readback.configure(validate, tally || occlusion !== "off", occlusion);
1585
347
  if (this.#on) return true;
1586
348
  if (this.#reported) return false;
1587
349
  if (renderer === undefined) {
@@ -1601,7 +363,7 @@ export class WorldGpuScene {
1601
363
  }
1602
364
  this.#on = true;
1603
365
  this.#reason = "on";
1604
- this.#watchDevice(renderer);
366
+ this.#readback.watch(renderer);
1605
367
  // Not printed here: the owner's own line is the one that says how many of its meshes are
1606
368
  // dressed, and that number is only known once it has dressed them — see {@link announce}.
1607
369
  return true;
@@ -1623,27 +385,6 @@ export class WorldGpuScene {
1623
385
  this.#report(renderer);
1624
386
  }
1625
387
 
1626
- /**
1627
- * Hold the device's uncaptured errors, so a check can read them instead of the console.
1628
- *
1629
- * Three already chains its own `onuncapturederror` onto the same device and prints the message,
1630
- * which is the whole reason a refused pipeline reads as a healthy run: the evidence was on screen
1631
- * as a console line nothing compared against the counts. This wraps that handler rather than
1632
- * replacing it, so three's own reporting still fires, and the last message is folded into the next
1633
- * `TN_WORLD_GPU_SCENE_VALIDATE` line. Nothing is cleared except by a check that has reported it,
1634
- * so an error that arrives between two checks still lands on the one after.
1635
- */
1636
- #watchDevice(renderer: IRendererLike): void {
1637
- const device = (renderer.raw as { backend?: { device?: IDeviceLike } })?.backend?.device;
1638
- if (device === undefined || this.#watched) return;
1639
- this.#watched = true;
1640
- const previous = device.onuncapturederror;
1641
- device.onuncapturederror = (event: unknown): void => {
1642
- this.#deviceError = uncapturedMessage(event);
1643
- if (typeof previous === "function") previous.call(device, event);
1644
- };
1645
- }
1646
-
1647
388
  get on(): boolean {
1648
389
  return this.#on;
1649
390
  }
@@ -1723,41 +464,8 @@ export class WorldGpuScene {
1723
464
  on: this.#on,
1724
465
  reason: this.#reason,
1725
466
  // Absent until a sample lands, never zero: "the GPU selected nothing" and "nothing has been
1726
- // read back yet" are different facts, and a zero would merge them.
1727
- ...(this.#tallySample < 0
1728
- ? {}
1729
- : {
1730
- gpuInstances: this.#tallyInstances,
1731
- gpuTallyAgeFrames: this.#dispatched - this.#tallySample,
1732
- gpuTriangles: this.#tallyTriangles,
1733
- }),
1734
- ...(this.#occlusion === "off"
1735
- ? {}
1736
- : {
1737
- occlusion: {
1738
- ageFrames: this.#occlusionSample < 0 ? 0 : this.#dispatched - this.#occlusionSample,
1739
- buildDispatches: this.#pyramid.levels,
1740
- instances: this.#occludedInstances,
1741
- levels: this.#pyramid.levels,
1742
- meanInstances:
1743
- this.#occlusionSamples === 0
1744
- ? 0
1745
- : Math.round(this.#occlusionSumInstances / this.#occlusionSamples),
1746
- meanTriangles:
1747
- this.#occlusionSamples === 0
1748
- ? 0
1749
- : Math.round(this.#occlusionSumTriangles / this.#occlusionSamples),
1750
- mode: this.#occlusion,
1751
- reason: this.#occlusionReason,
1752
- samples: this.#occlusionSamples,
1753
- gpuTriangles: this.#occlusionTotalTriangles,
1754
- share:
1755
- this.#occlusionTotalTriangles === 0
1756
- ? 0
1757
- : this.#occludedTriangles / this.#occlusionTotalTriangles,
1758
- triangles: this.#occludedTriangles,
1759
- },
1760
- }),
467
+ // read back yet" are different facts, and a zero would merge them. See {@link WorldGpuReadback}.
468
+ ...this.#readback.report(),
1761
469
  };
1762
470
  }
1763
471
 
@@ -2167,7 +875,7 @@ export class WorldGpuScene {
2167
875
  this.#eye.value.copy(_eye);
2168
876
  // `(placements, slots, keys, keys)`: the last two are the same count, and the clear dispatch is
2169
877
  // one thread per key.
2170
- if (this.#occlusion !== "off") this.#measureOcclusion(renderer, camera);
878
+ if (this.#readback.measuring) this.#readback.measure(renderer, camera);
2171
879
  // Measurement may replace the pyramid buffer on first use or resize. Bind the new buffer in
2172
880
  // this frame's cull, rather than dispatching a kernel captured before the replacement.
2173
881
  const kernel = this.#kernel ?? this.#buildKernel();
@@ -2177,107 +885,10 @@ export class WorldGpuScene {
2177
885
  // One pass holds both kernels: storage writes reach the next dispatch, so clear precedes cull.
2178
886
  renderer.compute([kernel.clear, kernel.cull]);
2179
887
  this.#dispatched += 1;
2180
- if (
2181
- this.#validate === true &&
2182
- this.#manualOnly === false &&
2183
- this.#validating === false &&
2184
- this.#dispatched % VALIDATE_EVERY === 0
2185
- )
2186
- this.#compare(renderer);
2187
- // A validation's own readback already holds the args, so it feeds the tally and this never adds
2188
- // a second copy beside it. With validation off the tally reads on its own slower clock, and a
2189
- // frame whose predecessor has not landed is skipped rather than queued.
2190
- else if (
2191
- this.#validate === false &&
2192
- this.#tally === true &&
2193
- (this.#occlusion === "off" || this.#occlusionCut.value === 0) &&
2194
- this.#tallyPending === false &&
2195
- (this.#tallyRequested < 0 || this.#dispatched - this.#tallyRequested >= TALLY_EVERY)
2196
- )
2197
- this.#tallyRead(renderer);
2198
- }
2199
-
2200
- /**
2201
- * One frame of `?tnOcclusion=measure`: rebuild the max-distance chain from the depth the previous
2202
- * frame's scene pass left behind, and point the test at the camera that depth was rendered with.
2203
- *
2204
- * The depth is last frame's on purpose. This runs in `beforeRender`, before the frame's own scene
2205
- * pass draws, so the texture still holds what the last one wrote — which is the only depth there
2206
- * is, and the reason the test reprojects rather than sampling the current frame.
2207
- *
2208
- * With no scene-pass depth — no render chain installed, so nothing rendered into a target of its
2209
- * own — the mode refuses and says so in `report().occlusion.reason` rather than reporting nothing
2210
- * hidden and reading as a cull that found no work.
2211
- */
2212
- #measureOcclusion(renderer: IRendererLike, camera: Camera): void {
2213
- this.#occlusionCut.value = 1;
2214
- // The main pass returns on an orthographic camera before it gets here (that is a shadow level's
2215
- // own), and a linear depth in metres is a perspective projection's to begin with.
2216
- if (!(camera instanceof PerspectiveCamera)) {
2217
- this.#previousDepth = undefined;
2218
- this.#occlusionReason = "refused: not a perspective camera";
2219
- return;
2220
- }
2221
- const raw = renderer.raw as { logarithmicDepthBuffer?: boolean; reversedDepthBuffer?: boolean };
2222
- if (raw?.logarithmicDepthBuffer || raw?.reversedDepthBuffer || camera.reversedDepth) {
2223
- this.#previousDepth = undefined;
2224
- this.#occlusionReason = "refused: nonstandard depth";
2225
- return;
2226
- }
2227
- const depth = renderer.scenePassDepth?.();
2228
- const width = depth?.width ?? 0;
2229
- const height = depth?.height ?? 0;
2230
- if (depth === undefined || width < 2 || height < 2) {
2231
- this.#previousDepth = undefined;
2232
- this.#occlusionReason = "refused: no scene depth";
2233
- return;
2234
- }
2235
- this.#occlusionReason = "";
2236
- // A resized depth resizes the chain, and the chain's two buffers are what the cull kernel reads,
2237
- // so a new chain is a new pipeline: structural, like every other grow in this class.
2238
- const resized = this.#pyramid.resize(width, height);
2239
- if (resized) {
2240
- this.#kernel = undefined;
2241
- this.#version += 1;
2242
- }
2243
- _view.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
2244
- _eye.setFromMatrixPosition(camera.matrixWorld);
2245
- // A cut skips the test for the frame: a teleport moved the camera further than a walk step, and
2246
- // a projection change means the pyramid is a different camera's depth altogether.
2247
- // ponytail: 2 m of camera travel in one dispatch is a cut. A game that teleports further per
2248
- // step than that raises the bound; one that cuts under it gets a frame of frustum-only.
2249
- const samples = depth.samples ?? 1;
2250
- const previous = this.#previousDepth;
2251
- const depthChanged =
2252
- previous?.texture !== depth.texture ||
2253
- previous.width !== width ||
2254
- previous.height !== height ||
2255
- previous.samples !== samples ||
2256
- previous.version !== depth.texture.version;
2257
- this.#occlusionCut.value =
2258
- depthChanged ||
2259
- resized ||
2260
- !sameProjection(this.#previousProjection, camera.projectionMatrix) ||
2261
- _eye.distanceTo(this.#previousEye) > OCCLUSION_CUT_METRES
2262
- ? 1
2263
- : 0;
2264
- if (this.#occlusionCut.value !== 0)
2265
- this.#occlusionReason =
2266
- depthChanged || resized ? "skipped: depth changed" : "skipped: camera cut";
2267
- this.#previousDepth = {
2268
- texture: depth.texture,
2269
- width,
2270
- height,
2271
- samples,
2272
- version: depth.texture.version,
2273
- };
2274
- this.#previousProjection.copy(camera.projectionMatrix);
2275
- // The chain first, then the camera the chain belongs to: last frame's, which is what the
2276
- // previous frame's depth recorded.
2277
- this.#pyramid.build(renderer, depth.texture, camera.near, camera.far, samples);
2278
- this.#occlusionView.value.copy(this.#previousView);
2279
- this.#previousView.copy(_view);
2280
- this.#previousEye.copy(_eye);
888
+ // The frame's sample, if one is due: a validation or the tally, on their own clocks. See
889
+ // {@link WorldGpuReadback.sample}.
890
+ this.#readback.setDispatched(this.#dispatched);
891
+ this.#readback.sample(renderer);
2281
892
  }
2282
893
 
2283
894
  /**
@@ -2293,14 +904,7 @@ export class WorldGpuScene {
2293
904
  readonly meshMismatched: number;
2294
905
  readonly lines: readonly string[];
2295
906
  } {
2296
- return {
2297
- verdict: this.#verdict,
2298
- compared: this.#compared,
2299
- mismatched: this.#mismatches,
2300
- matricesMismatched: this.#matrixMismatches,
2301
- meshMismatched: this.#meshMismatches,
2302
- lines: this.#lines,
2303
- };
907
+ return this.#readback.validation;
2304
908
  }
2305
909
 
2306
910
  /**
@@ -2309,29 +913,13 @@ export class WorldGpuScene {
2309
913
  * This is an opt-in diagnostic seam for a harness that must fence one rendered frame before it
2310
914
  * advances the fixed-step clock. It does not change the periodic validation path or production
2311
915
  * dispatches; a caller that asks twice for one dispatch is refused rather than silently counting
2312
- * one frame twice.
916
+ * one frame twice. See {@link WorldGpuReadback.fence}.
2313
917
  */
2314
918
  validateCurrentDispatch(
2315
919
  renderer: IRendererLike,
2316
920
  frame: number,
2317
921
  ): Promise<IWorldGpuFrameValidation> {
2318
- if (!Number.isInteger(frame) || frame < 0)
2319
- return Promise.reject(
2320
- new Error("World GPU frame validation needs a non-negative integer frame."),
2321
- );
2322
- if (this.#on === false)
2323
- return Promise.reject(new Error("World GPU scene validation is unavailable."));
2324
- if (this.#dispatched <= 0)
2325
- return Promise.reject(new Error("World GPU frame validation needs a completed dispatch."));
2326
- if (this.#validating)
2327
- return Promise.reject(
2328
- new Error("World GPU frame validation already has a pending readback."),
2329
- );
2330
- if (this.#manualDispatch === this.#dispatched)
2331
- return Promise.reject(new Error("World GPU dispatch was already manually validated."));
2332
- this.#manualOnly = true;
2333
- this.#manualDispatch = this.#dispatched;
2334
- return this.#compare(renderer, frame);
922
+ return this.#readback.fence(renderer, frame);
2335
923
  }
2336
924
 
2337
925
  /**
@@ -2339,471 +927,46 @@ export class WorldGpuScene {
2339
927
  * owner and asked only on a check's frame.
2340
928
  *
2341
929
  * The scene cannot answer this for itself: the records are the owner's, and the meshes whose
2342
- * indirect offsets are the question are the owner's too. It is asked inside {@link compare}, before
2343
- * the readback is issued, so the instances it compares are the ones the dispatch just read rather
2344
- * than whatever the cells hold when the bytes land — the same snapshot rule the rest of the check
2345
- * is built on, and the reason a walk that streams while a readback is in flight cannot make the
2346
- * check compare two different worlds.
930
+ * indirect offsets are the question are the owner's too. It is asked inside {@link #compare},
931
+ * before the readback is issued, so the instances it compares are the ones the dispatch just read
932
+ * rather than whatever the cells hold when the bytes land — the same snapshot rule the rest of the
933
+ * check is built on, and the reason a walk that streams while a readback is in flight cannot make
934
+ * the check compare two different worlds.
2347
935
  */
2348
936
  drawsFrom(provider: () => readonly IMeshDraw[]): void {
2349
- this.#draws = provider;
937
+ this.#readback.drawsFrom(provider);
2350
938
  }
2351
939
 
2352
- #draws: (() => readonly IMeshDraw[]) | undefined;
2353
- #mismatches = 0;
2354
- #matrixMismatches = 0;
2355
- #meshMismatches = 0;
2356
- #compared = 0;
2357
- #verdict: GpuSceneVerdict = "ok";
2358
- #lines: string[] = [];
2359
- #validate = false;
2360
- #validating = false;
2361
- /** Manual frame fences replace periodic samples after the first completed fence. */
2362
- #manualOnly = false;
2363
- /** The last dispatch a manual frame fence consumed; periodic checks do not move this. */
2364
- #manualDispatch = -1;
2365
- /** Reused MAP_READ buffers keep validation from allocating two fresh GPU buffers on every check. */
2366
- #validationReadbacks: IValidationReadbacks | undefined;
2367
- /** Whether the owner asked for the GPU-selected main-pass tally; a validation turns it on too. */
2368
- #tally = false;
2369
- /** What a launch asked the pyramid occlusion test to do. `measure` never changes what is drawn. */
2370
- #occlusion: OcclusionMode = "off";
2371
- /** The max-distance chain, and the previous frame's camera the test reprojects into. */
2372
- readonly #pyramid = new DepthPyramid();
2373
- readonly #previousView = new Matrix4();
2374
- readonly #previousProjection = new Matrix4();
2375
- #previousDepth:
2376
- | {
2377
- texture: DepthTexture;
2378
- width: number;
2379
- height: number;
2380
- samples: number;
2381
- version: number;
2382
- }
2383
- | undefined;
2384
- readonly #previousEye = new Vector3();
2385
- readonly #occlusionView = uniform(new Matrix4());
2386
- readonly #occlusionCut = uniform(1);
2387
- /** Why the measure mode measured nothing, or `""` while it is measuring. */
2388
- #occlusionReason = "";
2389
- /** The last landed tally's occlusion counts, and the running mean over every sample. */
2390
- #occludedInstances = 0;
2391
- #occludedTriangles = 0;
2392
- #occlusionTotalTriangles = 0;
2393
- #occlusionSample = -1;
2394
- #occlusionSamples = 0;
2395
- #occlusionSumInstances = 0;
2396
- #occlusionSumTriangles = 0;
2397
- #tallyPending = false;
2398
- /** Dispatch the in-flight tally readback was issued on, or `-1` when none is in flight. */
2399
- #tallyRequested = -1;
2400
- /** Dispatch whose GPU state the landed tally bytes hold, or `-1` before the first lands. */
2401
- #tallySample = -1;
2402
- #tallyInstances = 0;
2403
- #tallyTriangles = 0;
2404
- #watched = false;
2405
940
  /**
2406
941
  * The main meshes the owner has dressed against these buffers, and the main meshes it holds. It is
2407
942
  * the owner's, not this class's: a scene that reports itself on over a ring it never dressed was
2408
943
  * invisible from here, and `dressed=0/21094` is what a real run printed. See {@link announce}.
2409
944
  */
2410
945
  #census = { dressed: 0, meshes: 0 };
2411
- /** The device's last uncaptured error, reported by the next check and then cleared. */
2412
- #deviceError = "";
2413
-
2414
- /**
2415
- * Ask for the indirect args back, once, and tally what the GPU selected into them.
2416
- *
2417
- * This is the certificate the frame budget could not have: `renderer.info.render.triangles` counts
2418
- * a mesh's CPU window, which for an indirect draw is its capacity and therefore an upper bound,
2419
- * while the args record holds the instance count the kernel actually wrote. The readback is the
2420
- * same one a validation uses — the renderer's one staging buffer — on a slower clock, and a frame
2421
- * whose predecessor is still in flight is skipped rather than queued.
2422
- */
2423
- #tallyRead(renderer: IRendererLike): void {
2424
- const args = this.#buffers?.args;
2425
- if (args === undefined) return;
2426
- const issued = this.#dispatched;
2427
- this.#tallyRequested = issued;
2428
- this.#tallyPending = true;
2429
- // Streaming may grow the args tail while this copy is in flight. Decode its own layout.
2430
- const regions = this.#regions.map((region) => ({ argsIndex: region.argsIndex }));
2431
- const occlusionReason = this.#occlusionReason;
2432
- renderer
2433
- .readback(args)
2434
- .then((bytes) => this.#landTally(bytes, issued, regions, occlusionReason))
2435
- .catch(() => {
2436
- this.#tallyPending = false;
2437
- });
2438
- }
2439
946
 
2440
947
  /**
2441
- * Sum the landed args records: `instanceCount` over every record, and `instanceCount x indexCount`
2442
- * divided by three. A record the GPU never wrote reads as the zero it holds, which is correct —
2443
- * a key that selected nothing draws nothing.
948
+ * Every readback this scene takes, and the modes this launch asked for: the dispatch validation,
949
+ * the GPU-selected tally and the measured occlusion pass. Asked through functions rather than
950
+ * fields, so the answer is the one the moment the read needs it.
2444
951
  */
2445
- #landTally(
2446
- bytes: ArrayBuffer,
2447
- issued: number,
2448
- regions: readonly Pick<IRegion, "argsIndex">[],
2449
- occlusionReason: string,
2450
- ): void {
2451
- this.#tallyPending = false;
2452
- const words = new Uint32Array(bytes);
2453
- let instances = 0;
2454
- let products = 0;
2455
- for (const region of regions) {
2456
- const record = region.argsIndex * DRAW_ARGS_WORDS;
2457
- const count = word(words, record + 1);
2458
- instances += count;
2459
- products += count * word(words, record);
2460
- }
2461
- this.#tallyInstances = instances;
2462
- this.#tallyTriangles = products / 3;
2463
- this.#tallySample = issued;
2464
- if (this.#occlusion !== "off") this.#landOcclusion(words, issued, regions, occlusionReason);
2465
- }
2466
-
2467
- /**
2468
- * What the measured cull hid, out of the same landed bytes as the drawn counts.
2469
- *
2470
- * The tail of the args buffer is one word per key of measured-occlusion instances, so a hidden
2471
- * part's triangles are that word times its own `indexCount` — the same product the tally above
2472
- * sums over the records, which is why both numbers can be divided into a share without a second
2473
- * readback or a second clock.
2474
- */
2475
- #landOcclusion(
2476
- words: Uint32Array,
2477
- issued: number,
2478
- regions: readonly Pick<IRegion, "argsIndex">[],
2479
- sampleReason: string,
2480
- ): void {
2481
- let reason = sampleReason;
2482
- const tail = regions.length * DRAW_ARGS_WORDS;
2483
- if (reason === "" && words.length < tail + regions.length) reason = "skipped: short readback";
2484
- if (
2485
- reason === "" &&
2486
- regions.some(
2487
- (region, index) =>
2488
- word(words, tail + index) > word(words, region.argsIndex * DRAW_ARGS_WORDS + 1),
2489
- )
2490
- )
2491
- reason = "skipped: inconsistent readback";
2492
- if (reason !== "") {
2493
- this.#occlusionReason = reason;
2494
- console.info(
2495
- `TN_WORLD_GPU_SCENE_OCCLUSION mode=${this.#occlusion} dispatch=${String(issued)} skipped=1 reason=${reason}`,
2496
- );
2497
- return;
2498
- }
2499
- let instances = 0;
2500
- let products = 0;
2501
- for (const [index, region] of regions.entries()) {
2502
- const count = word(words, regions.length * DRAW_ARGS_WORDS + index);
2503
- instances += count;
2504
- products += count * word(words, region.argsIndex * DRAW_ARGS_WORDS);
2505
- }
2506
- this.#occludedInstances = instances;
2507
- this.#occludedTriangles = products / 3;
2508
- this.#occlusionReason = "";
2509
- this.#occlusionSample = issued;
2510
- this.#occlusionTotalTriangles = this.#tallyTriangles;
2511
- this.#occlusionSamples += 1;
2512
- this.#occlusionSumInstances += instances;
2513
- this.#occlusionSumTriangles += this.#occludedTriangles;
2514
- const report = this.report().occlusion;
2515
- if (report === undefined) return;
2516
- const line =
2517
- `TN_WORLD_GPU_SCENE_OCCLUSION mode=${report.mode} levels=${String(report.levels)} ` +
2518
- `dispatch=${String(issued)} reason=${report.reason || "none"} ` +
2519
- `wouldCullInstances=${String(report.instances)} wouldCullTriangles=${String(report.triangles)} ` +
2520
- `gpuInstances=${String(this.#tallyInstances)} gpuTriangles=${String(this.#tallyTriangles)} ` +
2521
- `share=${report.share.toFixed(4)}`;
2522
- console.info(line);
2523
- }
2524
-
2525
- /**
2526
- * Read the indirect args and the compacted matrices back and hold both against the reference, over
2527
- * the placements, camera and gate table the dispatch just read — copied at this moment, in this
2528
- * turn, so a structural change landing while the bytes are in flight changes nothing about what
2529
- * they are held against.
2530
- *
2531
- * The reference is {@link cullAndSelect} on the CPU, so this is the kernel measured against the
2532
- * loop it mirrors — the only place the TSL itself is ever checked. It costs two queue submissions
2533
- * and two mapped buffers every {@link VALIDATE_EVERY} dispatches, which is why it is a mode and
2534
- * not a default: a game never pays for it and a walk is never measured with it on. One check is in
2535
- * flight at a time, so every report answers a dispatch of its own.
2536
- *
2537
- * The counts alone are not the draw: a key can land every instance it owes into a record whose
2538
- * `firstInstance` points at the wrong run, or whose `indexCount` names no triangle, or into a
2539
- * region the mesh does not read — and a real WebGPU walk printed `ok` over 200 keys whose
2540
- * `indexCount` was zero, with the forest it was supposed to draw missing from the picture and its
2541
- * shadows still on the ground. So the matrices are read back too, and the same check that reads
2542
- * them holds the record's two CPU-owned words against what the key's geometry and layout say.
2543
- *
2544
- * And the third check reads nothing this file wrote: the owner's own dressed meshes, each with the
2545
- * indirect record its own geometry points at, against the instances the owner's own CPU path
2546
- * composes for the key that mesh is named. Both families above can only confirm that the kernel
2547
- * and the reference agree, which a wrong key-to-record mapping makes them agree on; only these two
2548
- * were not written by the same hand. See {@link compareMeshDraws}.
2549
- */
2550
- #compare(renderer: IRendererLike, frame = -1): Promise<IWorldGpuFrameValidation> {
2551
- const snapshot = this.#snapshot();
2552
- if (snapshot.args === undefined || snapshot.drawn === undefined)
2553
- return Promise.reject(new Error("World GPU frame validation has no dispatched buffers."));
2554
- const reference = cullAndSelect(snapshot);
2555
- // Taken now, with the snapshot, and not when the readback lands: see `drawsFrom`.
2556
- const draws = this.#draws?.() ?? [];
2557
- const issued = this.#dispatched;
2558
- const readbacks = this.#readbacksFor(snapshot);
2559
- this.#validating = true;
2560
- const occlusionReason = this.#occlusionReason;
2561
- const reads = [
2562
- renderer.readback(snapshot.args, readbacks.args),
2563
- renderer.readback(snapshot.drawn, readbacks.drawn),
2564
- ] as const;
2565
- const complete = Promise.all(reads)
2566
- .then(([argsBytes, drawnBytes]) => {
2567
- // The same landed args feed the tally, so a validation pays for it and this adds no copy.
2568
- this.#landTally(argsBytes, issued, snapshot.regions, occlusionReason);
2569
- const input = this.#against(
2570
- snapshot,
2571
- reference,
2572
- new Uint32Array(argsBytes),
2573
- new Float32Array(drawnBytes),
2574
- draws,
2575
- );
2576
- const report = this.#publish(renderer, input);
2577
- return { ...input, dispatch: issued, frame, verdict: report.verdict };
2578
- })
2579
- .catch((reason: unknown) => {
2580
- // A readback that never lands is a check that never ran, and saying so is the whole point:
2581
- // this line used to end the chain and leave the last verdict standing as if it were fresh.
2582
- const input: IGpuSceneComparison = {
2583
- cause: `readback-failed: ${String(reason instanceof Error ? reason.message : reason)}`,
2584
- compared: 0,
2585
- deviceError: this.#deviceError,
2586
- instancesCpu: 0,
2587
- instancesGpu: 0,
2588
- matricesMismatched: 0,
2589
- meshMismatched: 0,
2590
- meshMismatches: [],
2591
- mismatched: 0,
2592
- mismatches: [],
2593
- matrixMismatches: [],
2594
- placed: snapshot.placed,
2595
- };
2596
- const report = this.#publish(renderer, input);
2597
- return { ...input, dispatch: issued, frame, verdict: report.verdict };
2598
- });
2599
- // Promise.all reports the first failure, but its rejection does not mean the other GPU copy has
2600
- // stopped. Release only after both copies settle, so a pending map cannot race a reused target.
2601
- return complete.finally(async () => {
2602
- await Promise.allSettled(reads);
2603
- readbacks.args.release();
2604
- readbacks.drawn.release();
2605
- if (this.#validationReadbacks !== readbacks) {
2606
- readbacks.args.dispose();
2607
- readbacks.drawn.dispose();
2608
- }
2609
- this.#validating = false;
2610
- });
2611
- }
2612
-
2613
- #readbacksFor(snapshot: IValidationSnapshot): IValidationReadbacks {
2614
- const argsBytes = Math.max(
2615
- 4,
2616
- (snapshot.args as { array: { byteLength: number } }).array.byteLength,
2617
- );
2618
- const drawnBytes = Math.max(
2619
- 4,
2620
- (snapshot.drawn as { array: { byteLength: number } }).array.byteLength,
2621
- );
2622
- const current = this.#validationReadbacks;
2623
- if (
2624
- current !== undefined &&
2625
- current.args.maxByteLength >= argsBytes &&
2626
- current.drawn.maxByteLength >= drawnBytes
2627
- )
2628
- return current;
2629
- current?.args.dispose();
2630
- current?.drawn.dispose();
2631
- this.#validationReadbacks = {
2632
- args: new ReadbackBuffer(argsBytes),
2633
- drawn: new ReadbackBuffer(drawnBytes),
2634
- };
2635
- return this.#validationReadbacks;
2636
- }
2637
-
2638
- /**
2639
- * A copy of everything the dispatch that is running right now reads: the source records, the slot
2640
- * and gate tables, the region and args layout, the frustum planes and the eye.
2641
- *
2642
- * One flat array holds the placement records and each copy is a view into it, so a twenty-thousand
2643
- * placement walk costs one allocation rather than forty thousand. The gate and region tables are
2644
- * copied shallowly, which is whole: an asset's gate definition is replaced rather than edited, and
2645
- * a region is spread into a fresh object, so nothing reachable from a snapshot can move under it.
2646
- */
2647
- #snapshot(): IValidationSnapshot {
2648
- const flat = new Float32Array(this.placements.length * PLACEMENT_WORDS);
2649
- const placements = this.placements.map((placement, index) => {
2650
- const at = index * PLACEMENT_WORDS;
2651
- flat.set(placement.matrix, at);
2652
- flat.set(placement.centre, at + LOCAL_WORDS);
2653
- return {
2654
- centre: flat.subarray(at + LOCAL_WORDS, at + LOCAL_WORDS + 4),
2655
- matrix: flat.subarray(at, at + LOCAL_WORDS),
2656
- scale: placement.scale,
2657
- slot: placement.slot,
2658
- };
2659
- });
2660
- return {
2661
- args: this.#buffers?.args,
2662
- camera: {
2663
- planes: this.#planes.slice(),
2664
- x: this.#eye.value.x,
2665
- y: this.#eye.value.y,
2666
- z: this.#eye.value.z,
2667
- },
2668
- count: placements.length,
2669
- drawn: this.#buffers?.drawn,
2670
- placed: this.#live,
2671
- placements,
2672
- regionCount: this.#regions.length,
2673
- regions: this.#regions.map((region) => ({ ...region, local: region.local.slice() })),
2674
- slots: this.gates().map((slot) => ({ ...slot })),
2675
- };
2676
- }
2677
-
2678
- /** One readback's bytes against its own dispatch's reference: the counts, then the draw, then the meshes. */
2679
- #against(
2680
- snapshot: IValidationSnapshot,
2681
- reference: IKernelResult,
2682
- gpu: Uint32Array,
2683
- drawn: Float32Array,
2684
- draws: readonly IMeshDraw[],
2685
- ): IGpuSceneComparison {
2686
- const mismatches: string[] = [];
2687
- const matrixMismatches: string[] = [];
2688
- let mismatched = 0;
2689
- let matricesMismatched = 0;
2690
- let instancesGpu = 0;
2691
- let instancesCpu = 0;
2692
- for (const [index, region] of snapshot.regions.entries()) {
2693
- const record = region.argsIndex * DRAW_ARGS_WORDS;
2694
- // A readback that landed short is a mismatch, not a hole in the report: `word` reads out of
2695
- // range as the zero a record that was never written holds.
2696
- const landed = word(gpu, record + 1);
2697
- const expected = reference.counts[index] as number;
2698
- instancesGpu += landed;
2699
- instancesCpu += expected;
2700
- if (landed !== expected) {
2701
- mismatched += 1;
2702
- if (mismatches.length < VALIDATE_REPORTED_KEYS)
2703
- mismatches.push(
2704
- `${region.name ?? `#${String(index)}`} gpu=${String(landed)} cpu=${String(expected)}`,
2705
- );
2706
- }
2707
- const firstInstance = word(gpu, record + 4);
2708
- const indexCount = word(gpu, record);
2709
- const agrees =
2710
- firstInstance === region.start &&
2711
- indexCount === region.indexCount &&
2712
- sameMatrices(
2713
- drawn,
2714
- firstInstance,
2715
- landed,
2716
- reference.drawn,
2717
- region.start,
2718
- expected,
2719
- MATRIX_TOLERANCE,
2720
- );
2721
- if (agrees) continue;
2722
- matricesMismatched += 1;
2723
- if (matrixMismatches.length < MATRIX_REPORTED_KEYS)
2724
- matrixMismatches.push(
2725
- `${region.name ?? `#${String(index)}`} ` +
2726
- `first gpu=${xyz(drawn, firstInstance)} cpu=${xyz(reference.drawn, region.start)} ` +
2727
- `firstInstance gpu=${String(firstInstance)} expected=${String(region.start)} ` +
2728
- `indexCount gpu=${String(indexCount)} expected=${String(region.indexCount)}`,
2729
- );
2730
- }
2731
- // Off the snapshot's own regions: which key each mesh is, which record it reads and what it
2732
- // should be holding are the owner's numbers, and the whole point is that nothing in this file
2733
- // chose them.
2734
- const meshes = compareMeshDraws(gpu, drawn, draws, snapshot.regions);
2735
- // Both totals at zero is the case that never says why it saw nothing: name the snapshot's own
2736
- // camera and nearest live placement, the two inputs a real static validation needs to tell a
2737
- // missing source from a camera, sphere, range or frustum that rejected every one it held.
2738
- const probe =
2739
- instancesGpu === 0 && instancesCpu === 0 ? zeroComparisonProbe(snapshot) : undefined;
2740
- return {
2741
- compared: snapshot.regions.length,
2742
- deviceError: this.#deviceError,
2743
- instancesCpu,
2744
- instancesGpu,
2745
- matricesMismatched,
2746
- meshMismatched: meshes.mismatched,
2747
- meshMismatches: meshes.mismatches,
2748
- mismatched,
2749
- mismatches,
2750
- matrixMismatches,
2751
- placed: snapshot.placed,
2752
- ...(probe === undefined ? {} : { probe }),
2753
- };
2754
- }
2755
-
2756
- /**
2757
- * One verdict, stored for a harness to read and printed once, with its cause if it failed.
2758
- *
2759
- * The line also carries what the device and this scene held when the check reported, read here
2760
- * rather than polled: `renderer.raw.info.memory` is Three's own tally and `footprint()` is this
2761
- * scene's allocation, so a readback that leaks its staging buffer shows up as growing
2762
- * `readbackBuffers`/`readbackBuffersSize` across reports instead of only as a later OOM. A backend
2763
- * that tracks no memory field contributes none, and no field is ever printed as a fake zero.
2764
- */
2765
- #publish(renderer: IRendererLike, input: IGpuSceneComparison): IGpuSceneValidation {
2766
- const source = (renderer.raw as { info?: { memory?: Partial<Record<string, unknown>> } })?.info
2767
- ?.memory;
2768
- let memory: GpuSceneMemory | undefined;
2769
- // A backend Three keeps no memory tally for contributes nothing, footprint included: a scene
2770
- // number printed next to absent device numbers reads as if the device had been measured.
2771
- if (source !== undefined) {
2772
- memory = {};
2773
- for (const name of MEMORY_FIELDS) {
2774
- const value = source[name];
2775
- if (typeof value === "number" && Number.isFinite(value)) memory[name] = value;
2776
- }
2777
- const footprint = Object.values(this.footprint());
2778
- if (footprint.length > 0)
2779
- memory.footprintBytes = footprint.reduce((sum, buffer) => sum + buffer.bytes, 0);
2780
- }
2781
- const report = validationReport(
2782
- Object.keys(memory ?? {}).length === 0 ? input : { ...input, memory },
2783
- );
2784
- this.#verdict = report.verdict;
2785
- this.#compared = input.compared;
2786
- this.#mismatches = input.mismatched;
2787
- this.#matrixMismatches = input.matricesMismatched;
2788
- this.#meshMismatches = input.meshMismatched;
2789
- this.#lines = [...report.lines];
2790
- // Reported, so cleared: an error is folded into exactly the check that saw it.
2791
- this.#deviceError = "";
2792
- const name =
2793
- "log" in renderer ? (renderer.log as ((message: string) => void) | undefined) : undefined;
2794
- const say = typeof name === "function" ? name : console.info.bind(console);
2795
- say(report.line);
2796
- for (const line of report.lines) say(`TN_WORLD_GPU_SCENE_VALIDATE ${line}`);
2797
- return report;
2798
- }
952
+ readonly #readback: WorldGpuReadback = new WorldGpuReadback({
953
+ on: () => this.#on,
954
+ placements: () => this.placements,
955
+ regions: () => this.#regions,
956
+ buffers: () => this.#buffers,
957
+ planes: () => this.#planes,
958
+ eye: () => this.#eye.value,
959
+ live: () => this.#live,
960
+ gates: () => this.gates(),
961
+ footprint: () => this.footprint(),
962
+ restructure: () => {
963
+ this.#kernel = undefined;
964
+ this.#version += 1;
965
+ },
966
+ });
2799
967
 
2800
968
  dispose(): void {
2801
- const readbacks = this.#validationReadbacks;
2802
- this.#validationReadbacks = undefined;
2803
- if (!this.#validating) {
2804
- readbacks?.args.dispose();
2805
- readbacks?.drawn.dispose();
2806
- }
969
+ this.#readback.dispose();
2807
970
  this.#kernel = undefined;
2808
971
  this.#shadowKernel = undefined;
2809
972
  this.#shadow = undefined;
@@ -2818,10 +981,6 @@ export class WorldGpuScene {
2818
981
  this.#free.length = 0;
2819
982
  this.#live = 0;
2820
983
  this.#on = false;
2821
- this.#tallyPending = false;
2822
- this.#tallyRequested = -1;
2823
- this.#tallySample = -1;
2824
- this.#pyramid.dispose();
2825
984
  }
2826
985
 
2827
986
  readonly #planeVectors = Array.from({ length: 6 }, () => new Vector4());
@@ -2999,122 +1158,23 @@ export class WorldGpuScene {
2999
1158
  }
3000
1159
 
3001
1160
  /**
3002
- * The two dispatches, mirroring {@link cullAndSelect} branch for branch: one thread per key
3003
- * zeroes that key's instance count, one thread per resident placement appends its matrix to each
3004
- * of its level's parts.
1161
+ * Build the two dispatches the main pass submits — one key's count cleared, one placement selected
1162
+ * — and hold them: a capacity change is a new pipeline, and this is the only place one is compiled.
3005
1163
  */
3006
- #buildKernel(): { readonly cull: unknown; readonly clear: unknown } | undefined {
1164
+ #buildKernel(): IGpuKernel | undefined {
3007
1165
  const buffers = this.#buffers;
3008
1166
  if (buffers === undefined) return undefined;
3009
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
3010
- const drawn = nodes(storage(buffers.drawn, "mat4", buffers.drawn.count));
3011
- const argsPlain = nodes(storage(buffers.args, "uint", buffers.args.count));
3012
- const argsAtomic = nodes(storage(buffers.args, "uint", buffers.args.count).toAtomic());
3013
- const keys = nodes(storage(buffers.keys, "vec4", buffers.keys.count));
3014
- const locals = nodes(storage(buffers.locals, "mat4", buffers.locals.count));
3015
- const gates = nodes(storage(buffers.gates, "vec4", buffers.gates.count));
3016
- const levels = nodes(storage(buffers.levels, "vec4", buffers.levels.count));
3017
- const counts = nodes(this.#counts);
3018
- const eye = nodes(this.#eye);
3019
- const bias = nodes(this.#lodBias);
3020
- const planes = this.#planeUniforms.map((plane) => nodes(plane));
3021
- // Measuring doubles the clear: the second thread per key zeroes that key's word of the
3022
- // measured-occlusion tally, which is why the args buffer is sized for it (see `argsWords`).
3023
- // A run that is not measuring never pays the second thread.
3024
- const clearWidth = this.#occlusion === "off" ? 1 : 2;
3025
- const clear = Fn(() => {
3026
- If(instanceIndex.greaterThanEqual(counts.w.mul(clearWidth)), () => Return());
3027
- If(instanceIndex.lessThan(counts.w), () => {
3028
- const key = keys.element(instanceIndex);
3029
- argsPlain.element(key.z.mul(DRAW_ARGS_WORDS).add(1)).assign(int(0));
3030
- });
3031
- If(instanceIndex.greaterThanEqual(counts.w), () => {
3032
- argsPlain
3033
- .element(
3034
- nodes(counts.w.mul(DRAW_ARGS_WORDS)).add(
3035
- nodes(float(instanceIndex).sub(counts.w).floor()),
3036
- ),
3037
- )
3038
- .assign(int(0));
3039
- });
3040
- })().compute(Math.max(1, buffers.keys.count * clearWidth));
3041
- const cull = Fn(() => {
3042
- If(instanceIndex.greaterThanEqual(counts.x), () => Return());
3043
- const placement = source.element(instanceIndex);
3044
- const centre = placement.get("centre");
3045
- const matrix = placement.get("matrix");
3046
- const slot = placement.get("info").x;
3047
- If(slot.lessThan(0.0), () => Return());
3048
- If(slot.greaterThanEqual(counts.y), () => Return());
3049
- const radius = centre.w;
3050
- for (const plane of planes)
3051
- If(plane.dot(centre.xyz).lessThan(radius.negate()), () => Return());
3052
- const gate = gates.element(slot);
3053
- const distance = length(vec3(centre.x.sub(eye.x), 0.0, centre.z.sub(eye.z)));
3054
- If(gate.w.mod(2.0).greaterThan(0.5).and(distance.greaterThan(gate.z)), () => Return());
3055
- // Cull above is the authored distance; the level below is the same distance scaled by the
3056
- // adaptive bias, mirroring `cullAndSelect` and the CPU `model-lod` path.
3057
- const lodDistance = nodes(distance).mul(bias as never);
3058
- // The level, by the same ascending test the CPU runs: the last gate the placement is past.
3059
- // The loop is bounded by `gate.y` rather than unrolled, because a baked chain can carry more
3060
- // levels than any fixed count, and a level the loop stopped short of is a placement drawn at
3061
- // the wrong shape by however many levels it missed.
3062
- const level = int(0).toVar();
3063
- // The placement's own uniform scale, written into `info.y`; the whole-asset impostor's terminal
3064
- // gate is the base projected distance and is scaled by it. A mirrored placement's scale is
3065
- // negative, and the extent it reaches is the same, so the kernel takes the magnitude exactly as
3066
- // `levelAtGates` does; `info.y` is already finite-sanitised when the record is written.
3067
- const scale = abs(placement.get("info").y);
3068
- Loop({ start: int(1), end: gate.y, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
3069
- const candidate = levels.element(gate.x.add(i as never));
3070
- const threshold = nodes(candidate.x).toVar();
3071
- // Only the terminal level carries this mark: its stored distance is the base-sphere projected
3072
- // one, so its real threshold is `max(strictly after last source gate, base * |scale|)`. The
3073
- // source floor is the previous level's own authored gate, unscaled and nudged one f32 step,
3074
- // so a small scale cannot starve the last source level by sharing its switch distance.
3075
- If(candidate.w.greaterThan(0.5), () => {
3076
- const previous = levels.element(gate.x.add(i as never).sub(1)).x;
3077
- const floor = previous.add(abs(previous).mul(GATE_STEP));
3078
- threshold.assign(max(floor, candidate.x.mul(scale)));
3079
- });
3080
- // A level the prewarm has minted no key for is not taken: the gate table names every level of
3081
- // an asset from the moment it is adopted, and the draw loop below would run this level's
3082
- // zero keys, so the placement would be selected and drawn nowhere while the CPU path drew it
3083
- // and its shadow halves drew under it. The last level that has keys keeps it. See
3084
- // `drawableLevel`, which the reference mirrors.
3085
- If(lodDistance.greaterThan(threshold), () => {
3086
- If(candidate.z.greaterThan(0.5), () => {
3087
- level.assign(i as never);
3088
- });
3089
- });
3090
- });
3091
- const at = levels.element(gate.x.add(level));
3092
- // The pyramid test, once per placement: a placement the frustum and the gates kept, reprojected
3093
- // into the previous frame's pyramid. Measured only, so the write below happens either way and
3094
- // the indirect counts are develop's.
3095
- const hidden = float(0).toVar();
3096
- if (this.#occlusion !== "off" && this.#pyramid.levels > 0)
3097
- hidden.assign(
3098
- this.#pyramid.occluded(centre.xyz, radius, this.#occlusionView, this.#occlusionCut),
3099
- );
3100
- Loop({ start: int(0), end: at.z, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
3101
- const keyIndex = at.y.add(i as never);
3102
- const key = keys.element(keyIndex);
3103
- If(hidden.greaterThan(0.5), () => {
3104
- atomicAdd(argsAtomic.element(counts.w.mul(DRAW_ARGS_WORDS).add(keyIndex)), int(1));
3105
- });
3106
- const taken = nodes(
3107
- atomicAdd(argsAtomic.element(key.z.mul(DRAW_ARGS_WORDS).add(1)), int(1)),
3108
- );
3109
- If(taken.toFloat().lessThan(key.y), () => {
3110
- drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
3111
- });
3112
- });
3113
- })().compute(Math.max(1, buffers.source.count));
3114
- clear.setName("worldGpuSceneClear");
3115
- cull.setName("worldGpuSceneCull");
3116
- this.#kernel = { clear, cull };
3117
- return this.#kernel;
1167
+ const occlusion = this.#readback.occlusionBinding();
1168
+ const kernel = buildCullKernel({
1169
+ buffers,
1170
+ bias: this.#lodBias,
1171
+ counts: this.#counts,
1172
+ eye: this.#eye,
1173
+ planes: this.#planeUniforms,
1174
+ ...(occlusion === undefined ? {} : { occlusion }),
1175
+ });
1176
+ this.#kernel = kernel;
1177
+ return kernel;
3118
1178
  }
3119
1179
 
3120
1180
  /**
@@ -3201,136 +1261,26 @@ export class WorldGpuScene {
3201
1261
  }
3202
1262
 
3203
1263
  /**
3204
- * The shadow twin of {@link #buildKernel}: the same clear and the same per-placement selection,
3205
- * reading the same source, gate, level and key tables and writing the twin records and runs.
3206
- *
3207
- * Two branches are the level's rather than the camera's — the planes it tests against and its
3208
- * texel gate — and one is the level's base, which floors the main pass's own level at the shape the
3209
- * cluster path hands it. A level whose key has no minted twin (`keys.w`) casts nothing.
1264
+ * The shadow twin of {@link #buildKernel}, for one level's numbers: the same clear and the same
1265
+ * per-placement selection, writing the twin records and runs.
3210
1266
  */
3211
- #buildShadowKernel(): { readonly cull: unknown; readonly clear: unknown } | undefined {
1267
+ #buildShadowKernel(): IGpuKernel | undefined {
3212
1268
  const buffers = this.#buffers;
3213
1269
  const shadow = this.#shadow;
3214
1270
  if (buffers === undefined || shadow === undefined) return undefined;
3215
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
3216
- const drawn = nodes(storage(shadow.drawn, "mat4", shadow.drawn.count));
3217
- const argsPlain = nodes(storage(shadow.args, "uint", shadow.args.count));
3218
- const argsAtomic = nodes(storage(shadow.args, "uint", shadow.args.count).toAtomic());
3219
- const keys = nodes(storage(buffers.keys, "vec4", buffers.keys.count));
3220
- const locals = nodes(storage(buffers.locals, "mat4", buffers.locals.count));
3221
- const gates = nodes(storage(buffers.gates, "vec4", buffers.gates.count));
3222
- const levels = nodes(storage(buffers.levels, "vec4", buffers.levels.count));
3223
- const counts = nodes(this.#counts);
3224
- // The main pass's own eye and bias, which this frame's main dispatch set: a shadow map draws each
3225
- // placement at the level the main pass draws it, as the cluster path does.
3226
- const eye = nodes(this.#eye);
3227
- const bias = nodes(this.#lodBias);
3228
- const gate = nodes(this.#shadowGate);
3229
- const base = nodes(this.#shadowBase);
3230
- const planes = this.#shadowPlaneUniforms.map((plane) => nodes(plane));
3231
- // Measuring doubles the clear: the second thread per key zeroes that key's word of the
3232
- // measured-occlusion tally, which is why the args buffer is sized for it (see `argsWords`).
3233
- // A run that is not measuring never pays the second thread.
3234
- const clearWidth = this.#occlusion === "off" ? 1 : 2;
3235
- const clear = Fn(() => {
3236
- If(instanceIndex.greaterThanEqual(counts.w.mul(clearWidth)), () => Return());
3237
- If(instanceIndex.lessThan(counts.w), () => {
3238
- const key = keys.element(instanceIndex);
3239
- argsPlain.element(key.z.mul(DRAW_ARGS_WORDS).add(1)).assign(int(0));
3240
- });
3241
- If(instanceIndex.greaterThanEqual(counts.w), () => {
3242
- argsPlain
3243
- .element(
3244
- nodes(counts.w.mul(DRAW_ARGS_WORDS)).add(
3245
- nodes(float(instanceIndex).sub(counts.w).floor()),
3246
- ),
3247
- )
3248
- .assign(int(0));
3249
- });
3250
- })().compute(Math.max(1, buffers.keys.count * clearWidth));
3251
- const cull = Fn(() => {
3252
- If(instanceIndex.greaterThanEqual(counts.x), () => Return());
3253
- const placement = source.element(instanceIndex);
3254
- const centre = placement.get("centre");
3255
- const matrix = placement.get("matrix");
3256
- const slot = placement.get("info").x;
3257
- If(slot.lessThan(0.0), () => Return());
3258
- If(slot.greaterThanEqual(counts.y), () => Return());
3259
- const radius = centre.w;
3260
- for (const plane of planes)
3261
- If(plane.dot(centre.xyz).lessThan(radius.negate()), () => Return());
3262
- // Sub-texel, the level's own gate rather than a camera's: a caster this map cannot resolve
3263
- // casts no shadow a fragment could tell from ground cover.
3264
- If(gate.greaterThan(0.0).and(radius.mul(2.0).lessThan(gate)), () => Return());
3265
- const asset = gates.element(slot);
3266
- const distance = length(vec3(centre.x.sub(eye.x), 0.0, centre.z.sub(eye.z)));
3267
- If(asset.w.mod(2.0).greaterThan(0.5).and(distance.greaterThan(asset.z)), () => Return());
3268
- // The main pass's own biased distance and level; see `shadowLevel`, which the reference runs.
3269
- const lodDistance = nodes(distance).mul(bias as never);
3270
- const level = int(0).toVar();
3271
- const scale = abs(placement.get("info").y);
3272
- Loop(
3273
- { start: int(1), end: asset.y, type: "int", condition: "<" },
3274
- ({ i }: { i: unknown }) => {
3275
- const candidate = levels.element(asset.x.add(i as never));
3276
- const threshold = nodes(candidate.x).toVar();
3277
- If(candidate.w.greaterThan(0.5), () => {
3278
- const previous = levels.element(asset.x.add(i as never).sub(1)).x;
3279
- const floor = previous.add(abs(previous).mul(GATE_STEP));
3280
- threshold.assign(max(floor, candidate.x.mul(scale)));
3281
- });
3282
- // A level the prewarm has minted no key for is not taken, as in the main kernel: see
3283
- // `drawableLevel`, which the reference mirrors.
3284
- If(lodDistance.greaterThan(threshold), () => {
3285
- If(candidate.z.greaterThan(0.5), () => {
3286
- level.assign(i as never);
3287
- });
3288
- });
3289
- },
3290
- );
3291
- // A level casts when its first key has a minted twin (`keys.w`). The shape is the last
3292
- // casting level in `[0, max(level, base)]`: a placement whose own level casts nothing casts
3293
- // with the coarsest one below it that does, and the map's base floors it, clamped to the last
3294
- // level that casts, so a coarse map never asks for a twin that was not minted. None: no cast.
3295
- const castsAt = (index: unknown): unknown => {
3296
- const entry = levels.element(asset.x.add(index as never));
3297
- return nodes(entry.z.greaterThan(0.5)).and(keys.element(entry.y).w.greaterThan(0.5));
3298
- };
3299
- // Authored LODs past castLevels cast nothing, matching WorldCells#castLevelOf.
3300
- If(asset.w.greaterThan(1.5).and(nodes(castsAt(level)).not()), () => Return());
3301
- const shape = int(-1).toVar();
3302
- Loop(
3303
- {
3304
- start: int(0),
3305
- end: nodes(
3306
- max(level as never, int(min(base as never, asset.y.sub(1.0) as never)) as never),
3307
- ).add(1),
3308
- type: "int",
3309
- condition: "<",
3310
- },
3311
- ({ i }: { i: unknown }) => {
3312
- If(castsAt(i) as never, () => {
3313
- shape.assign(i as never);
3314
- });
3315
- },
3316
- );
3317
- If(shape.lessThan(0), () => Return());
3318
- const at = levels.element(asset.x.add(shape));
3319
- Loop({ start: int(0), end: at.z, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
3320
- const keyIndex = at.y.add(i as never);
3321
- const key = keys.element(keyIndex);
3322
- const taken = nodes(
3323
- atomicAdd(argsAtomic.element(key.z.mul(DRAW_ARGS_WORDS).add(1)), int(1)),
3324
- );
3325
- If(taken.toFloat().lessThan(key.y), () => {
3326
- drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
3327
- });
3328
- });
3329
- })().compute(Math.max(1, buffers.source.count));
3330
- clear.setName("worldGpuSceneShadowClear");
3331
- cull.setName("worldGpuSceneShadowCull");
3332
- this.#shadowKernel = { clear, cull };
3333
- return this.#shadowKernel;
1271
+ const kernel = buildShadowKernel({
1272
+ base: this.#shadowBase,
1273
+ bias: this.#lodBias,
1274
+ buffers,
1275
+ counts: this.#counts,
1276
+ eye: this.#eye,
1277
+ gate: this.#shadowGate,
1278
+ measureOcclusion: this.#readback.measuring,
1279
+ planes: this.#shadowPlaneUniforms,
1280
+ shadow,
1281
+ });
1282
+ this.#shadowKernel = kernel;
1283
+ return kernel;
3334
1284
  }
3335
1285
 
3336
1286
  #report(renderer: IRendererLike): void {