@luma.gl/engine 10.0.0-alpha.10 → 10.0.0-alpha.11

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 (208) hide show
  1. package/dist/animation/node-animation-binding.cjs +10 -0
  2. package/dist/animation/node-animation-binding.d.ts +1 -1
  3. package/dist/animation/node-animation-binding.d.ts.map +1 -1
  4. package/dist/animation/node-animation-binding.js +10 -0
  5. package/dist/animation/node-animation-binding.js.map +1 -1
  6. package/dist/dist.dev.js +325 -80
  7. package/dist/dist.min.js +58 -58
  8. package/dist/gltf/gltf/animations/animations.d.ts +1 -1
  9. package/dist/gltf/gltf/animations/animations.d.ts.map +1 -1
  10. package/dist/gltf/gltf/create-scenegraph-from-gltf.cjs +80 -12
  11. package/dist/gltf/gltf/create-scenegraph-from-gltf.d.ts +8 -1
  12. package/dist/gltf/gltf/create-scenegraph-from-gltf.d.ts.map +1 -1
  13. package/dist/gltf/gltf/create-scenegraph-from-gltf.js +82 -14
  14. package/dist/gltf/gltf/create-scenegraph-from-gltf.js.map +1 -1
  15. package/dist/gltf/gltf/gltf-billboard.cjs +6 -1
  16. package/dist/gltf/gltf/gltf-billboard.d.ts.map +1 -1
  17. package/dist/gltf/gltf/gltf-billboard.js +6 -1
  18. package/dist/gltf/gltf/gltf-billboard.js.map +1 -1
  19. package/dist/gltf/gltf/gltf-extension-support.cjs +2 -2
  20. package/dist/gltf/gltf/gltf-extension-support.js +2 -2
  21. package/dist/gltf/gltf/gltf-extension-support.js.map +1 -1
  22. package/dist/gltf/index.cjs +2 -0
  23. package/dist/gltf/index.cjs.map +3 -3
  24. package/dist/gltf/index.d.ts +1 -1
  25. package/dist/gltf/index.d.ts.map +1 -1
  26. package/dist/gltf/index.js +1 -1
  27. package/dist/gltf/index.js.map +1 -1
  28. package/dist/gltf/parsers/parse-gltf-animations.cjs +8 -5
  29. package/dist/gltf/parsers/parse-gltf-animations.js +20 -5
  30. package/dist/gltf/parsers/parse-gltf-animations.js.map +1 -1
  31. package/dist/gltf/parsers/parse-gltf-lights.cjs +36 -72
  32. package/dist/gltf/parsers/parse-gltf-lights.d.ts +6 -2
  33. package/dist/gltf/parsers/parse-gltf-lights.d.ts.map +1 -1
  34. package/dist/gltf/parsers/parse-gltf-lights.js +34 -91
  35. package/dist/gltf/parsers/parse-gltf-lights.js.map +1 -1
  36. package/dist/gltf/parsers/parse-gltf-metadata.cjs +60 -0
  37. package/dist/gltf/parsers/parse-gltf-metadata.d.ts +5 -0
  38. package/dist/gltf/parsers/parse-gltf-metadata.d.ts.map +1 -0
  39. package/dist/gltf/parsers/parse-gltf-metadata.js +39 -0
  40. package/dist/gltf/parsers/parse-gltf-metadata.js.map +1 -0
  41. package/dist/gltf/parsers/parse-gltf.cjs +4 -1
  42. package/dist/gltf/parsers/parse-gltf.d.ts +4 -0
  43. package/dist/gltf/parsers/parse-gltf.d.ts.map +1 -1
  44. package/dist/gltf/parsers/parse-gltf.js +3 -0
  45. package/dist/gltf/parsers/parse-gltf.js.map +1 -1
  46. package/dist/gltf/pbr/pbr-environment.cjs +21 -3
  47. package/dist/gltf/pbr/pbr-environment.d.ts +3 -0
  48. package/dist/gltf/pbr/pbr-environment.d.ts.map +1 -1
  49. package/dist/gltf/pbr/pbr-environment.js +19 -1
  50. package/dist/gltf/pbr/pbr-environment.js.map +1 -1
  51. package/dist/graph/models/index.cjs.map +1 -1
  52. package/dist/graph/models/path/path-attribute-model.cjs +1 -1
  53. package/dist/graph/models/path/path-attribute-model.js +1 -1
  54. package/dist/graph/models/path/path-attribute-model.js.map +1 -1
  55. package/dist/graph/models/path/path-storage-model.cjs +1 -1
  56. package/dist/graph/models/path/path-storage-model.js +1 -1
  57. package/dist/graph/models/path/path-storage-model.js.map +1 -1
  58. package/dist/graph/physics/index.cjs.map +1 -1
  59. package/dist/graph/tables/index.cjs.map +1 -1
  60. package/dist/index.cjs +13 -0
  61. package/dist/index.cjs.map +3 -3
  62. package/dist/index.d.ts +4 -0
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +3 -0
  65. package/dist/index.js.map +1 -1
  66. package/dist/lighting/ambient-occlusion-pass.cjs +126 -0
  67. package/dist/lighting/ambient-occlusion-pass.d.ts +31 -0
  68. package/dist/lighting/ambient-occlusion-pass.d.ts.map +1 -0
  69. package/dist/lighting/ambient-occlusion-pass.js +108 -0
  70. package/dist/lighting/ambient-occlusion-pass.js.map +1 -0
  71. package/dist/lighting/clustered-light-grid.cjs +378 -0
  72. package/dist/lighting/clustered-light-grid.d.ts +94 -0
  73. package/dist/lighting/clustered-light-grid.d.ts.map +1 -0
  74. package/dist/lighting/clustered-light-grid.js +370 -0
  75. package/dist/lighting/clustered-light-grid.js.map +1 -0
  76. package/dist/lighting/contact-shadow-composite.cjs +80 -0
  77. package/dist/lighting/contact-shadow-composite.d.ts +6 -0
  78. package/dist/lighting/contact-shadow-composite.d.ts.map +1 -0
  79. package/dist/lighting/contact-shadow-composite.js +59 -0
  80. package/dist/lighting/contact-shadow-composite.js.map +1 -0
  81. package/dist/lighting/contact-shadow-pass.cjs +102 -0
  82. package/dist/lighting/contact-shadow-pass.d.ts +23 -0
  83. package/dist/lighting/contact-shadow-pass.d.ts.map +1 -0
  84. package/dist/lighting/contact-shadow-pass.js +85 -0
  85. package/dist/lighting/contact-shadow-pass.js.map +1 -0
  86. package/dist/lighting/index.cjs +98 -0
  87. package/dist/lighting/index.cjs.map +6 -0
  88. package/dist/lighting/index.d.ts +23 -0
  89. package/dist/lighting/index.d.ts.map +1 -0
  90. package/dist/lighting/index.js +16 -0
  91. package/dist/lighting/index.js.map +1 -0
  92. package/dist/lighting/pbr-environment.cjs +45 -0
  93. package/dist/lighting/pbr-environment.d.ts +25 -0
  94. package/dist/lighting/pbr-environment.d.ts.map +1 -0
  95. package/dist/lighting/pbr-environment.js +30 -0
  96. package/dist/lighting/pbr-environment.js.map +1 -0
  97. package/dist/lighting/pbr-material.cjs +75 -0
  98. package/dist/lighting/pbr-material.d.ts +33 -0
  99. package/dist/lighting/pbr-material.d.ts.map +1 -0
  100. package/dist/lighting/pbr-material.js +52 -0
  101. package/dist/lighting/pbr-material.js.map +1 -0
  102. package/dist/lighting/pbr-model.cjs +509 -0
  103. package/dist/lighting/pbr-model.d.ts +41 -0
  104. package/dist/lighting/pbr-model.d.ts.map +1 -0
  105. package/dist/lighting/pbr-model.js +475 -0
  106. package/dist/lighting/pbr-model.js.map +1 -0
  107. package/dist/lighting/pbr-surface-pass.cjs +116 -0
  108. package/dist/lighting/pbr-surface-pass.d.ts +35 -0
  109. package/dist/lighting/pbr-surface-pass.d.ts.map +1 -0
  110. package/dist/lighting/pbr-surface-pass.js +98 -0
  111. package/dist/lighting/pbr-surface-pass.js.map +1 -0
  112. package/dist/lighting/prefiltered-environment.cjs +275 -0
  113. package/dist/lighting/prefiltered-environment.d.ts +56 -0
  114. package/dist/lighting/prefiltered-environment.d.ts.map +1 -0
  115. package/dist/lighting/prefiltered-environment.js +264 -0
  116. package/dist/lighting/prefiltered-environment.js.map +1 -0
  117. package/dist/lighting/shadow-map-renderer.cjs +627 -0
  118. package/dist/lighting/shadow-map-renderer.d.ts +92 -0
  119. package/dist/lighting/shadow-map-renderer.d.ts.map +1 -0
  120. package/dist/lighting/shadow-map-renderer.js +617 -0
  121. package/dist/lighting/shadow-map-renderer.js.map +1 -0
  122. package/dist/lighting/shadow-quality.cjs +58 -0
  123. package/dist/lighting/shadow-quality.d.ts +13 -0
  124. package/dist/lighting/shadow-quality.d.ts.map +1 -0
  125. package/dist/lighting/shadow-quality.js +37 -0
  126. package/dist/lighting/shadow-quality.js.map +1 -0
  127. package/dist/material/material.cjs +3 -0
  128. package/dist/material/material.d.ts +2 -0
  129. package/dist/material/material.d.ts.map +1 -1
  130. package/dist/material/material.js +3 -0
  131. package/dist/material/material.js.map +1 -1
  132. package/dist/model/gpu-vector-model.cjs +11 -1
  133. package/dist/model/gpu-vector-model.d.ts +4 -2
  134. package/dist/model/gpu-vector-model.d.ts.map +1 -1
  135. package/dist/model/gpu-vector-model.js +12 -1
  136. package/dist/model/gpu-vector-model.js.map +1 -1
  137. package/dist/scenegraph/controllers/punctual-light-controller.cjs +121 -0
  138. package/dist/scenegraph/controllers/punctual-light-controller.d.ts +31 -0
  139. package/dist/scenegraph/controllers/punctual-light-controller.d.ts.map +1 -0
  140. package/dist/scenegraph/controllers/punctual-light-controller.js +117 -0
  141. package/dist/scenegraph/controllers/punctual-light-controller.js.map +1 -0
  142. package/dist/scenegraph/scene-metadata.cjs +43 -0
  143. package/dist/scenegraph/scene-metadata.d.ts +9 -0
  144. package/dist/scenegraph/scene-metadata.d.ts.map +1 -0
  145. package/dist/scenegraph/scene-metadata.js +21 -0
  146. package/dist/scenegraph/scene-metadata.js.map +1 -0
  147. package/dist/scenegraph/scenegraph-interaction.cjs +99 -0
  148. package/dist/scenegraph/scenegraph-interaction.d.ts +47 -0
  149. package/dist/scenegraph/scenegraph-interaction.d.ts.map +1 -0
  150. package/dist/scenegraph/scenegraph-interaction.js +79 -0
  151. package/dist/scenegraph/scenegraph-interaction.js.map +1 -0
  152. package/dist/scenegraph/scenegraph-node.cjs +10 -0
  153. package/dist/scenegraph/scenegraph-node.d.ts +10 -0
  154. package/dist/scenegraph/scenegraph-node.d.ts.map +1 -1
  155. package/dist/scenegraph/scenegraph-node.js +10 -0
  156. package/dist/scenegraph/scenegraph-node.js.map +1 -1
  157. package/dist/text/experimental.cjs.map +1 -1
  158. package/dist/text/fonts/atlas/text-utils.cjs +1 -1
  159. package/dist/text/fonts/atlas/text-utils.js +1 -1
  160. package/dist/text/fonts/atlas/text-utils.js.map +1 -1
  161. package/dist/text/fonts/index.cjs.map +1 -1
  162. package/dist/text/index.cjs.map +1 -1
  163. package/dist/text/text-2d/models/text-attribute-model.cjs +1 -1
  164. package/dist/text/text-2d/models/text-attribute-model.js +1 -1
  165. package/dist/text/text-2d/models/text-attribute-model.js.map +1 -1
  166. package/dist/text/text-2d/models/text-dictionary-model.cjs +1 -1
  167. package/dist/text/text-2d/models/text-dictionary-model.js +1 -1
  168. package/dist/text/text-2d/models/text-dictionary-model.js.map +1 -1
  169. package/dist/text/text-2d/models/text-storage-model.cjs +1 -1
  170. package/dist/text/text-2d/models/text-storage-model.js +1 -1
  171. package/dist/text/text-2d/models/text-storage-model.js.map +1 -1
  172. package/package.json +13 -8
  173. package/src/animation/node-animation-binding.ts +18 -1
  174. package/src/gltf/gltf/animations/animations.ts +8 -1
  175. package/src/gltf/gltf/create-scenegraph-from-gltf.ts +98 -17
  176. package/src/gltf/gltf/gltf-billboard.ts +6 -1
  177. package/src/gltf/gltf/gltf-extension-support.ts +2 -2
  178. package/src/gltf/index.ts +1 -0
  179. package/src/gltf/parsers/parse-gltf-animations.ts +22 -8
  180. package/src/gltf/parsers/parse-gltf-lights.ts +42 -130
  181. package/src/gltf/parsers/parse-gltf-metadata.ts +40 -0
  182. package/src/gltf/parsers/parse-gltf.ts +5 -0
  183. package/src/gltf/pbr/pbr-environment.ts +27 -1
  184. package/src/graph/models/path/path-attribute-model.ts +1 -1
  185. package/src/graph/models/path/path-storage-model.ts +1 -1
  186. package/src/index.ts +16 -0
  187. package/src/lighting/ambient-occlusion-pass.ts +130 -0
  188. package/src/lighting/clustered-light-grid.ts +481 -0
  189. package/src/lighting/contact-shadow-composite.ts +67 -0
  190. package/src/lighting/contact-shadow-pass.ts +107 -0
  191. package/src/lighting/index.ts +88 -0
  192. package/src/lighting/pbr-environment.ts +55 -0
  193. package/src/lighting/pbr-material.ts +85 -0
  194. package/src/lighting/pbr-model.ts +531 -0
  195. package/src/lighting/pbr-surface-pass.ts +122 -0
  196. package/src/lighting/prefiltered-environment.ts +354 -0
  197. package/src/lighting/shadow-map-renderer.ts +909 -0
  198. package/src/lighting/shadow-quality.ts +50 -0
  199. package/src/material/material.ts +3 -0
  200. package/src/model/gpu-vector-model.ts +18 -3
  201. package/src/scenegraph/controllers/punctual-light-controller.ts +172 -0
  202. package/src/scenegraph/scene-metadata.ts +23 -0
  203. package/src/scenegraph/scenegraph-interaction.ts +131 -0
  204. package/src/scenegraph/scenegraph-node.ts +12 -0
  205. package/src/text/fonts/atlas/text-utils.ts +1 -1
  206. package/src/text/text-2d/models/text-attribute-model.ts +1 -1
  207. package/src/text/text-2d/models/text-dictionary-model.ts +1 -1
  208. package/src/text/text-2d/models/text-storage-model.ts +1 -1
@@ -0,0 +1,909 @@
1
+ // luma.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {
6
+ Framebuffer,
7
+ RenderPass,
8
+ RenderPipelineParameters,
9
+ Sampler,
10
+ Texture,
11
+ TextureView
12
+ } from '@luma.gl/core';
13
+ import {Device, Texture as TextureResource} from '@luma.gl/core';
14
+ import {Matrix4, radians} from '@math.gl/core';
15
+ import type {NumberArray3, NumberArray16} from '@math.gl/core';
16
+ import {SHADOW_QUALITY_SETTINGS} from './shadow-quality';
17
+ import type {
18
+ DirectionalShadowLight,
19
+ SpotShadowLight,
20
+ PointShadowLight,
21
+ ShadowProps,
22
+ ShadowBiasProps
23
+ } from '@luma.gl/shaders';
24
+ export type {DirectionalShadowLight, SpotShadowLight, PointShadowLight} from '@luma.gl/shaders';
25
+
26
+ const MAX_DIRECTIONAL_LIGHTS = 1;
27
+ const MAX_SPOT_LIGHTS = 4;
28
+ const MAX_POINT_LIGHTS = 4;
29
+ const MAX_CASCADES = 4;
30
+ const POINT_FACE_COUNT = 6;
31
+ const DEFAULT_NEAR_PLANE = 0.1;
32
+ // math.gl projection builders use OpenGL [-1, 1] depth; shadow maps require WebGPU [0, 1].
33
+ const OPENGL_TO_WEBGPU_MATRIX: NumberArray16 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1];
34
+ const IDENTITY_MATRIX: NumberArray16 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1];
35
+
36
+ export type PointShadowFace = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z';
37
+
38
+ /** Camera matrices and clip distances used to fit directional cascades. */
39
+ export type ShadowCamera = {
40
+ viewMatrix: Readonly<Matrix4 | NumberArray16>;
41
+ projectionMatrix: Readonly<Matrix4 | NumberArray16>;
42
+ near: number;
43
+ far: number;
44
+ /** Input projection depth convention. Defaults to math.gl's OpenGL convention. */
45
+ clipDepth?: 'negative-one-to-one' | 'zero-to-one';
46
+ };
47
+
48
+ /** Resource capacities and quality defaults owned by {@link ShadowMapRenderer}. */
49
+ export type ShadowMapRendererProps = {
50
+ quality?: 'low' | 'balanced' | 'cinematic';
51
+ directionalLightCapacity?: number;
52
+ spotLightCapacity?: number;
53
+ pointLightCapacity?: number;
54
+ directionalMapSize?: number;
55
+ spotMapSize?: number;
56
+ pointMapSize?: number;
57
+ };
58
+
59
+ /** One depth-only light view passed to the application caster callback. */
60
+ export type ShadowRenderView = {
61
+ renderPass: RenderPass;
62
+ framebuffer: Framebuffer;
63
+ type: 'directional' | 'spot' | 'point';
64
+ lightIndex: number;
65
+ cascadeIndex?: number;
66
+ pointFace?: PointShadowFace;
67
+ camera: ShadowCamera;
68
+ viewProjectionMatrix: Readonly<Matrix4>;
69
+ mapSize: number;
70
+ rasterParameters: Readonly<RenderPipelineParameters>;
71
+ };
72
+
73
+ /** Per-frame lights and caster callback accepted by {@link ShadowMapRenderer.render}. */
74
+ export type ShadowRenderOptions = {
75
+ camera: ShadowCamera;
76
+ directionalLights?: readonly DirectionalShadowLight[];
77
+ spotLights?: readonly SpotShadowLight[];
78
+ pointLights?: readonly PointShadowLight[];
79
+ drawShadowCasters: (view: ShadowRenderView) => void;
80
+ /** Upload resources before opening the depth render pass. */
81
+ prepareShadowCasters?: (view: Omit<ShadowRenderView, 'renderPass'>) => void;
82
+ };
83
+
84
+ /** GPU resource props returned by the renderer for the shadow sampling module. */
85
+ export type ShadowShaderProps = ShadowProps<Texture, Sampler>;
86
+
87
+ type ResolvedShadowMapRendererProps = Required<ShadowMapRendererProps> & {
88
+ cascadeCount: number;
89
+ blockerSampleCount: number;
90
+ filterSampleCount: number;
91
+ };
92
+
93
+ type ShadowMapResources = {
94
+ directionalTexture: Texture;
95
+ spotTexture: Texture;
96
+ pointTexture: Texture;
97
+ comparisonSampler: Sampler;
98
+ nonFilteringSampler: Sampler;
99
+ directionalFramebuffers: Framebuffer[];
100
+ spotFramebuffers: Framebuffer[];
101
+ pointFramebuffers: Framebuffer[];
102
+ attachmentViews: TextureView[];
103
+ };
104
+
105
+ type ComputedShadowView = {
106
+ camera: ShadowCamera;
107
+ viewProjectionMatrix: Matrix4;
108
+ };
109
+
110
+ const POINT_FACE_ORIENTATIONS: ReadonlyArray<{
111
+ face: PointShadowFace;
112
+ direction: NumberArray3;
113
+ up: NumberArray3;
114
+ }> = [
115
+ {face: '+X', direction: [1, 0, 0], up: [0, -1, 0]},
116
+ {face: '-X', direction: [-1, 0, 0], up: [0, -1, 0]},
117
+ {face: '+Y', direction: [0, 1, 0], up: [0, 0, 1]},
118
+ {face: '-Y', direction: [0, -1, 0], up: [0, 0, -1]},
119
+ {face: '+Z', direction: [0, 0, 1], up: [0, -1, 0]},
120
+ {face: '-Z', direction: [0, 0, -1], up: [0, -1, 0]}
121
+ ];
122
+
123
+ let nextShadowResourceId = 0;
124
+
125
+ /**
126
+ * Owns backend-selected depth-array resources and records application-supplied shadow caster draws.
127
+ *
128
+ * The renderer never submits the device command encoder. Applications should pre-create any
129
+ * per-view uniform storage needed by `drawShadowCasters`; one shared mutable uniform buffer cannot
130
+ * retain different matrices for several passes recorded into the same command buffer.
131
+ */
132
+ export class ShadowMapRenderer {
133
+ readonly device: Device;
134
+ props: ResolvedShadowMapRendererProps;
135
+
136
+ private inputProps: ShadowMapRendererProps;
137
+ private resources: ShadowMapResources;
138
+ private destroyed = false;
139
+
140
+ constructor(device: Device, props: ShadowMapRendererProps = {}) {
141
+ if (device.type !== 'webgpu' && device.type !== 'webgl') {
142
+ throw new Error('ShadowMapRenderer requires a WebGPU or WebGL2 device.');
143
+ }
144
+ this.device = device;
145
+ this.inputProps = {...props};
146
+ this.props = resolveShadowMapRendererProps(device, this.inputProps);
147
+ this.resources = createShadowMapResources(device, this.props);
148
+ }
149
+
150
+ /** Reconfigures capacities or quality, rebuilding GPU resources only when their shape changes. */
151
+ setProps(props: ShadowMapRendererProps): void {
152
+ this.assertNotDestroyed();
153
+ const nextInputProps = {...this.inputProps, ...props};
154
+ const nextProps = resolveShadowMapRendererProps(this.device, nextInputProps);
155
+ const needsResourceRebuild = !resourcePropsEqual(this.props, nextProps);
156
+ this.inputProps = nextInputProps;
157
+ this.props = nextProps;
158
+ if (!needsResourceRebuild) {
159
+ return;
160
+ }
161
+ const previousResources = this.resources;
162
+ this.resources = createShadowMapResources(this.device, nextProps);
163
+ destroyShadowMapResources(previousResources);
164
+ }
165
+
166
+ /** Records all active shadow-map views and returns props ready for `ShaderInputs.setProps`. */
167
+ render(options: ShadowRenderOptions): ShadowShaderProps {
168
+ this.assertNotDestroyed();
169
+ validateShadowCamera(options.camera);
170
+ const directionalLights = options.directionalLights || [];
171
+ const spotLights = options.spotLights || [];
172
+ const pointLights = options.pointLights || [];
173
+ validateLightCount(
174
+ 'directional',
175
+ directionalLights.length,
176
+ this.props.directionalLightCapacity
177
+ );
178
+ validateLightCount('spot', spotLights.length, this.props.spotLightCapacity);
179
+ validateLightCount('point', pointLights.length, this.props.pointLightCapacity);
180
+
181
+ const directionalViews: ComputedShadowView[] = [];
182
+ let cascadeSplits = padCascadeSplits([], options.camera.far);
183
+ if (directionalLights[0]) {
184
+ const light = resolveDirectionalLight(directionalLights[0], options.camera);
185
+ cascadeSplits = padCascadeSplits(
186
+ getPracticalCascadeSplits(
187
+ options.camera.near,
188
+ light.shadowDistance,
189
+ this.props.cascadeCount,
190
+ light.cascadeSplitLambda
191
+ ),
192
+ light.shadowDistance
193
+ );
194
+ directionalViews.push(
195
+ ...getDirectionalCascadeViews(
196
+ options.camera,
197
+ light,
198
+ cascadeSplits,
199
+ this.props.cascadeCount,
200
+ this.props.directionalMapSize
201
+ )
202
+ );
203
+ directionalViews.forEach((view, cascadeIndex) => {
204
+ this.renderView({
205
+ framebuffer: this.resources.directionalFramebuffers[cascadeIndex],
206
+ view,
207
+ type: 'directional',
208
+ lightIndex: 0,
209
+ cascadeIndex,
210
+ mapSize: this.props.directionalMapSize,
211
+ light,
212
+ drawShadowCasters: options.drawShadowCasters,
213
+ prepareShadowCasters: options.prepareShadowCasters
214
+ });
215
+ });
216
+ }
217
+
218
+ const spotViews = spotLights.map(light => getSpotShadowView(resolveSpotLight(light)));
219
+ spotViews.forEach((view, lightIndex) => {
220
+ this.renderView({
221
+ framebuffer: this.resources.spotFramebuffers[lightIndex],
222
+ view,
223
+ type: 'spot',
224
+ lightIndex,
225
+ mapSize: this.props.spotMapSize,
226
+ light: resolveSpotLight(spotLights[lightIndex]),
227
+ drawShadowCasters: options.drawShadowCasters,
228
+ prepareShadowCasters: options.prepareShadowCasters
229
+ });
230
+ });
231
+
232
+ const pointViews = pointLights.flatMap(light => getPointShadowViews(resolvePointLight(light)));
233
+ pointLights.forEach((inputLight, lightIndex) => {
234
+ const light = resolvePointLight(inputLight);
235
+ for (let faceIndex = 0; faceIndex < POINT_FACE_COUNT; faceIndex++) {
236
+ const viewIndex = lightIndex * POINT_FACE_COUNT + faceIndex;
237
+ this.renderView({
238
+ framebuffer: this.resources.pointFramebuffers[viewIndex],
239
+ view: pointViews[viewIndex],
240
+ type: 'point',
241
+ lightIndex,
242
+ pointFace: POINT_FACE_ORIENTATIONS[faceIndex].face,
243
+ mapSize: this.props.pointMapSize,
244
+ light,
245
+ drawShadowCasters: options.drawShadowCasters,
246
+ prepareShadowCasters: options.prepareShadowCasters
247
+ });
248
+ }
249
+ });
250
+
251
+ return {
252
+ quality: this.props.quality,
253
+ cascadeCount: this.props.cascadeCount,
254
+ cascadeSplits,
255
+ blockerSampleCount: this.props.blockerSampleCount,
256
+ filterSampleCount: this.props.filterSampleCount,
257
+ directionalLights: directionalLights.map(light =>
258
+ resolveDirectionalLight(light, options.camera)
259
+ ),
260
+ spotLights: spotLights.map(resolveSpotLight),
261
+ pointLights: pointLights.map(resolvePointLight),
262
+ directionalViewProjectionMatrices: padMatrices(
263
+ directionalViews.map(view => view.viewProjectionMatrix),
264
+ MAX_CASCADES
265
+ ),
266
+ spotViewProjectionMatrices: padMatrices(
267
+ spotViews.map(view => view.viewProjectionMatrix),
268
+ MAX_SPOT_LIGHTS
269
+ ),
270
+ pointViewProjectionMatrices: padMatrices(
271
+ pointViews.map(view => view.viewProjectionMatrix),
272
+ MAX_POINT_LIGHTS * POINT_FACE_COUNT
273
+ ),
274
+ directionalShadowTexture: this.resources.directionalTexture,
275
+ spotShadowTexture: this.resources.spotTexture,
276
+ pointShadowTexture: this.resources.pointTexture,
277
+ comparisonSampler: this.resources.comparisonSampler,
278
+ nonFilteringSampler: this.resources.nonFilteringSampler
279
+ };
280
+ }
281
+
282
+ /** Destroys all owned depth textures, views, framebuffers and samplers. */
283
+ destroy(): void {
284
+ if (this.destroyed) {
285
+ return;
286
+ }
287
+ this.destroyed = true;
288
+ destroyShadowMapResources(this.resources);
289
+ }
290
+
291
+ private renderView(options: {
292
+ framebuffer: Framebuffer;
293
+ view: ComputedShadowView;
294
+ type: ShadowRenderView['type'];
295
+ lightIndex: number;
296
+ cascadeIndex?: number;
297
+ pointFace?: PointShadowFace;
298
+ mapSize: number;
299
+ light: ShadowBiasProps;
300
+ drawShadowCasters: ShadowRenderOptions['drawShadowCasters'];
301
+ prepareShadowCasters?: ShadowRenderOptions['prepareShadowCasters'];
302
+ }): void {
303
+ const rasterParameters = Object.freeze({
304
+ depthWriteEnabled: true,
305
+ depthCompare: 'less-equal',
306
+ depthBias: options.light.depthBias,
307
+ depthBiasSlopeScale: options.light.depthBiasSlopeScale,
308
+ cullMode: 'back'
309
+ } satisfies RenderPipelineParameters);
310
+ const context = {
311
+ framebuffer: options.framebuffer,
312
+ type: options.type,
313
+ lightIndex: options.lightIndex,
314
+ cascadeIndex: options.cascadeIndex,
315
+ pointFace: options.pointFace,
316
+ camera: options.view.camera,
317
+ viewProjectionMatrix: options.view.viewProjectionMatrix,
318
+ mapSize: options.mapSize,
319
+ rasterParameters
320
+ };
321
+ options.prepareShadowCasters?.(context);
322
+ const renderPass = this.device.beginRenderPass({
323
+ id: makeShadowResourceId(`${options.type}-shadow-pass`),
324
+ framebuffer: options.framebuffer,
325
+ clearDepth: 1
326
+ });
327
+ try {
328
+ options.drawShadowCasters({
329
+ renderPass,
330
+ framebuffer: options.framebuffer,
331
+ type: options.type,
332
+ lightIndex: options.lightIndex,
333
+ cascadeIndex: options.cascadeIndex,
334
+ pointFace: options.pointFace,
335
+ camera: options.view.camera,
336
+ viewProjectionMatrix: options.view.viewProjectionMatrix,
337
+ mapSize: options.mapSize,
338
+ rasterParameters
339
+ });
340
+ } finally {
341
+ renderPass.end();
342
+ }
343
+ }
344
+
345
+ private assertNotDestroyed(): void {
346
+ if (this.destroyed) {
347
+ throw new Error('ShadowMapRenderer has been destroyed.');
348
+ }
349
+ }
350
+ }
351
+
352
+ /** Returns logarithmic/uniform blended cascade far distances. */
353
+ export function getPracticalCascadeSplits(
354
+ near: number,
355
+ far: number,
356
+ cascadeCount: number,
357
+ lambda = 0.5
358
+ ): number[] {
359
+ if (!(near > 0 && far > near)) {
360
+ throw new Error('Cascade split range requires 0 < near < far.');
361
+ }
362
+ if (!Number.isInteger(cascadeCount) || cascadeCount < 1 || cascadeCount > MAX_CASCADES) {
363
+ throw new Error(`Cascade count must be an integer from 1 to ${MAX_CASCADES}.`);
364
+ }
365
+ const clampedLambda = clamp(lambda, 0, 1);
366
+ const splits: number[] = [];
367
+ for (let splitIndex = 1; splitIndex <= cascadeCount; splitIndex++) {
368
+ const fraction = splitIndex / cascadeCount;
369
+ const logarithmic = near * Math.pow(far / near, fraction);
370
+ const uniform = near + (far - near) * fraction;
371
+ splits.push(uniform * (1 - clampedLambda) + logarithmic * clampedLambda);
372
+ }
373
+ return splits;
374
+ }
375
+
376
+ /** Computes texel-snapped orthographic cascade cameras for a directional light. */
377
+ export function getDirectionalCascadeViews(
378
+ camera: ShadowCamera,
379
+ light: Required<DirectionalShadowLight>,
380
+ cascadeSplits: readonly number[],
381
+ cascadeCount: number,
382
+ mapSize: number
383
+ ): ComputedShadowView[] {
384
+ const inverseViewProjection = new Matrix4(camera.projectionMatrix)
385
+ .multiplyRight(camera.viewMatrix)
386
+ .invert();
387
+ const nearCorners = getNdcPlaneCorners(
388
+ inverseViewProjection,
389
+ camera.clipDepth === 'zero-to-one' ? 0 : -1
390
+ );
391
+ const farCorners = getNdcPlaneCorners(inverseViewProjection, 1);
392
+ const lightDirection = normalize3(light.direction);
393
+ const views: ComputedShadowView[] = [];
394
+ let cascadeNear = camera.near;
395
+
396
+ for (let cascadeIndex = 0; cascadeIndex < cascadeCount; cascadeIndex++) {
397
+ const cascadeFar = cascadeSplits[cascadeIndex];
398
+ const nearFraction = (cascadeNear - camera.near) / (camera.far - camera.near);
399
+ const farFraction = (cascadeFar - camera.near) / (camera.far - camera.near);
400
+ const corners: NumberArray3[] = [];
401
+ for (let cornerIndex = 0; cornerIndex < 4; cornerIndex++) {
402
+ corners.push(lerp3(nearCorners[cornerIndex], farCorners[cornerIndex], nearFraction));
403
+ corners.push(lerp3(nearCorners[cornerIndex], farCorners[cornerIndex], farFraction));
404
+ }
405
+ const center = average3(corners);
406
+ let radius = 0;
407
+ for (const corner of corners) {
408
+ radius = Math.max(radius, distance3(center, corner));
409
+ }
410
+ radius = Math.ceil(radius * 16) / 16;
411
+ const texelWorldSize = (radius * 2) / mapSize;
412
+ const lightForward = scale3(lightDirection, -1);
413
+ const referenceUp: NumberArray3 = Math.abs(lightForward[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0];
414
+ const lightRight = normalize3(cross3(lightForward, referenceUp));
415
+ const lightUp = normalize3(cross3(lightRight, lightForward));
416
+ const centerRight = dot3(center, lightRight);
417
+ const centerUp = dot3(center, lightUp);
418
+ const snappedCenter = add3(
419
+ center,
420
+ add3(
421
+ scale3(lightRight, Math.round(centerRight / texelWorldSize) * texelWorldSize - centerRight),
422
+ scale3(lightUp, Math.round(centerUp / texelWorldSize) * texelWorldSize - centerUp)
423
+ )
424
+ );
425
+ const eye = add3(snappedCenter, scale3(lightDirection, radius + light.casterDistance));
426
+ const viewMatrix = new Matrix4().lookAt({eye, center: snappedCenter, up: lightUp});
427
+ const projectionMatrix = new Matrix4(OPENGL_TO_WEBGPU_MATRIX).multiplyRight(
428
+ new Matrix4().ortho({
429
+ left: -radius,
430
+ right: radius,
431
+ bottom: -radius,
432
+ top: radius,
433
+ near: 0.01,
434
+ far: radius * 2 + light.casterDistance
435
+ })
436
+ );
437
+ views.push({
438
+ camera: {
439
+ viewMatrix,
440
+ projectionMatrix,
441
+ near: 0.01,
442
+ far: radius * 2 + light.casterDistance,
443
+ clipDepth: 'zero-to-one'
444
+ },
445
+ viewProjectionMatrix: new Matrix4(projectionMatrix).multiplyRight(viewMatrix)
446
+ });
447
+ cascadeNear = cascadeFar;
448
+ }
449
+ return views;
450
+ }
451
+
452
+ /** Computes a perspective camera for one spot shadow map. */
453
+ export function getSpotShadowView(light: Required<SpotShadowLight>): ComputedShadowView {
454
+ const direction = normalize3(light.direction);
455
+ const up: NumberArray3 = Math.abs(direction[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0];
456
+ const viewMatrix = new Matrix4().lookAt({
457
+ eye: light.position,
458
+ center: add3(light.position, direction),
459
+ up
460
+ });
461
+ const projectionMatrix = new Matrix4(OPENGL_TO_WEBGPU_MATRIX).multiplyRight(
462
+ new Matrix4().perspective({
463
+ fovy: light.outerConeAngle * 2,
464
+ aspect: 1,
465
+ near: light.nearPlane,
466
+ far: light.range
467
+ })
468
+ );
469
+ return {
470
+ camera: {
471
+ viewMatrix,
472
+ projectionMatrix,
473
+ near: light.nearPlane,
474
+ far: light.range,
475
+ clipDepth: 'zero-to-one'
476
+ },
477
+ viewProjectionMatrix: new Matrix4(projectionMatrix).multiplyRight(viewMatrix)
478
+ };
479
+ }
480
+
481
+ /** Computes the six canonical cameras used by one cube-array point shadow. */
482
+ export function getPointShadowViews(light: Required<PointShadowLight>): ComputedShadowView[] {
483
+ const projectionMatrix = new Matrix4(OPENGL_TO_WEBGPU_MATRIX).multiplyRight(
484
+ new Matrix4().perspective({
485
+ fovy: radians(90),
486
+ aspect: 1,
487
+ near: light.nearPlane,
488
+ far: light.range
489
+ })
490
+ );
491
+ return POINT_FACE_ORIENTATIONS.map((orientation): ComputedShadowView => {
492
+ const viewMatrix = new Matrix4().lookAt({
493
+ eye: light.position,
494
+ center: add3(light.position, orientation.direction),
495
+ up: orientation.up
496
+ });
497
+ return {
498
+ camera: {
499
+ viewMatrix,
500
+ projectionMatrix,
501
+ near: light.nearPlane,
502
+ far: light.range,
503
+ clipDepth: 'zero-to-one'
504
+ },
505
+ viewProjectionMatrix: new Matrix4(projectionMatrix).multiplyRight(viewMatrix)
506
+ };
507
+ });
508
+ }
509
+
510
+ function resolveShadowMapRendererProps(
511
+ device: Device,
512
+ props: ShadowMapRendererProps
513
+ ): ResolvedShadowMapRendererProps {
514
+ const quality = props.quality || 'balanced';
515
+ const qualitySettings = SHADOW_QUALITY_SETTINGS[quality];
516
+ if (!qualitySettings) {
517
+ throw new Error(`Unknown shadow quality: ${String(quality)}.`);
518
+ }
519
+ const resolved = {
520
+ quality,
521
+ directionalLightCapacity: props.directionalLightCapacity ?? 1,
522
+ spotLightCapacity: props.spotLightCapacity ?? 1,
523
+ pointLightCapacity: props.pointLightCapacity ?? 1,
524
+ directionalMapSize: props.directionalMapSize ?? qualitySettings.directionalMapSize,
525
+ spotMapSize: props.spotMapSize ?? qualitySettings.spotMapSize,
526
+ pointMapSize: props.pointMapSize ?? qualitySettings.pointMapSize,
527
+ cascadeCount: qualitySettings.cascadeCount,
528
+ blockerSampleCount: qualitySettings.blockerSampleCount,
529
+ filterSampleCount: qualitySettings.filterSampleCount
530
+ };
531
+ validateCapacity(
532
+ 'directionalLightCapacity',
533
+ resolved.directionalLightCapacity,
534
+ MAX_DIRECTIONAL_LIGHTS
535
+ );
536
+ validateCapacity('spotLightCapacity', resolved.spotLightCapacity, MAX_SPOT_LIGHTS);
537
+ validateCapacity('pointLightCapacity', resolved.pointLightCapacity, MAX_POINT_LIGHTS);
538
+ validateMapSize(device, 'directionalMapSize', resolved.directionalMapSize);
539
+ validateMapSize(device, 'spotMapSize', resolved.spotMapSize);
540
+ validateMapSize(device, 'pointMapSize', resolved.pointMapSize);
541
+ const pointLayers = Math.max(POINT_FACE_COUNT, resolved.pointLightCapacity * POINT_FACE_COUNT);
542
+ if (pointLayers > device.limits.maxTextureArrayLayers) {
543
+ throw new Error(
544
+ `pointLightCapacity requires ${pointLayers} array layers, exceeding the device limit ${device.limits.maxTextureArrayLayers}.`
545
+ );
546
+ }
547
+ return resolved;
548
+ }
549
+
550
+ function createShadowMapResources(
551
+ device: Device,
552
+ props: ResolvedShadowMapRendererProps
553
+ ): ShadowMapResources {
554
+ const directionalLayers = Math.max(1, props.directionalLightCapacity * props.cascadeCount);
555
+ const spotLayers = Math.max(1, props.spotLightCapacity);
556
+ const pointLayers = Math.max(POINT_FACE_COUNT, props.pointLightCapacity * POINT_FACE_COUNT);
557
+ const comparisonSampler = device.createSampler({
558
+ id: makeShadowResourceId('shadow-comparison-sampler'),
559
+ type: 'comparison-sampler',
560
+ compare: 'less-equal',
561
+ minFilter: 'linear',
562
+ magFilter: 'linear',
563
+ addressModeU: 'clamp-to-edge',
564
+ addressModeV: 'clamp-to-edge',
565
+ addressModeW: 'clamp-to-edge'
566
+ });
567
+ const nonFilteringSampler = device.createSampler({
568
+ id: makeShadowResourceId('shadow-depth-sampler'),
569
+ minFilter: 'nearest',
570
+ magFilter: 'nearest',
571
+ addressModeU: 'clamp-to-edge',
572
+ addressModeV: 'clamp-to-edge',
573
+ addressModeW: 'clamp-to-edge'
574
+ });
575
+ const directionalTexture = createDepthArrayTexture(
576
+ device,
577
+ 'directional-shadow-map',
578
+ '2d-array',
579
+ props.directionalMapSize,
580
+ directionalLayers,
581
+ nonFilteringSampler
582
+ );
583
+ const spotTexture = createDepthArrayTexture(
584
+ device,
585
+ 'spot-shadow-map',
586
+ '2d-array',
587
+ props.spotMapSize,
588
+ spotLayers,
589
+ nonFilteringSampler
590
+ );
591
+ const pointTexture = createDepthArrayTexture(
592
+ device,
593
+ 'point-shadow-map',
594
+ device.type === 'webgpu' ? 'cube-array' : '2d-array',
595
+ props.pointMapSize,
596
+ pointLayers,
597
+ nonFilteringSampler
598
+ );
599
+ const attachmentViews: TextureView[] = [];
600
+ const directionalFramebuffers = createLayerFramebuffers(
601
+ device,
602
+ directionalTexture,
603
+ props.directionalMapSize,
604
+ directionalLayers,
605
+ attachmentViews
606
+ );
607
+ const spotFramebuffers = createLayerFramebuffers(
608
+ device,
609
+ spotTexture,
610
+ props.spotMapSize,
611
+ spotLayers,
612
+ attachmentViews
613
+ );
614
+ const pointFramebuffers = createLayerFramebuffers(
615
+ device,
616
+ pointTexture,
617
+ props.pointMapSize,
618
+ pointLayers,
619
+ attachmentViews
620
+ );
621
+ return {
622
+ directionalTexture,
623
+ spotTexture,
624
+ pointTexture,
625
+ comparisonSampler,
626
+ nonFilteringSampler,
627
+ directionalFramebuffers,
628
+ spotFramebuffers,
629
+ pointFramebuffers,
630
+ attachmentViews
631
+ };
632
+ }
633
+
634
+ function createDepthArrayTexture(
635
+ device: Device,
636
+ id: string,
637
+ dimension: '2d-array' | 'cube-array',
638
+ size: number,
639
+ depth: number,
640
+ sampler: Sampler
641
+ ): Texture {
642
+ return device.createTexture({
643
+ id: makeShadowResourceId(id),
644
+ dimension,
645
+ format: 'depth32float',
646
+ width: size,
647
+ height: size,
648
+ depth,
649
+ sampler,
650
+ usage: TextureResource.SAMPLE | TextureResource.RENDER
651
+ });
652
+ }
653
+
654
+ function createLayerFramebuffers(
655
+ device: Device,
656
+ texture: Texture,
657
+ size: number,
658
+ layerCount: number,
659
+ views: TextureView[]
660
+ ): Framebuffer[] {
661
+ return Array.from({length: layerCount}, (_, layerIndex) => {
662
+ const view = texture.createView({
663
+ id: makeShadowResourceId('shadow-layer-view'),
664
+ format: texture.format,
665
+ dimension: '2d',
666
+ baseMipLevel: 0,
667
+ mipLevelCount: 1,
668
+ baseArrayLayer: layerIndex,
669
+ arrayLayerCount: 1
670
+ });
671
+ views.push(view);
672
+ return device.createFramebuffer({
673
+ id: makeShadowResourceId('shadow-layer-framebuffer'),
674
+ width: size,
675
+ height: size,
676
+ colorAttachments: [],
677
+ depthStencilAttachment: view
678
+ });
679
+ });
680
+ }
681
+
682
+ function destroyShadowMapResources(resources: ShadowMapResources): void {
683
+ for (const framebuffer of [
684
+ ...resources.directionalFramebuffers,
685
+ ...resources.spotFramebuffers,
686
+ ...resources.pointFramebuffers
687
+ ]) {
688
+ framebuffer.destroy();
689
+ }
690
+ for (const view of resources.attachmentViews) {
691
+ view.destroy();
692
+ }
693
+ resources.directionalTexture.destroy();
694
+ resources.spotTexture.destroy();
695
+ resources.pointTexture.destroy();
696
+ resources.comparisonSampler.destroy();
697
+ resources.nonFilteringSampler.destroy();
698
+ }
699
+
700
+ function resourcePropsEqual(
701
+ first: ResolvedShadowMapRendererProps,
702
+ second: ResolvedShadowMapRendererProps
703
+ ): boolean {
704
+ return (
705
+ first.cascadeCount === second.cascadeCount &&
706
+ first.directionalLightCapacity === second.directionalLightCapacity &&
707
+ first.spotLightCapacity === second.spotLightCapacity &&
708
+ first.pointLightCapacity === second.pointLightCapacity &&
709
+ first.directionalMapSize === second.directionalMapSize &&
710
+ first.spotMapSize === second.spotMapSize &&
711
+ first.pointMapSize === second.pointMapSize
712
+ );
713
+ }
714
+
715
+ function resolveDirectionalLight(
716
+ light: DirectionalShadowLight,
717
+ camera: ShadowCamera
718
+ ): Required<DirectionalShadowLight> {
719
+ const shadowDistance = clamp(light.shadowDistance ?? camera.far, camera.near, camera.far);
720
+ return {
721
+ direction: normalize3(light.direction),
722
+ shadowDistance,
723
+ casterDistance: light.casterDistance ?? shadowDistance,
724
+ sourceAngularRadius: light.sourceAngularRadius ?? 0.00465,
725
+ cascadeSplitLambda: light.cascadeSplitLambda ?? 0.5,
726
+ cascadeBlendFraction: light.cascadeBlendFraction ?? 0.1,
727
+ farFadeFraction: light.farFadeFraction ?? 0.1,
728
+ normalBias: light.normalBias ?? 0.04,
729
+ depthBias: light.depthBias ?? 2,
730
+ depthBiasSlopeScale: light.depthBiasSlopeScale ?? 2,
731
+ strength: clamp(light.strength ?? 1, 0, 1)
732
+ };
733
+ }
734
+
735
+ function resolveSpotLight(light: SpotShadowLight): Required<SpotShadowLight> {
736
+ validateRange('Spot shadow', light.range);
737
+ if (!(light.outerConeAngle > 0 && light.outerConeAngle < Math.PI / 2)) {
738
+ throw new Error('Spot shadow outerConeAngle must be between 0 and PI / 2 radians.');
739
+ }
740
+ return {
741
+ position: [...light.position] as NumberArray3,
742
+ direction: normalize3(light.direction),
743
+ range: light.range,
744
+ outerConeAngle: light.outerConeAngle,
745
+ nearPlane: resolveNearPlane(light.nearPlane, light.range),
746
+ sourceRadius: light.sourceRadius ?? 0.2,
747
+ normalBias: light.normalBias ?? 0.025,
748
+ depthBias: light.depthBias ?? 2,
749
+ depthBiasSlopeScale: light.depthBiasSlopeScale ?? 2,
750
+ strength: clamp(light.strength ?? 1, 0, 1)
751
+ };
752
+ }
753
+
754
+ function resolvePointLight(light: PointShadowLight): Required<PointShadowLight> {
755
+ validateRange('Point shadow', light.range);
756
+ return {
757
+ position: [...light.position] as NumberArray3,
758
+ range: light.range,
759
+ nearPlane: resolveNearPlane(light.nearPlane, light.range),
760
+ sourceRadius: light.sourceRadius ?? 0.2,
761
+ normalBias: light.normalBias ?? 0.025,
762
+ depthBias: light.depthBias ?? 2,
763
+ depthBiasSlopeScale: light.depthBiasSlopeScale ?? 2,
764
+ strength: clamp(light.strength ?? 1, 0, 1)
765
+ };
766
+ }
767
+
768
+ function resolveNearPlane(nearPlane: number | undefined, range: number): number {
769
+ const resolvedNearPlane = nearPlane ?? Math.max(DEFAULT_NEAR_PLANE, range / 1000);
770
+ if (!(resolvedNearPlane > 0 && resolvedNearPlane < range)) {
771
+ throw new Error('Shadow nearPlane must be greater than zero and less than range.');
772
+ }
773
+ return resolvedNearPlane;
774
+ }
775
+
776
+ function validateShadowCamera(camera: ShadowCamera): void {
777
+ if (!(camera.near > 0 && camera.far > camera.near)) {
778
+ throw new Error('ShadowCamera requires 0 < near < far.');
779
+ }
780
+ }
781
+
782
+ function validateCapacity(name: string, value: number, maximum: number): void {
783
+ if (!Number.isInteger(value) || value < 0 || value > maximum) {
784
+ throw new Error(`${name} must be an integer from 0 to ${maximum}.`);
785
+ }
786
+ }
787
+
788
+ function validateMapSize(device: Device, name: string, value: number): void {
789
+ if (!Number.isInteger(value) || value < 1 || value > device.limits.maxTextureDimension2D) {
790
+ throw new Error(
791
+ `${name} must be a positive integer no greater than ${device.limits.maxTextureDimension2D}.`
792
+ );
793
+ }
794
+ }
795
+
796
+ function validateLightCount(type: string, count: number, capacity: number): void {
797
+ if (count > capacity) {
798
+ throw new Error(`${type} shadow light count ${count} exceeds configured capacity ${capacity}.`);
799
+ }
800
+ }
801
+
802
+ function validateRange(label: string, range: number): void {
803
+ if (!(range > 0 && Number.isFinite(range))) {
804
+ throw new Error(`${label} range must be a finite positive number.`);
805
+ }
806
+ }
807
+
808
+ function padCascadeSplits(splits: readonly number[], fallback: number): number[] {
809
+ const result = splits.slice(0, MAX_CASCADES);
810
+ while (result.length < MAX_CASCADES) {
811
+ result.push(result[result.length - 1] ?? fallback);
812
+ }
813
+ return result;
814
+ }
815
+
816
+ function padMatrices(
817
+ matrices: readonly Readonly<Matrix4 | NumberArray16>[],
818
+ count: number
819
+ ): Readonly<Matrix4 | NumberArray16>[] {
820
+ const result = matrices.slice(0, count);
821
+ while (result.length < count) {
822
+ result.push(IDENTITY_MATRIX);
823
+ }
824
+ return result;
825
+ }
826
+
827
+ function getNdcPlaneCorners(matrix: Matrix4, z: number): NumberArray3[] {
828
+ return [
829
+ transformHomogeneous(matrix, [-1, -1, z]),
830
+ transformHomogeneous(matrix, [1, -1, z]),
831
+ transformHomogeneous(matrix, [1, 1, z]),
832
+ transformHomogeneous(matrix, [-1, 1, z])
833
+ ];
834
+ }
835
+
836
+ function transformHomogeneous(matrix: Matrix4, point: NumberArray3): NumberArray3 {
837
+ const x = point[0];
838
+ const y = point[1];
839
+ const z = point[2];
840
+ const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
841
+ return [
842
+ (matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) / w,
843
+ (matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) / w,
844
+ (matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]) / w
845
+ ];
846
+ }
847
+
848
+ function normalize3(vector: Readonly<NumberArray3>): NumberArray3 {
849
+ const length = Math.hypot(vector[0], vector[1], vector[2]);
850
+ if (!(length > 0)) {
851
+ throw new Error('Shadow light direction must be non-zero.');
852
+ }
853
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
854
+ }
855
+
856
+ function add3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): NumberArray3 {
857
+ return [first[0] + second[0], first[1] + second[1], first[2] + second[2]];
858
+ }
859
+
860
+ function scale3(vector: Readonly<NumberArray3>, scale: number): NumberArray3 {
861
+ return [vector[0] * scale, vector[1] * scale, vector[2] * scale];
862
+ }
863
+
864
+ function dot3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): number {
865
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
866
+ }
867
+
868
+ function cross3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): NumberArray3 {
869
+ return [
870
+ first[1] * second[2] - first[2] * second[1],
871
+ first[2] * second[0] - first[0] * second[2],
872
+ first[0] * second[1] - first[1] * second[0]
873
+ ];
874
+ }
875
+
876
+ function lerp3(
877
+ first: Readonly<NumberArray3>,
878
+ second: Readonly<NumberArray3>,
879
+ t: number
880
+ ): NumberArray3 {
881
+ return [
882
+ first[0] + (second[0] - first[0]) * t,
883
+ first[1] + (second[1] - first[1]) * t,
884
+ first[2] + (second[2] - first[2]) * t
885
+ ];
886
+ }
887
+
888
+ function average3(vectors: readonly Readonly<NumberArray3>[]): NumberArray3 {
889
+ const sum: NumberArray3 = [0, 0, 0];
890
+ for (const vector of vectors) {
891
+ sum[0] += vector[0];
892
+ sum[1] += vector[1];
893
+ sum[2] += vector[2];
894
+ }
895
+ return scale3(sum, 1 / vectors.length);
896
+ }
897
+
898
+ function distance3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): number {
899
+ return Math.hypot(first[0] - second[0], first[1] - second[1], first[2] - second[2]);
900
+ }
901
+
902
+ function clamp(value: number, minimum: number, maximum: number): number {
903
+ return Math.max(minimum, Math.min(maximum, value));
904
+ }
905
+
906
+ function makeShadowResourceId(prefix: string): string {
907
+ nextShadowResourceId += 1;
908
+ return `${prefix}-${nextShadowResourceId}`;
909
+ }