@threenative/core 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
@@ -0,0 +1,596 @@
1
+ import type { DepthTexture } from "three";
2
+ import { Vector2 } from "three";
3
+ import {
4
+ Fn,
5
+ If,
6
+ Return,
7
+ abs,
8
+ ceil,
9
+ clamp,
10
+ float,
11
+ instanceIndex,
12
+ int,
13
+ ivec2,
14
+ log2,
15
+ max,
16
+ min,
17
+ pow,
18
+ storage,
19
+ textureLoad,
20
+ uniform,
21
+ vec3,
22
+ vec4,
23
+ } from "three/tsl";
24
+ import { StorageBufferAttribute } from "three/webgpu";
25
+
26
+ /**
27
+ * The hierarchical-depth (pyramid) occlusion test, and the max-distance pyramid it reads.
28
+ *
29
+ * The pyramid is a previous frame's own depth, reduced so that one texel of a level covers `2^level`
30
+ * pixels of the level below it and every texel holds the *farthest* surface inside its footprint.
31
+ * Farthest, not nearest: a sphere is only hidden when its nearest point is behind the farthest
32
+ * thing already drawn in front of it, so a max reduction is the conservative direction and a min
33
+ * reduction would reject objects a fragment can still see.
34
+ *
35
+ * Two readers, one rule. {@link occludedBy} is the reference in plain TypeScript and
36
+ * {@link DepthPyramid.occluded} is the same rule in TSL for the cull kernel. Four answers are never
37
+ * "hidden", and each is a case the test has to get right rather than a tuning choice:
38
+ * - a camera cut — a teleport or a projection change — skips the test for the whole frame, because
39
+ * the pyramid is a different camera's depth;
40
+ * - a sphere that touches the near plane has no last-frame screen rect to compare against;
41
+ * - a sphere that fell off screen last frame has no texel to read;
42
+ * - a sphere whose footprint is a single texel at every level is kept, because the level it would
43
+ * need does not exist and a coarser level would reject it wrongly.
44
+ *
45
+ * Nothing here decides a look: the test reads depths and answers a boolean.
46
+ */
47
+
48
+ /** The launch flag. */
49
+ export const OCCLUSION_FLAG = "TN_OCCLUSION";
50
+
51
+ /** What a launch asked the GPU-scene occlusion cull to do. `measure` counts; `off` runs no test. */
52
+ export type OcclusionMode = "off" | "measure";
53
+
54
+ /**
55
+ * What this launch asked for.
56
+ *
57
+ * @situation measure what a pyramid occlusion cull would cull on map-walk, without culling it
58
+ * @constraint `measure` never changes what is drawn: it runs the test and counts the answer, so a
59
+ * measured frame is the frame an unmeasured run draws. `off`, the default, runs no test and
60
+ * allocates nothing. An unknown value throws rather than picking one.
61
+ * @example WorldCells.load({ ...options, gpuScene: true, occlusion: occlusionMode() });
62
+ *
63
+ * Read the way `gpuSceneRequested` reads its own: a native launch sets the environment variable, a
64
+ * browser asks with `?tnOcclusion=measure`, and a test sets the global.
65
+ */
66
+ export function occlusionMode(): OcclusionMode {
67
+ const host = globalThis as {
68
+ process?: { env?: Record<string, unknown> };
69
+ __tnOcclusion?: unknown;
70
+ location?: { search?: string };
71
+ };
72
+ const fromEnv = host.process?.env?.[OCCLUSION_FLAG];
73
+ const query = host.location?.search;
74
+ const asked =
75
+ typeof fromEnv === "string" && fromEnv !== ""
76
+ ? fromEnv
77
+ : typeof query === "string"
78
+ ? (/[?&]tnOcclusion=([^&]*)/u.exec(query)?.[1] ?? "")
79
+ : typeof host.__tnOcclusion === "string"
80
+ ? host.__tnOcclusion
81
+ : "";
82
+ const value = asked.trim().toLowerCase();
83
+ if (value === "" || value === "0" || value === "off" || value === "false") return "off";
84
+ if (value === "measure" || value === "1" || value === "true") return "measure";
85
+ throw new Error(`${OCCLUSION_FLAG}: unknown mode "${asked}". Use "off" or "measure".`);
86
+ }
87
+
88
+ /** One level of the pyramid: the farthest view-axis distance each texel of it saw, in metres. */
89
+ export interface IDepthPyramidLevel {
90
+ readonly width: number;
91
+ readonly height: number;
92
+ readonly distance: Float32Array;
93
+ }
94
+
95
+ /** The max-distance chain, level 0 first and the coarsest last. */
96
+ export interface IDepthPyramid {
97
+ readonly levels: readonly IDepthPyramidLevel[];
98
+ }
99
+
100
+ /** The camera the pyramid was built from, which is the only camera the test reprojects into. */
101
+ export interface IOcclusionFrame {
102
+ /** Column-major `projection * viewInverse` of the frame the pyramid came from. */
103
+ readonly viewProjection: Float32Array;
104
+ /** The frame's own drawing-buffer size, which is what level 0's texels are pixels of. */
105
+ readonly width: number;
106
+ readonly height: number;
107
+ /** A teleport or a projection change: the test is skipped for the whole frame. */
108
+ readonly cut: boolean;
109
+ readonly near?: number;
110
+ }
111
+
112
+ /** The pyramid a cull tests against, and whether a hidden placement is dropped or only counted. */
113
+ export interface IKernelOcclusion {
114
+ readonly frame: IOcclusionFrame;
115
+ readonly pyramid: IDepthPyramid;
116
+ /**
117
+ * `false` measures: a placement the test hides is counted and still drawn, which is the point of
118
+ * a measured frame — the picture is the unmeasured one and the count is the hypothesis. `true` is
119
+ * the cull the next phase turns on by default.
120
+ */
121
+ readonly cull: boolean;
122
+ }
123
+
124
+ /**
125
+ * The max-distance chain of a frame's own view-axis depths. Level 0 is the buffer handed in and
126
+ * every level above it is the 2x2 maximum of the level below, clamped at the edge so an odd width
127
+ * loses no texel to an out-of-range read.
128
+ */
129
+ export function buildDepthPyramid(
130
+ distance: Float32Array,
131
+ width: number,
132
+ height: number,
133
+ ): IDepthPyramid {
134
+ const levels: IDepthPyramidLevel[] = [{ width, height, distance }];
135
+ let source = levels[0] as IDepthPyramidLevel;
136
+ while (source.width > 1 || source.height > 1) {
137
+ const next = reduceMax(source);
138
+ levels.push(next);
139
+ source = next;
140
+ }
141
+ return { levels };
142
+ }
143
+
144
+ /** One level up: the 2x2 maximum of `source`, clamped at the edge so an odd size keeps every texel. */
145
+ function reduceMax(source: IDepthPyramidLevel): IDepthPyramidLevel {
146
+ const width = Math.max(1, Math.ceil(source.width / 2));
147
+ const height = Math.max(1, Math.ceil(source.height / 2));
148
+ const next: IDepthPyramidLevel = { width, height, distance: new Float32Array(width * height) };
149
+ for (let y = 0; y < height; y += 1) {
150
+ for (let x = 0; x < width; x += 1) {
151
+ let far = 0;
152
+ for (const [dx, dy] of [
153
+ [0, 0],
154
+ [1, 0],
155
+ [0, 1],
156
+ [1, 1],
157
+ ] as const) {
158
+ const sx = Math.min(source.width - 1, x * 2 + dx);
159
+ const sy = Math.min(source.height - 1, y * 2 + dy);
160
+ far = Math.max(far, source.distance[sy * source.width + sx] as number);
161
+ }
162
+ next.distance[y * width + x] = far;
163
+ }
164
+ }
165
+ return next;
166
+ }
167
+
168
+ /**
169
+ * Would this placement be hidden from the frame the pyramid came from?
170
+ *
171
+ * The sphere is reprojected into last frame's clip space, where `w` is its view-axis distance, and
172
+ * its screen half-extent bounds both the numerator and perspective divide over the sphere.
173
+ * Row lengths recover projection scale even after camera rotation. The level is the
174
+ * one whose texels cover the footprint, and the answer is whether the sphere's
175
+ * nearest point along the view axis is behind the farthest distance the four texels under it hold.
176
+ */
177
+ export function occludedBy(
178
+ occlusion: IKernelOcclusion,
179
+ centre: ArrayLike<number>,
180
+ radius: number,
181
+ ): boolean {
182
+ const { frame, pyramid } = occlusion;
183
+ // A camera cut skips the test for the frame: the pyramid is a different camera's depth.
184
+ if (frame.cut) return false;
185
+ const levels = pyramid.levels;
186
+ const base = levels[0] as IDepthPyramidLevel;
187
+ const projected = projectInto(frame, centre, radius, base);
188
+ if (projected === undefined) return false;
189
+ const index = Math.min(
190
+ levels.length - 1,
191
+ Math.max(0, Math.ceil(Math.log2(projected.diameter(base)))),
192
+ );
193
+ const level = levels[index] as IDepthPyramidLevel;
194
+ const far = footprintMax(
195
+ level,
196
+ base.width / 2 ** index,
197
+ base.height / 2 ** index,
198
+ projected.at,
199
+ projected.row,
200
+ projected.halfX,
201
+ projected.halfY,
202
+ );
203
+ return projected.w - radius > far;
204
+ }
205
+
206
+ /** A sphere in the frame's clip space and the texels under it, or `undefined` when it is kept. */
207
+ interface IProjectedSphere {
208
+ readonly w: number;
209
+ readonly at: number;
210
+ readonly row: number;
211
+ readonly halfX: number;
212
+ readonly halfY: number;
213
+ /** The footprint's diameter in level-0 texels, which is what picks the level. */
214
+ diameter(base: IDepthPyramidLevel): number;
215
+ }
216
+
217
+ /**
218
+ * The sphere as last frame's camera saw it, or `undefined` for the two answers that are never
219
+ * "hidden": a sphere reaching the near plane, and a sphere off screen last frame.
220
+ */
221
+ function projectInto(
222
+ frame: IOcclusionFrame,
223
+ centre: ArrayLike<number>,
224
+ radius: number,
225
+ base: IDepthPyramidLevel,
226
+ ): IProjectedSphere | undefined {
227
+ const m = frame.viewProjection;
228
+ const x = centre[0] as number;
229
+ const y = centre[1] as number;
230
+ const z = centre[2] as number;
231
+ // `w` is the view-axis distance: a sphere reaching the near plane has no rect to compare.
232
+ const w = (m[3] as number) * x + (m[7] as number) * y + (m[11] as number) * z + (m[15] as number);
233
+ if (w - radius <= (frame.near ?? 0)) return undefined;
234
+ const ndcX =
235
+ ((m[0] as number) * x + (m[4] as number) * y + (m[8] as number) * z + (m[12] as number)) / w;
236
+ const ndcY =
237
+ ((m[1] as number) * x + (m[5] as number) * y + (m[9] as number) * z + (m[13] as number)) / w;
238
+ // Expand one base texel for raster edges and the padded last texel of an odd-sized depth.
239
+ const halfX =
240
+ (radius * (Math.hypot(m[0] as number, m[4] as number, m[8] as number) + Math.abs(ndcX))) /
241
+ (w - radius) +
242
+ 2 / base.width;
243
+ const halfY =
244
+ (radius * (Math.hypot(m[1] as number, m[5] as number, m[9] as number) + Math.abs(ndcY))) /
245
+ (w - radius) +
246
+ 2 / base.height;
247
+ if (Math.abs(ndcX) + halfX > 1 || Math.abs(ndcY) + halfY > 1) return undefined;
248
+ return {
249
+ diameter: (base) => Math.max(1, Math.max(halfX * base.width, halfY * base.height)),
250
+ halfX,
251
+ halfY,
252
+ row: 0.5 - ndcY * 0.5,
253
+ at: ndcX * 0.5 + 0.5,
254
+ w,
255
+ };
256
+ }
257
+
258
+ /**
259
+ * The farthest distance the 2x2 texel block under a sphere's corner holds.
260
+ *
261
+ * The level is chosen so the sphere spans about one texel of it, so this block is the whole of the
262
+ * sphere's last-frame footprint; the edge clamp is what an odd width costs.
263
+ */
264
+ function footprintMax(
265
+ level: IDepthPyramidLevel,
266
+ spanX: number,
267
+ spanY: number,
268
+ at: number,
269
+ row: number,
270
+ halfX: number,
271
+ halfY: number,
272
+ ): number {
273
+ const x = Math.max(0, Math.min(level.width - 1, Math.floor((at - halfX / 2) * spanX)));
274
+ const y = Math.max(0, Math.min(level.height - 1, Math.floor((row - halfY / 2) * spanY)));
275
+ let far = 0;
276
+ for (let dy = 0; dy < 2; dy += 1) {
277
+ for (let dx = 0; dx < 2; dx += 1) {
278
+ const x2 = Math.min(level.width - 1, x + dx);
279
+ const y2 = Math.min(level.height - 1, y + dy);
280
+ far = Math.max(far, level.distance[y2 * level.width + x2] as number);
281
+ }
282
+ }
283
+ return far;
284
+ }
285
+
286
+ /**
287
+ * A TSL node this module reads through the swizzles and the `.element()` chain.
288
+ *
289
+ * Three's node types are precise about which swizzle a `vec4` answers and deliberately vague about
290
+ * what a storage element or a texture load resolves to, and the pyramid is the one place in core
291
+ * that has to read a matrix column and a loaded depth. The cast is confined here so the shader
292
+ * reads as the plain thing it is.
293
+ */
294
+ // quality-allow: the pyramid is a typed handle onto three's TSL nodes, which resolve to `any` in 0.185.
295
+ // biome-ignore lint/suspicious/noExplicitAny: three's TSL types refuse the chains these shaders read.
296
+ type Kernel = any;
297
+
298
+ /** A TSL value this module builds its shaders from. */
299
+ function nodes(value: unknown): Kernel {
300
+ return value as Kernel;
301
+ }
302
+
303
+ /** Words of per-level table each level's row occupies, at the head of the pyramid's one buffer. */
304
+ const TABLE_WORDS = 4;
305
+
306
+ /** The 2x2 footprint every level of the chain reduces, in the order the loop walks it. */
307
+ const FOOTPRINT = [
308
+ [0, 0],
309
+ [1, 0],
310
+ [0, 1],
311
+ [1, 1],
312
+ ] as const;
313
+
314
+ /**
315
+ * The GPU half of the same rule: the buffers a level is written into, the per-level table the test
316
+ * addresses them by, and one dispatch per level that reduces the level below — or the frame's own
317
+ * depth texture, for level 0.
318
+ *
319
+ * Level 0 is half the depth's own resolution, so the chain starts one texel per four pixels. That
320
+ * is the granularity this shape of cull always has: a sphere narrower than a texel cannot be
321
+ * tested at all, and a finer level 0 would only lengthen the chain without rejecting more.
322
+ */
323
+ /**
324
+ * The GPU half of the same rule, and the whole pyramid in one storage buffer.
325
+ *
326
+ * One buffer and not two is a device limit, not a taste: the cull kernel already binds seven storage
327
+ * buffers and WebGPU refuses a pipeline over eight per stage unless the device was asked for more —
328
+ * measured on the RTX 2080 as `The number of storage buffers (9) in the Compute stage exceeds the
329
+ * maximum per-stage limit (8)`. So the per-level table is the head of this one buffer, four words a
330
+ * level, and the distances follow at each level's own offset.
331
+ */
332
+ export class DepthPyramid {
333
+ /** `[width, height, offset, 0]` per level, then every level's distances. */
334
+ #words = new StorageBufferAttribute(new Float32Array(TABLE_WORDS), 1);
335
+ /** The depth texture's own size, which level 0 reads its 2x2 footprint out of. */
336
+ readonly #depthSize = uniform(new Vector2(1, 1));
337
+ /** `(near, far)` of the frame the depth came from, which turn its NDC depth into metres. */
338
+ readonly #nearFar = uniform(new Vector2(0.1, 1000));
339
+ #levels: { width: number; height: number; offset: number }[] = [];
340
+ #kernels: Kernel[] = [];
341
+ #depth: DepthTexture | undefined;
342
+ #samples = 1;
343
+ #disposed = false;
344
+
345
+ /** The chain's level count, which is also the clamp the test's level selection runs into. */
346
+ get levels(): number {
347
+ return this.#levels.length;
348
+ }
349
+
350
+ /** One storage binding for the table and the distances together, as the cull kernel reads it. */
351
+ get chain(): Kernel {
352
+ return nodes(storage(this.#words, "float", this.#words.count));
353
+ }
354
+
355
+ /**
356
+ * Size the chain for a depth texture and write its per-level table.
357
+ *
358
+ * Structural: a resize replaces the buffer, so every level kernel is a new pipeline. A depth that
359
+ * did not change size is left alone, because a frame never reallocates.
360
+ */
361
+ resize(depthWidth: number, depthHeight: number): boolean {
362
+ const levels: { width: number; height: number; offset: number }[] = [];
363
+ let span = 0;
364
+ let width = Math.max(1, Math.ceil(depthWidth / 2));
365
+ let height = Math.max(1, Math.ceil(depthHeight / 2));
366
+ // Down to a single texel, and the loop condition is that texel rather than `width > 0`: a `1`
367
+ // halved is `0` and floored back to `1`, so a positive-width test never ends.
368
+ while (true) {
369
+ levels.push({ width, height, offset: span });
370
+ span += width * height;
371
+ if (width === 1 && height === 1) break;
372
+ width = Math.max(1, Math.ceil(width / 2));
373
+ height = Math.max(1, Math.ceil(height / 2));
374
+ }
375
+ // The distances start after the table, whose width the loop above only now knows.
376
+ for (const level of levels) level.offset += levels.length * TABLE_WORDS;
377
+ const held = this.#levels;
378
+ if (
379
+ levels.length === held.length &&
380
+ levels.every((level, index) => {
381
+ const own = held[index];
382
+ return own !== undefined && own.width === level.width && own.height === level.height;
383
+ })
384
+ )
385
+ return false;
386
+ this.#words = new StorageBufferAttribute(
387
+ new Float32Array(levels.length * TABLE_WORDS + span),
388
+ 1,
389
+ );
390
+ const table = this.#words.array as Float32Array;
391
+ for (const [index, level] of levels.entries()) {
392
+ table[index * TABLE_WORDS] = level.width;
393
+ table[index * TABLE_WORDS + 1] = level.height;
394
+ table[index * TABLE_WORDS + 2] = level.offset;
395
+ }
396
+ this.#words.needsUpdate = true;
397
+ this.#levels = levels;
398
+ this.#kernels = [];
399
+ return true;
400
+ }
401
+
402
+ /**
403
+ * Resolve every sample of the previous frame's stored depth into level 0, then reduce the chain.
404
+ * The resolve shares level 0's dispatch, so timing the whole chain includes that cost.
405
+ */
406
+ build(
407
+ renderer: { compute(node: unknown, span?: "depthPyramid"): void },
408
+ depth: DepthTexture,
409
+ near: number,
410
+ far: number,
411
+ samples = 1,
412
+ ): number {
413
+ if (this.#disposed || this.#levels.length === 0) return 0;
414
+ if (depth !== this.#depth || samples !== this.#samples) {
415
+ this.#kernels = [];
416
+ this.#depth = depth;
417
+ this.#samples = samples;
418
+ }
419
+ this.#depthSize.value.set(depth.image.width ?? 0, depth.image.height ?? 0);
420
+ this.#nearFar.value.set(near, far);
421
+ // Three timestamps a compute group around all its dispatches, including level 0's depth resolve.
422
+ for (const [index] of this.#levels.entries()) this.#levelKernel(index, depth);
423
+ renderer.compute(this.#kernels, "depthPyramid");
424
+ return this.#levels.length;
425
+ }
426
+
427
+ /**
428
+ * One level's reduction, as its own pipeline with its own level baked in.
429
+ *
430
+ * The level is a constant rather than a uniform because a uniform written between two dispatches of
431
+ * the same frame only re-uploads if the node happens to flush per dispatch, and a pyramid that
432
+ * reduced the wrong level is still a pyramid. With the level constant the level it reads is a
433
+ * constant too, so this shader carries no table reads at all.
434
+ */
435
+ #levelKernel(index: number, depth: DepthTexture): unknown {
436
+ const held = this.#kernels[index];
437
+ if (held !== undefined) return held;
438
+ const own = this.#levels[index] as { width: number; height: number; offset: number };
439
+ const below = this.#levels[index - 1];
440
+ const chain = this.chain;
441
+ const depthSize = nodes(this.#depthSize);
442
+ const nearFar = nodes(this.#nearFar);
443
+ const built = nodes(
444
+ Fn(() => {
445
+ // One thread per texel of this level, addressed as a float: TSL's clamp is float-only, so
446
+ // the whole reduction stays in floats and converts once, at the storage index.
447
+ const linear = float(instanceIndex);
448
+ If(linear.greaterThanEqual(own.width * own.height), () => {
449
+ Return();
450
+ });
451
+ const y = linear.div(own.width).floor();
452
+ const x = linear.sub(y.mul(own.width));
453
+ const far = float(0).toVar();
454
+ for (const [dx, dy] of FOOTPRINT) {
455
+ // Resolve the stored MSAA attachment into this single-distance buffer. Max over every
456
+ // sample keeps an uncovered edge sample; copying depth or changing the main pass is unnecessary.
457
+ for (
458
+ let sampleIndex = 0;
459
+ sampleIndex < (below === undefined ? this.#samples : 1);
460
+ sampleIndex += 1
461
+ ) {
462
+ const sample =
463
+ below === undefined
464
+ ? nodes(nearFar.x)
465
+ .mul(nodes(nearFar.y))
466
+ .div(
467
+ nodes(nearFar.y).sub(
468
+ nodes(nearFar.y)
469
+ .sub(nodes(nearFar.x))
470
+ .mul(
471
+ textureLoad(
472
+ depth,
473
+ nodes(
474
+ ivec2(
475
+ int(nodes(x.mul(2).add(dx)).clamp(0, nodes(depthSize.x).sub(1))),
476
+ int(nodes(y.mul(2).add(dy)).clamp(0, nodes(depthSize.y).sub(1))),
477
+ ),
478
+ ),
479
+ float(sampleIndex),
480
+ ),
481
+ ),
482
+ ),
483
+ )
484
+ : chain.element(
485
+ float(below.offset)
486
+ .add(
487
+ nodes(y.mul(2).add(dy))
488
+ .clamp(0, below.height - 1)
489
+ .mul(below.width),
490
+ )
491
+ .add(nodes(x.mul(2).add(dx)).clamp(0, below.width - 1)),
492
+ );
493
+ far.assign(max(far, nodes(sample)));
494
+ }
495
+ }
496
+ chain
497
+ .element(
498
+ float(own.offset)
499
+ .add(nodes(y.mul(own.width)))
500
+ .add(x),
501
+ )
502
+ .assign(far);
503
+ })().compute(Math.max(1, own.width * own.height)),
504
+ );
505
+ built.name = `tnDepthPyramid${String(index)}`;
506
+ this.#kernels[index] = built;
507
+ return built;
508
+ }
509
+
510
+ /**
511
+ * The test, in the cull kernel's own language: the same four keeps and the same comparison, read
512
+ * off the same buffer {@link occludedBy} reads off its own arrays.
513
+ *
514
+ * `centre` is a TSL world position, `radius` its bounding-sphere radius, `viewProjection` the
515
+ * previous frame's `projection * viewInverse` as a `mat4` uniform and `cut` this frame's cut flag.
516
+ * Matrix row lengths recover projection scale without assuming an unrotated camera.
517
+ *
518
+ * The answer is a float, not a bool: `1` is hidden. A cull kernel runs the test once per part of a
519
+ * placement's level and branches on the answer each time, and a float is what a TSL variable holds
520
+ * across those branches without recomputing the test per part.
521
+ */
522
+ occluded(centre: Kernel, radius: Kernel, viewProjection: Kernel, cut: Kernel): Kernel {
523
+ const chain = this.chain;
524
+ const last = Math.max(0, this.levels - 1);
525
+ const clip = viewProjection.mul(vec4(centre, 1));
526
+ const w = clip.w;
527
+ const depth = max(w, float(1e-6));
528
+ const ndc = clip.xyz.div(depth);
529
+ const nearest = max(w.sub(radius), float(1e-6));
530
+ const scaleX = nodes(
531
+ vec3(viewProjection.element(0).x, viewProjection.element(1).x, viewProjection.element(2).x),
532
+ ).length();
533
+ const scaleY = nodes(
534
+ vec3(viewProjection.element(0).y, viewProjection.element(1).y, viewProjection.element(2).y),
535
+ ).length();
536
+ const halfX = nodes(scaleX.add(abs(ndc.x)))
537
+ .mul(radius)
538
+ .div(nearest)
539
+ .add(float(2).div(chain.element(0)));
540
+ const halfY = nodes(scaleY.add(abs(ndc.y)))
541
+ .mul(radius)
542
+ .div(nearest)
543
+ .add(float(2).div(chain.element(1)));
544
+ // The level a footprint this wide needs, and that level's own row of the table.
545
+ const level = nodes(
546
+ nodes(
547
+ ceil(log2(max(float(1), max(halfX.mul(chain.element(0)), halfY.mul(chain.element(1)))))),
548
+ ).clamp(0, last),
549
+ ).toVar();
550
+ const row = int(level.mul(TABLE_WORDS)).toVar();
551
+ const width = chain.element(row);
552
+ const height = chain.element(nodes(row).add(1));
553
+ const spanX = nodes(chain.element(0)).div(pow(float(2), level));
554
+ const spanY = nodes(chain.element(1)).div(pow(float(2), level));
555
+ const far = float(0).toVar();
556
+ for (const [dx, dy] of FOOTPRINT) {
557
+ // The footprint spans about one texel of this level, so the 2x2 block under its corner is the
558
+ // whole of it.
559
+ const x = nodes(ndc.x.mul(0.5).add(0.5).sub(halfX.div(2)).mul(spanX))
560
+ .floor()
561
+ .add(dx)
562
+ .clamp(0, nodes(width).sub(1));
563
+ const y = nodes(float(0.5).sub(ndc.y.mul(0.5)).sub(halfY.div(2)).mul(spanY))
564
+ .floor()
565
+ .add(dy)
566
+ .clamp(0, nodes(height).sub(1));
567
+ far.assign(
568
+ max(
569
+ far,
570
+ chain.element(
571
+ nodes(chain.element(nodes(row).add(2)))
572
+ .add(nodes(y).mul(width))
573
+ .add(x),
574
+ ),
575
+ ),
576
+ );
577
+ }
578
+ const keeps = w
579
+ .sub(radius)
580
+ .lessThanEqual(nodes(this.#nearFar).x)
581
+ .or(ndc.x.abs().add(halfX).greaterThan(1))
582
+ .or(ndc.y.abs().add(halfY).greaterThan(1))
583
+ .or(cut.greaterThan(0.5));
584
+ return keeps
585
+ .not()
586
+ .and(nodes(w.sub(radius)).greaterThan(far))
587
+ .select(float(1), float(0));
588
+ }
589
+
590
+ dispose(): void {
591
+ this.#disposed = true;
592
+ this.#kernels = [];
593
+ this.#levels = [];
594
+ this.#depth = undefined;
595
+ }
596
+ }