rhodonite 0.21.0 → 0.22.1

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 (43) hide show
  1. package/README.md +4 -4
  2. package/VERSION-FILE +1 -1
  3. package/dist/esm/foundation/components/Camera/CameraComponent.d.ts +15 -0
  4. package/dist/esm/foundation/components/Light/LightComponent.d.ts +116 -4
  5. package/dist/esm/foundation/components/SceneGraph/SceneGraphComponent.d.ts +2 -0
  6. package/dist/esm/foundation/core/Config.d.ts +199 -3
  7. package/dist/esm/foundation/helpers/Shadow/PointShadowMap.d.ts +3 -1
  8. package/dist/esm/foundation/helpers/Shadow/ShadowSystem.d.ts +13 -0
  9. package/dist/esm/foundation/math/Transform3D.d.ts +26 -2
  10. package/dist/esm/foundation/renderer/index.d.ts +1 -0
  11. package/dist/esm/foundation/renderer/lightCluster/LightClusterBuilder.d.ts +97 -0
  12. package/dist/esm/foundation/renderer/lightCluster/LightClusterLayout.d.ts +98 -0
  13. package/dist/esm/foundation/renderer/lightCluster/LightClusterSystem.d.ts +171 -0
  14. package/dist/esm/foundation/renderer/lightCluster/index.d.ts +1 -0
  15. package/dist/esm/foundation/system/Engine.d.ts +20 -2
  16. package/dist/esm/foundation/textures/TextureArray.d.ts +1 -1
  17. package/dist/esm/index.js +1216 -650
  18. package/dist/esm/webgl/WebGLStrategyWebGL2.d.ts +16 -0
  19. package/dist/esm/webgpu/WebGpuGpuTimer.d.ts +18 -7
  20. package/dist/esm/webgpu/WebGpuLightClusterBuilder.d.ts +37 -0
  21. package/dist/esm/webgpu/WebGpuResourceRepository.d.ts +28 -3
  22. package/dist/esm/webgpu/WebGpuStrategyBasic.d.ts +18 -1
  23. package/dist/esmdev/foundation/components/Camera/CameraComponent.d.ts +15 -0
  24. package/dist/esmdev/foundation/components/Light/LightComponent.d.ts +116 -4
  25. package/dist/esmdev/foundation/components/SceneGraph/SceneGraphComponent.d.ts +2 -0
  26. package/dist/esmdev/foundation/core/Config.d.ts +199 -3
  27. package/dist/esmdev/foundation/helpers/Shadow/PointShadowMap.d.ts +3 -1
  28. package/dist/esmdev/foundation/helpers/Shadow/ShadowSystem.d.ts +13 -0
  29. package/dist/esmdev/foundation/math/Transform3D.d.ts +26 -2
  30. package/dist/esmdev/foundation/renderer/index.d.ts +1 -0
  31. package/dist/esmdev/foundation/renderer/lightCluster/LightClusterBuilder.d.ts +97 -0
  32. package/dist/esmdev/foundation/renderer/lightCluster/LightClusterLayout.d.ts +98 -0
  33. package/dist/esmdev/foundation/renderer/lightCluster/LightClusterSystem.d.ts +171 -0
  34. package/dist/esmdev/foundation/renderer/lightCluster/index.d.ts +1 -0
  35. package/dist/esmdev/foundation/system/Engine.d.ts +20 -2
  36. package/dist/esmdev/foundation/textures/TextureArray.d.ts +1 -1
  37. package/dist/esmdev/index.js +2394 -214
  38. package/dist/esmdev/webgl/WebGLStrategyWebGL2.d.ts +16 -0
  39. package/dist/esmdev/webgpu/WebGpuGpuTimer.d.ts +18 -7
  40. package/dist/esmdev/webgpu/WebGpuLightClusterBuilder.d.ts +37 -0
  41. package/dist/esmdev/webgpu/WebGpuResourceRepository.d.ts +28 -3
  42. package/dist/esmdev/webgpu/WebGpuStrategyBasic.d.ts +18 -1
  43. package/package.json +1 -1
@@ -21,7 +21,23 @@ type ConfigInitDescription = {
21
21
  bufferSizeDivisionRatiosForGPUInstanceDataUsage?: number[];
22
22
  logLevel?: LogLevel;
23
23
  isMultiDrawEnabled?: boolean;
24
+ isDepthPrepassEnabled?: boolean;
25
+ isClusteredForwardEnabled?: boolean;
26
+ clusteredForwardBuildMode?: ClusteredForwardBuildMode;
27
+ clusteredForwardGridSize?: [number, number, number];
28
+ clusteredForwardMaxViewNumber?: number;
29
+ clusteredForwardLightCapacityPerCluster?: number;
30
+ clusteredForwardMinLocalLightNumber?: number;
31
+ maxLightListLength?: number;
32
+ lightAutoRangeThreshold?: number;
33
+ lightRangeScale?: number;
24
34
  };
35
+ /**
36
+ * Where the light clusters of Clustered Forward rendering are built.
37
+ * - `'auto'`: WebGPU builds them with compute shaders, WebGL2 builds them on the CPU.
38
+ * - `'cpu'`: Both backends build them on the CPU.
39
+ */
40
+ export type ClusteredForwardBuildMode = 'auto' | 'cpu';
25
41
  /**
26
42
  * Config is a configuration class that contains the configuration for the library.
27
43
  */
@@ -32,10 +48,166 @@ export declare class Config {
32
48
  skeletalComponentCountPerBufferView: number;
33
49
  /** The number of camera components per buffer view */
34
50
  cameraComponentCountPerBufferView: number;
35
- /** The number of light components per buffer view */
51
+ /**
52
+ * The number of light components per buffer view.
53
+ * Every new buffer view changes the generated shader getters and recompiles all shaders,
54
+ * so this is large enough for scenes with many lights.
55
+ */
36
56
  lightComponentCountPerBufferView: number;
37
- /** The maximum number of lights that Rhodonite can handle */
38
- maxLightNumber: number;
57
+ /**
58
+ * The maximum number of lights that can cast shadows at the same time.
59
+ * This is also the length of the per-light arrays of the MToon 0.x shader.
60
+ *
61
+ * @remarks
62
+ * 0 disables the per-light shadow map slots: the shaders compile out the shadow sampling and no shadow map
63
+ * textures are created. The shader arrays themselves cannot have a length of 0, so they use
64
+ * {@link Config.maxLightNumberOrOne} instead. Negative and NaN values are treated as 0.
65
+ */
66
+ private __maxLightNumber;
67
+ /** See {@link Config.maxLightNumber}. */
68
+ get maxLightNumber(): number;
69
+ /** See {@link Config.maxLightNumber}. */
70
+ set maxLightNumber(value: number);
71
+ /**
72
+ * The length-safe value of {@link Config.maxLightNumber}: `maxLightNumber`, or 1 when it is 0.
73
+ *
74
+ * @remarks
75
+ * Shader arrays, material parameters and texture arrays cannot have a length of 0. The shaders use this value
76
+ * for their per-light array sizes and loop bounds. Shadow processing itself is controlled by
77
+ * {@link Config.maxLightNumber}: when it is 0, the shadow code is compiled out and no shadow slots are assigned.
78
+ */
79
+ get maxLightNumberOrOne(): number;
80
+ /**
81
+ * Whether Clustered Forward rendering is enabled.
82
+ * When enabled, each fragment evaluates only the lights whose range reaches the cluster (froxel) of the fragment.
83
+ * Lights without a range limit and directional lights are always evaluated.
84
+ */
85
+ isClusteredForwardEnabled: boolean;
86
+ /** Where the light clusters are built. See {@link ClusteredForwardBuildMode}. */
87
+ clusteredForwardBuildMode: ClusteredForwardBuildMode;
88
+ /**
89
+ * The number of clusters along the screen X, screen Y and view depth axes.
90
+ *
91
+ * @remarks
92
+ * The default puts about a 40 pixel tile on a 1920x1080 canvas. The screen tiles should stay roughly 30-40 pixels
93
+ * at the rendered resolution: a coarser grid lets many lights share each cluster (the cost is paid by every
94
+ * fragment), and a finer grid increases the per-frame cluster build cost (the cost is paid once per frame, and the
95
+ * build is proportional to the cluster count in the current implementation).
96
+ */
97
+ clusteredForwardGridSize: [number, number, number];
98
+ /**
99
+ * The maximum number of cameras whose light clusters are built in one frame.
100
+ * The other cameras evaluate all lights.
101
+ */
102
+ clusteredForwardMaxViewNumber: number;
103
+ /**
104
+ * The light clusters are built only when the number of lights that can be culled (point and spot lights with a
105
+ * range, including an automatic range of {@link Config.lightAutoRangeThreshold}) and emit light (an intensity
106
+ * greater than 0) is at least this value. With fewer lights, every fragment evaluates all lights as in plain forward
107
+ * rendering, which skips the cluster build and the cluster lookup of the fragment shaders.
108
+ *
109
+ * @remarks
110
+ * The default value 1 is the measured break-even point of both backends: on Apple M2 Max (Chrome, ANGLE-Metal /
111
+ * Dawn-Metal) with a full-screen 2048x2048 PBR surface, the GPU frame time with and without clusters was
112
+ * (ratio = clustered / plain forward, lower is better; a range is the spread of several runs):
113
+ *
114
+ * | Lights | WebGL2 (radius 3 / 6) | WebGPU (radius 3 / 6) |
115
+ * |--------|------------------------|-----------------------|
116
+ * | 1 | 0.90-0.92 / 0.82-1.09 | 0.83 / 0.92 |
117
+ * | 2 | 0.64 / 0.76-0.84 | 0.61 / 0.76 |
118
+ * | 3 | 0.62 / 0.72 | 0.49 / 0.66 |
119
+ * | 8 | 0.42 / 0.62 | 0.32 / 0.51 |
120
+ *
121
+ * (A light with the radius 3 or 6 covers about 7% or 28% of the screen.) The cluster lookup costs about half a
122
+ * light in both backends. The Classic shader and a moving camera (clusters rebuilt every frame) gave the same
123
+ * break-even points. Lights that cover the whole screen can not be culled, so clustering them is always a few
124
+ * percent slower (WebGL2 2-3%, WebGPU 1-11%) whatever this value is. Raise this value for such scenes.
125
+ * Other GPUs may differ.
126
+ */
127
+ clusteredForwardMinLocalLightNumber: number;
128
+ /**
129
+ * The maximum number of lights in the list of each cluster.
130
+ *
131
+ * @remarks
132
+ * Every cluster keeps at most this many lights. When the number of local lights is greater than this value, the
133
+ * lights are sorted by their view depth and each cluster keeps the nearest ones, so the lights that are dropped
134
+ * are the farthest ones. The cost of a fragment is bounded by this value.
135
+ *
136
+ * Memory per camera: about `16 * clusterCount * ceil(value / 4)` bytes, where clusterCount is the product of
137
+ * {@link Config.clusteredForwardGridSize} (62,208 by default). The default 96 is about 25 MB per camera.
138
+ */
139
+ clusteredForwardLightCapacityPerCluster: number;
140
+ /** The maximum number of enabled lights that are shaded. The other lights are ignored. (max: 65535) */
141
+ maxLightListLength: number;
142
+ /**
143
+ * When greater than 0, point and spot lights without a range get an effective range where their intensity
144
+ * (the maximum of color * intensity, divided by the squared distance) falls to this value.
145
+ * This makes those lights fade out smoothly at that distance and lets Clustered Forward rendering cull them.
146
+ * 0 (default) disables it. Lights with a range and directional lights are not affected.
147
+ *
148
+ * @remarks
149
+ * The effective range is `R = sqrt(max(color) * intensity / lightAutoRangeThreshold)`. With the range window
150
+ * of the shaders (`(1 - (d / R)^4) / d^2`), the difference from the unlimited inverse-square falloff at the
151
+ * distance `d` is `lightAutoRangeThreshold * (d / R)^2`. So this value is the upper bound of the error added to
152
+ * the linear brightness (for the diffuse lighting of a white surface facing the light). The error is largest at
153
+ * the border of the range and smaller inside it.
154
+ *
155
+ * Reference values (without tone mapping, exposure 1):
156
+ *
157
+ * | Value | Range (intensity 1 / 10) | Effect on the image |
158
+ * |--------|--------------------------|---------------------|
159
+ * | 0.0003 | 58 / 183 | Practically lossless, but the range is so large that the lights are rarely culled. |
160
+ * | 0.001 | 32 / 100 | At most about 3/255 even on a black background. Not noticeable on lit surfaces. Recommended starting point. |
161
+ * | 0.003 | 18 / 58 | Hardly noticeable in scenes with ambient light or IBL. |
162
+ * | 0.01 | 10 / 32 | On a dark background, the tail of the light fades out a little early. About 3/255 on lit surfaces. |
163
+ *
164
+ * Tips:
165
+ * - Compare the resulting range with the visible area and the spacing of the lights. A range larger than them
166
+ * puts the light in almost every cluster, so it does not make rendering faster.
167
+ * - Scale the value with the brightness level of the scene. For example, when the light intensities are in the
168
+ * hundreds and the exposure brings them down, scale the value by the same factor. About 1/300 to 1/1000 of the
169
+ * typical brightness of the scene is a good guide.
170
+ * - Use a smaller value for dark scenes or when the exposure brightens dark areas, where the cut-off tail is
171
+ * more noticeable.
172
+ * - The error of specular highlights on glossy surfaces can be larger than the table above, but the light is
173
+ * weak near the border of the range, so it is rarely noticeable.
174
+ * - Set this when initializing the engine. A change at runtime takes effect for each light when the light is
175
+ * updated next.
176
+ */
177
+ lightAutoRangeThreshold: number;
178
+ /**
179
+ * Scales the effective range of the point and spot lights, and raises their intensity to compensate.
180
+ * A shorter range reaches fewer clusters, so fewer fragments evaluate the light in Clustered Forward rendering.
181
+ *
182
+ * @remarks
183
+ * `1` (default) applies no adjustment. The measured presets are:
184
+ *
185
+ * | lightRangeScale | Intensity | GPU frame time (measured) |
186
+ * |-----------------|-----------|----------------------------|
187
+ * | 1 | x1 | 5.5-6.4 ms |
188
+ * | 0.9 | x1.16 | 4.2-4.5 ms (-20 to -24%) |
189
+ * | 0.8 | x1.35 | 3.1-3.2 ms (-43 to -50%) |
190
+ *
191
+ * The measurement is a Sponza scene with 1000 animated point lights (WebGPU, 1920x1080, clustered forward).
192
+ * Intermediate values interpolate the measured intensity factors: `1 -> 1`, `0.9 -> 1.16`, `0.8 -> 1.35`,
193
+ * and below 0.8 the last slope continues. A constant factor cannot compensate the range window exactly: with
194
+ * a shorter range the falloff `(1 - (d / range)^4)^4 / d^2` is slightly dimmer at mid distances, and the lights
195
+ * fade out closer to their centers. 0.9 changes only 0.1% of the pixels by more than 32/255; 0.8 changes about
196
+ * 7% of the pixels that much (the lit area of each light becomes smaller).
197
+ *
198
+ * The engine does not change this value by itself. An application that targets a frame budget can adjust it
199
+ * at runtime (for example, from the measured GPU time and the display refresh interval).
200
+ *
201
+ * Only point and spot lights with a positive effective range are adjusted. Directional lights and lights without
202
+ * a range limit are unchanged. The values of `LightComponent.range` and `LightComponent.intensity` themselves are
203
+ * not modified: only the values uploaded to the GPU (and read by the light clusters and the shaders) are scaled,
204
+ * so all rendering paths see the same light.
205
+ */
206
+ private __lightRangeScale;
207
+ /** See {@link Config.lightRangeScale}. */
208
+ get lightRangeScale(): number;
209
+ /** See {@link Config.lightRangeScale}. */
210
+ set lightRangeScale(value: number);
39
211
  /**
40
212
  * Number of instances of each material type to be placed consecutively in memory.
41
213
  * This is on the memory layout, and the number of material instances that can be generated is not limited by this setting.
@@ -73,6 +245,30 @@ export declare class Config {
73
245
  * vertex/index buffers and consecutive draws with the same state are issued with WEBGL_multi_draw.
74
246
  */
75
247
  isMultiDrawEnabled: boolean;
248
+ /**
249
+ * Whether to render a depth prepass for the opaque primitives of the main render passes (WebGPU only).
250
+ *
251
+ * @remarks
252
+ * The prepass draws the opaque primitives with a depth-only pipeline before the color pass, and the color pass
253
+ * tests the depth with `less-equal`. Hidden fragments are rejected before the fragment shader, so the cost of the
254
+ * prepass (vertex processing and a trivial fragment shader) is traded for the shading of the overdrawn fragments.
255
+ *
256
+ * Primitives that alpha test (Mask), alpha-to-coverage, discard for wireframe, or blend are not part of the prepass:
257
+ * they keep their normal draw, depth test and depth write. A material that discards in another way should not be
258
+ * used with this option. At exactly coplanar surfaces the visible surface can change, because the color pass passes
259
+ * fragments whose depth is equal to the prepass depth (a few hundred pixels on a Sponza-scale scene).
260
+ *
261
+ * Render passes with a material override (shadow maps, post effects and other helper passes) are not affected.
262
+ * The prepass is per render pass, so stereo rendering runs it once per eye. The WebGL2 backend ignores this option
263
+ * (its multi-draw path keeps the material order).
264
+ *
265
+ * @remarks
266
+ * Measured on the 1000-point-light Sponza (WebGPU, Apple M2 Max): the GPU time fell by about 5-7% (1280x720:
267
+ * 4.46 -> 4.13 ms) and the frame wall time by about 0-10% (the run was thermally throttled, so treat the wall
268
+ * number as an upper bound). The gain grows with the amount of overdrawn shading. The default is off because the
269
+ * extra geometry pass hurts scenes with little overdraw or heavy vertex shaders.
270
+ */
271
+ isDepthPrepassEnabled: boolean;
76
272
  constructor(initDescription?: ConfigInitDescription);
77
273
  }
78
274
  export {};
@@ -26,9 +26,11 @@ export declare class PointShadowMap {
26
26
  *
27
27
  * @param entities - Array of scene graph entities to be rendered for shadow map generation
28
28
  * @param lightEntity - The point light entity that casts shadows
29
+ * @param shadowSlot - The shadow slot of the light (below `Config.maxLightNumber`). Defaults to the shadow slot
30
+ * of the light component.
29
31
  * @returns An array containing two render passes: [frontRenderPass, backRenderPass]
30
32
  */
31
- getRenderPasses(entities: ISceneGraphEntity[], lightEntity: ISceneGraphEntity & ILightEntityMethods): RenderPass[];
33
+ getRenderPasses(entities: ISceneGraphEntity[], lightEntity: ISceneGraphEntity & ILightEntityMethods, shadowSlot?: number): RenderPass[];
32
34
  /**
33
35
  * Gets the framebuffer used for storing shadow moment data.
34
36
  * This framebuffer contains the encoded depth moments for variance shadow mapping.
@@ -15,6 +15,8 @@ export declare class ShadowSystem {
15
15
  private __lightTypes;
16
16
  private __lightEnables;
17
17
  private __lightCastShadows;
18
+ private __lightSids;
19
+ private __isShadowSlotShortageWarned;
18
20
  /** Reused by setDepthBiasPV() on every frame. */
19
21
  private __depthBiasPVArray?;
20
22
  private __depthBiasPV?;
@@ -42,6 +44,17 @@ export declare class ShadowSystem {
42
44
  * @returns Array of Expression objects containing the shadow mapping render passes
43
45
  */
44
46
  getExpressions(entities: ISceneGraphEntity[]): Expression[];
47
+ /**
48
+ * Assigns the shadow slots (the indices of the per-material shadow arrays) to the lights.
49
+ *
50
+ * A shadow casting light keeps the slot equal to its component SID when the SID is below
51
+ * `Config.maxLightNumber` (the convention of manual shadow map setups), and the other shadow casting lights
52
+ * use the free slots. Lights that do not cast shadows get no slot.
53
+ *
54
+ * @param lightComponents - The live light components
55
+ * @param hasShadowCasters - Whether any entity is rendered to the shadow maps
56
+ */
57
+ private __assignShadowSlots;
45
58
  /**
46
59
  * Sets the blurred shadow map texture for directional and spot lights on all entity materials.
47
60
  * Creates a linear sampler and assigns the shadow map texture to the 'depthTexture' parameter.
@@ -26,6 +26,13 @@ export declare class Transform3D {
26
26
  private __scale;
27
27
  private __rotation;
28
28
  private __updateCount;
29
+ /** The local matrix composed from the current position, rotation and scale. */
30
+ private __matrix;
31
+ private __isMatrixUpToDate;
32
+ /** The position, rotation and scale the cached matrix was composed from (to detect direct inner mutations). */
33
+ private __matrixPosition;
34
+ private __matrixRotation;
35
+ private __matrixScale;
29
36
  private static __tmpMatrix44_0;
30
37
  private static __tmpVector3_0;
31
38
  private static __tmpVector3_1;
@@ -126,9 +133,15 @@ export declare class Transform3D {
126
133
  get rotationInner(): Quaternion;
127
134
  /**
128
135
  * Internal method to increment the update counter when transform changes.
136
+ *
137
+ * A position-only change updates the translation column of the cached matrix instead of invalidating it.
138
+ * Animations that move nodes (the common case with many lights) then avoid the quaternion-to-matrix
139
+ * composition every frame. A rotation or scale change invalidates the matrix.
140
+ *
141
+ * @param change - What changed: `'position'` or everything (`'all'`).
129
142
  * @private
130
143
  */
131
- __updateTransform(): void;
144
+ __updateTransform(change?: 'all' | 'position'): void;
132
145
  /**
133
146
  * Sets the transform from a 4x4 transformation matrix.
134
147
  * Decomposes the matrix into position, rotation, and scale components.
@@ -146,9 +159,20 @@ export declare class Transform3D {
146
159
  * @returns A MutableMatrix44 representing the composed transformation
147
160
  */
148
161
  get matrixInner(): MutableMatrix44;
162
+ /**
163
+ * Composes the local matrix from the current position, rotation and scale and stores it in the cache.
164
+ */
165
+ private __composeMatrix;
166
+ /**
167
+ * Brings the cached matrix up to date. Direct mutations of the inner vectors (positionInner and the like)
168
+ * bypass the setters, so they are detected here: a position-only change updates the translation column, and
169
+ * a rotation or scale change recomposes the matrix.
170
+ */
171
+ private __ensureMatrixUpToDate;
149
172
  /**
150
173
  * Efficiently computes the transformation matrix and stores it in the provided matrix.
151
- * This method avoids memory allocation by reusing an existing matrix object.
174
+ * The composed matrix is cached, so repeated reads (including animated translations) do not
175
+ * recompose the rotation and scale.
152
176
  * @param mat - The target matrix to store the result in
153
177
  */
154
178
  getMatrixInnerTo(mat: MutableMatrix44): void;
@@ -2,6 +2,7 @@ export * from './CGAPIResourceRepository';
2
2
  export * from './Expression';
3
3
  export * from './Frame';
4
4
  export * from './FrameBuffer';
5
+ export * from './lightCluster';
5
6
  export * from './pipelines';
6
7
  export * from './RenderingCommonMethods';
7
8
  export * from './RenderPass';
@@ -0,0 +1,97 @@
1
+ import { type LightClusterViewLayout } from './LightClusterLayout';
2
+ /**
3
+ * Pure functions that build the Clustered Forward light clusters of a view on the CPU.
4
+ * The memory layout is described in LightClusterLayout.ts.
5
+ *
6
+ * A light is assigned to a cluster `(x, y, z)` when its bounding sphere `(c, r)` passes all of these tests
7
+ * (the WebGPU compute shader in WebGpuLightClusterBuilder.ts implements the same tests):
8
+ * - The sphere is not entirely behind the eye plane: `dot(rowW, c) / |rowW.xyz| > -r` (skipped when rowW.xyz is 0).
9
+ * - Column: `x == 0 || dist(rowX - x * rowW, c) >= -r` and `x == gridX - 1 || dist((x + 1) * rowW - rowX, c) >= -r`.
10
+ * - Row: the same with rowY and y.
11
+ * - Slice: `z == 0 || d + r >= zs(z)` and `z == gridZ - 1 || d - r <= zs(z + 1)`,
12
+ * where `d = dot(rowDepth, c)` and `zs(k) = exp((k - sliceBias) / sliceScale)`.
13
+ *
14
+ * `dist(plane, c)` is the signed distance `(dot(plane.xyz, c) + plane.w) / |plane.xyz|`.
15
+ * The clusters at the borders of the grid extend to infinity, so a fragment whose cluster coordinates are clamped
16
+ * is still inside its cluster.
17
+ */
18
+ /**
19
+ * The result of a light cluster build.
20
+ * - `'built'`: every light was stored.
21
+ * - `'truncated'`: some clusters had more lights than `clusterLightCapacity` and kept only their nearest lights.
22
+ */
23
+ export type LightClusterBuildResult = 'built' | 'truncated';
24
+ /** Scratch memory reused between builds. */
25
+ export type LightClusterBuildScratch = {
26
+ /** The number of vec4 of the light index list used by the last build. */
27
+ usedIndexVec4Count: number;
28
+ counts: Uint32Array;
29
+ offsets: Uint32Array;
30
+ sliceBoundaries: Float64Array;
31
+ /** The normalized tile planes `rowX - k * rowW` (k = 0..gridX), (nx, ny, nz, w) each. Degenerate planes are 0. */
32
+ planesX: Float64Array;
33
+ /** The normalized tile planes `rowY - k * rowW` (k = 0..gridY). */
34
+ planesY: Float64Array;
35
+ /**
36
+ * The columns, rows and slices each light passes (gridX + gridY + gridZ flags per light), evaluated once and
37
+ * reused by the count and fill passes. Grown on demand.
38
+ */
39
+ axisPass: Uint8Array;
40
+ /** Whether each light touches any cluster. Grown on demand. */
41
+ isLightInView: Uint8Array;
42
+ /** The first and last passing column, row and slice of each light (6 per light). Grown on demand. */
43
+ axisRanges: Int32Array;
44
+ };
45
+ /**
46
+ * Creates the scratch memory for a layout.
47
+ */
48
+ export declare function createLightClusterBuildScratch(layout: LightClusterViewLayout): LightClusterBuildScratch;
49
+ /**
50
+ * Writes the header of a view region: the clip rows, the depth row, the grid size and the depth slices.
51
+ *
52
+ * The depth range of the slices is the intersection of the depth range of the light spheres and the visible depth
53
+ * range of the camera: the slices are not wasted on depths where no light reaches, nor in front of the camera near
54
+ * plane or beyond the far plane.
55
+ *
56
+ * @param dst - The memory of the view region
57
+ * @param viewOffset - The float offset of the view region in `dst`
58
+ * @param viewMatrix - The view matrix (column-major, as uploaded to the GPU)
59
+ * @param projectionMatrix - The projection matrix (column-major, as uploaded to the GPU)
60
+ * @param spheres - The light spheres in world space (cx, cy, cz, r) * localCount
61
+ * @param localCount - The number of light spheres
62
+ * @param layout - The layout of the view region
63
+ * @param visibleNearDepth - The view depth of the camera near plane (0 disables the clamp)
64
+ * @param visibleFarDepth - The view depth of the camera far plane (Infinity disables the clamp)
65
+ */
66
+ export declare function writeLightClusterViewHeader(dst: Float32Array, viewOffset: number, viewMatrix: ArrayLike<number>, projectionMatrix: ArrayLike<number>, spheres: ArrayLike<number>, localCount: number, layout: LightClusterViewLayout, visibleNearDepth?: number, visibleFarDepth?: number): void;
67
+ /**
68
+ * Builds the cluster table and the light index list of a view whose header has been written.
69
+ *
70
+ * The lights of each cluster are stored in the order of `localEntries`. The caller passes the lights sorted by their
71
+ * view depth (nearest first) when the number of local lights exceeds the capacity, so that a cluster which is full
72
+ * keeps its nearest lights. Every cluster keeps at most `layout.clusterLightCapacity` lights, so the list cannot
73
+ * overflow.
74
+ */
75
+ export declare function buildLightClustersOnCpu(dst: Float32Array, viewOffset: number, layout: LightClusterViewLayout, spheres: ArrayLike<number>, localEntries: ArrayLike<number>, localCount: number, scratch: LightClusterBuildScratch): LightClusterBuildResult;
76
+ /**
77
+ * The cluster-centric form of the assignment test (the form the WebGPU compute shader uses).
78
+ * It must agree with the light-centric build of `buildLightClustersOnCpu`.
79
+ */
80
+ export declare function sphereIntersectsLightCluster(dst: Float32Array, viewOffset: number, layout: LightClusterViewLayout, x: number, y: number, z: number, cx: number, cy: number, cz: number, r: number): boolean;
81
+ /**
82
+ * The reference implementation of the cluster lookup of the shaders (`getLightList`).
83
+ *
84
+ * @returns The cluster index, or -1 when the position uses the all-light list (behind the eye plane or overflow).
85
+ */
86
+ export declare function computeLightClusterIndex(dst: Float32Array, viewOffset: number, px: number, py: number, pz: number): number;
87
+ /**
88
+ * Reads the light entries of a cluster built by `buildLightClustersOnCpu` (or by the compute shader).
89
+ */
90
+ export declare function readLightClusterEntries(dst: Float32Array, viewOffset: number, layout: LightClusterViewLayout, clusterIndex: number): number[];
91
+ /**
92
+ * Computes the bounding sphere of a light from the values uploaded to the GPU.
93
+ * Returns the radius, or -1 when the light can not be culled (directional lights and lights without range).
94
+ *
95
+ * @param out - Receives (cx, cy, cz, r) at `outOffset`
96
+ */
97
+ export declare function computeLightBoundingSphere(typeValue: number, position: ArrayLike<number>, direction: ArrayLike<number>, range: number, outerConeCos: number, out: Float64Array, outOffset: number): number;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Memory layout of the Clustered Forward light data.
3
+ *
4
+ * All values are stored as 32-bit floats in the GPU instance data (the data texture in WebGL2,
5
+ * the storage buffer in WebGPU) and read with `fetchElement(vec4Index)` / `get_clusteredLightData(0u, idx)`.
6
+ * Integers are below 2^24 and are therefore represented exactly.
7
+ *
8
+ * ## Global property `clusteredLightData` (always present)
9
+ * ```
10
+ * [0] (allCount, globalCount, localCount, sphereBase)
11
+ * [1..] allList: light entries, 4 entries per vec4.
12
+ * The lights that can not be culled (directional lights, lights without range) come first,
13
+ * then the local lights. Both groups are sorted by the light component SID.
14
+ * ```
15
+ * `sphereBase` is -1 (the GPU cluster build receives its own sorted light input in a separate storage buffer).
16
+ *
17
+ * ## Light entry
18
+ * `entry = lightComponentSID + 65536 * (shadowSlot + 1)` (`shadowSlot` is -1 when the light has no shadow slot).
19
+ *
20
+ * ## View region (one per camera, allocated on demand, referenced by `CameraComponent.lightClusterViewInfo.x`)
21
+ * ```
22
+ * [0] rowX 0.5 * gridX * (clipRow0 + clipRow3): tileX = floor(dot(rowX, p) / dot(rowW, p))
23
+ * [1] rowY 0.5 * gridY * (clipRow1 + clipRow3)
24
+ * [2] rowW clipRow3
25
+ * [3] rowDepth normalized view depth row: depth = dot(rowDepth, p) (positive in front of the camera)
26
+ * [4] (gridX, gridY, gridZ, state) state: 0 (valid; reserved)
27
+ * [5] (sliceScale, sliceBias, zNear, zFar) slice = floor(log(depth) * sliceScale + sliceBias)
28
+ * [6..] cluster table: one vec4 per cluster, (offset, count, 0, 0).
29
+ * offset is the vec4 index of the list of the cluster from the index list start.
30
+ * [6 + clusterCount..] index list: 4 entries per vec4.
31
+ * The CPU build packs the lists densely (offset is the exclusive prefix sum of the cluster counts); the WebGPU
32
+ * build gives every cluster its own `ceil(clusterLightCapacity / 4)` vec4s (offset = cluster * that). The rest
33
+ * of the last vec4 of a list is zero.
34
+ * ```
35
+ * The cluster index is `(z * gridY + y) * gridX + x`. The clusters at the borders of the grid extend to infinity,
36
+ * so clamping the cluster coordinates of a fragment is always correct.
37
+ *
38
+ * Every cluster owns whole vec4s of the table and of the index list, so the compute shaders never write to a vec4
39
+ * that another invocation writes (some backends store a vector component by rewriting the whole vector).
40
+ */
41
+ export declare const LightClusterLayout: {
42
+ /** The radix used to pack the shadow slot into a light entry. */
43
+ readonly entryRadix: 65536;
44
+ /** The maximum number of lights in the light list (light component SIDs must be below the radix). */
45
+ readonly maxLightListLength: 65535;
46
+ /** The number of vec4 of the header of the global property. */
47
+ readonly globalHeaderVec4Count: 1;
48
+ /** The number of vec4 of the header of a view region. */
49
+ readonly viewHeaderVec4Count: 6;
50
+ /** The vec4 offset of the grid info (gridX, gridY, gridZ, state) in a view region. */
51
+ readonly viewGridOffset: 4;
52
+ /** The vec4 offset of the slice info (sliceScale, sliceBias, zNear, zFar) in a view region. */
53
+ readonly viewSliceOffset: 5;
54
+ };
55
+ /**
56
+ * Clamps the length of the light list to the supported range.
57
+ */
58
+ export declare function getLightListCapacity(maxLightListLength: number): number;
59
+ /**
60
+ * Returns the array length (in vec4) of the `clusteredLightData` global property.
61
+ */
62
+ export declare function getLightClusterGlobalPropertyLength(maxLightListLength: number): number;
63
+ /**
64
+ * Packs a light component SID and a shadow slot into a light entry.
65
+ */
66
+ export declare function packLightEntry(lightComponentSid: number, shadowSlot: number): number;
67
+ /**
68
+ * Unpacks a light entry into the light component SID and the shadow slot (-1 = no shadow slot).
69
+ */
70
+ export declare function unpackLightEntry(entry: number): [number, number];
71
+ /**
72
+ * The sizes of a view region (in vec4).
73
+ */
74
+ export type LightClusterViewLayout = {
75
+ gridX: number;
76
+ gridY: number;
77
+ gridZ: number;
78
+ clusterCount: number;
79
+ tableVec4Count: number;
80
+ indexCapacity: number;
81
+ indexVec4Count: number;
82
+ /** The maximum number of lights stored in one cluster. */
83
+ clusterLightCapacity: number;
84
+ viewVec4Count: number;
85
+ };
86
+ /**
87
+ * Computes the sizes of a view region from the grid size and the number of lights per cluster the light index list
88
+ * is sized for. The list is shared by the clusters, and each cluster pads its list to a multiple of 4 entries, so
89
+ * the list never overflows while no cluster has more lights than `lightCapacityPerCluster`.
90
+ */
91
+ export declare function getLightClusterViewLayout(gridSize: readonly [number, number, number], lightCapacityPerCluster: number): LightClusterViewLayout;
92
+ /**
93
+ * Splits the byte range `[start, end)` into the parts outside the excluded ranges.
94
+ *
95
+ * @param excluded - Ranges `[start, end)` sorted by their start
96
+ * @returns The remaining ranges `[start, end)` in ascending order
97
+ */
98
+ export declare function subtractByteRanges(start: number, end: number, excluded: readonly [number, number][]): [number, number][];