Skip to main content

three_rs/lights/
light_shadow.rs

1//! Ports of `three.js/src/lights/LightShadow.js`, `SpotLightShadow.js`,
2//! `DirectionalLightShadow.js` and `PointLightShadow.js`' defaults (its
3//! six-face `updateMatrices` lives in the renderer's shadow pass).
4
5use crate::cameras::{OrthographicCamera, PerspectiveCamera};
6use crate::math::{Matrix4, Vector2, Vector3, RAD2DEG};
7use crate::nodes::NodeRef;
8use crate::textures::CubeDepthTexture;
9
10use super::shadow_filter::ShadowFilterFn;
11
12/// `LightShadow.camera` — a `PerspectiveCamera` for `SpotLightShadow`, an
13/// `OrthographicCamera` for `DirectionalLightShadow`.
14#[derive(Clone)]
15#[allow(clippy::large_enum_variant)] // public API; boxing a variant would change every construction site (batched separately, see #9/#38/#39)
16pub enum ShadowCamera {
17    /// The spot- and point-light shadow camera.
18    Perspective(PerspectiveCamera),
19    /// The directional-light shadow camera.
20    Orthographic(OrthographicCamera),
21}
22
23impl ShadowCamera {
24    /// `shadow.camera.near`.
25    pub fn near(&self) -> f64 {
26        match self {
27            ShadowCamera::Perspective(c) => c.near,
28            ShadowCamera::Orthographic(c) => c.near,
29        }
30    }
31
32    /// `shadow.camera.near = near`.
33    pub fn set_near(&mut self, near: f64) {
34        match self {
35            ShadowCamera::Perspective(c) => c.near = near,
36            ShadowCamera::Orthographic(c) => c.near = near,
37        }
38    }
39
40    /// `shadow.camera.far`.
41    pub fn far(&self) -> f64 {
42        match self {
43            ShadowCamera::Perspective(c) => c.far,
44            ShadowCamera::Orthographic(c) => c.far,
45        }
46    }
47
48    /// `shadow.camera.far = far`.
49    pub fn set_far(&mut self, far: f64) {
50        match self {
51            ShadowCamera::Perspective(c) => c.far = far,
52            ShadowCamera::Orthographic(c) => c.far = far,
53        }
54    }
55
56    /// `shadow.camera.left / right / top / bottom` — only the directional
57    /// light's orthographic shadow camera has them.
58    pub fn set_bounds(&mut self, left: f64, right: f64, top: f64, bottom: f64) {
59        match self {
60            ShadowCamera::Perspective(_) => {
61                panic!("three-rs: a perspective shadow camera has no ortho bounds")
62            }
63            ShadowCamera::Orthographic(c) => {
64                c.left = left;
65                c.right = right;
66                c.top = top;
67                c.bottom = bottom;
68            }
69        }
70    }
71
72    /// `shadow.camera.isOrthographicCamera` — `ShadowNode.setupShadowCoord()`
73    /// branches on it (and so does `_updateMatrix`, through
74    /// `coordinateSystem`).
75    pub fn is_orthographic(&self) -> bool {
76        matches!(self, ShadowCamera::Orthographic(_))
77    }
78
79    /// `shadow.camera.projectionMatrix`.
80    pub fn projection_matrix(&self) -> Matrix4 {
81        match self {
82            ShadowCamera::Perspective(c) => c.projection_matrix,
83            ShadowCamera::Orthographic(c) => c.projection_matrix,
84        }
85    }
86
87    /// `shadow.camera.matrixWorld`.
88    pub fn matrix_world(&self) -> Matrix4 {
89        match self {
90            ShadowCamera::Perspective(c) => c.node.borrow().matrix_world,
91            ShadowCamera::Orthographic(c) => c.object.matrix_world,
92        }
93    }
94
95    /// `shadow.camera.matrixWorldInverse`.
96    pub fn matrix_world_inverse(&self) -> Matrix4 {
97        match self {
98            ShadowCamera::Perspective(c) => c.matrix_world_inverse,
99            ShadowCamera::Orthographic(c) => c.matrix_world_inverse,
100        }
101    }
102
103    /// `shadow.camera.updateProjectionMatrix()`.
104    pub fn update_projection_matrix(&mut self) {
105        match self {
106            ShadowCamera::Perspective(c) => c.update_projection_matrix(),
107            ShadowCamera::Orthographic(c) => c.update_projection_matrix(),
108        }
109    }
110
111    /// `shadowCamera.position.copy( lightPositionWorld )`, `lookAt( target )`,
112    /// `updateMatrixWorld()`.
113    fn place(&mut self, position: Vector3, target: &Vector3) {
114        match self {
115            ShadowCamera::Perspective(c) => {
116                c.node.borrow_mut().position = position;
117                c.look_at(target);
118                c.update_matrix_world();
119            }
120            ShadowCamera::Orthographic(c) => {
121                c.object.position = position;
122                c.look_at(target);
123                c.update_matrix_world();
124            }
125        }
126    }
127}
128
129/// `class LightShadow`, plus the `SpotLightShadow`/`DirectionalLightShadow`
130/// fields (`focus`, `aspect`) — the two subclasses differ only in their camera
131/// and in `updateMatrices`, so one struct with a camera enum covers both.
132pub struct LightShadow {
133    /// `this.camera` — a perspective camera for a spot or point light, an
134    /// orthographic one for a directional light.
135    pub camera: ShadowCamera,
136    /// `this.intensity`.
137    pub intensity: f64,
138    /// `this.bias` — added to the shadow coordinate's `z` in the shader.
139    pub bias: f64,
140    /// `this.normalBias` — scales `normalWorld` before the shadow matrix.
141    pub normal_bias: f64,
142    /// `this.radius` — the PCF disk radius, in texels.
143    pub radius: f64,
144    /// `this.blurSamples` — the tap count of each VSM blur pass.
145    pub blur_samples: usize,
146    /// `this.mapSize`.
147    pub map_size: Vector2,
148    /// `this.matrix` — the bias matrix composed with
149    /// `projectionMatrix * matrixWorldInverse`.
150    pub matrix: Matrix4,
151    /// `SpotLightShadow.focus`.
152    pub focus: f64,
153    /// `SpotLightShadow.aspect`.
154    pub aspect: f64,
155    /// `this.filterNode` — a shadow filter used in place of the one
156    /// `renderer.shadowMap.type` picks. `None` is three's `undefined`.
157    pub filter_node: Option<ShadowFilterFn>,
158    /// `this.shadowNode` — a node used as the light's whole shadow factor
159    /// instead of a `ShadowNode`; no shadow map is rendered for the light.
160    pub shadow_node: Option<NodeRef>,
161    /// `this.map.depthTexture` of a point light's shadow — the
162    /// `CubeDepthTexture` the renderer draws the six faces into. Made on first
163    /// ask, by [`LightShadow::point_depth_texture`] or by the renderer's first
164    /// shadow render, whichever comes first, so a node built before the first
165    /// frame (`GodraysNode`) and the renderer name the same texture.
166    pub(crate) point_depth_texture: Option<CubeDepthTexture>,
167}
168
169/// Field for field, except the point light's cube depth texture, which the
170/// clone starts without. Three's `LightShadow.copy()` never copies `map`, so a
171/// copied shadow renders into a map of its own; a derived `Clone` would share
172/// the `CubeDepthTexture` handle and have two lights draw into one texture.
173impl Clone for LightShadow {
174    fn clone(&self) -> Self {
175        Self {
176            camera: self.camera.clone(),
177            intensity: self.intensity,
178            bias: self.bias,
179            normal_bias: self.normal_bias,
180            radius: self.radius,
181            blur_samples: self.blur_samples,
182            map_size: self.map_size,
183            matrix: self.matrix,
184            focus: self.focus,
185            aspect: self.aspect,
186            filter_node: self.filter_node.clone(),
187            shadow_node: self.shadow_node.clone(),
188            point_depth_texture: None,
189        }
190    }
191}
192
193impl LightShadow {
194    /// `new SpotLightShadow()` — `new PerspectiveCamera( 50, 1, 0.5, 500 )`.
195    pub fn spot() -> Self {
196        Self::new(ShadowCamera::Perspective(PerspectiveCamera::new(
197            50.0, 1.0, 0.5, 500.0,
198        )))
199    }
200
201    /// `new PointLightShadow()` — `new PerspectiveCamera( 90, 1, 0.5, 500 )`.
202    pub fn point() -> Self {
203        Self::new(ShadowCamera::Perspective(PerspectiveCamera::new(
204            90.0, 1.0, 0.5, 500.0,
205        )))
206    }
207
208    /// `new DirectionalLightShadow()` —
209    /// `new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 )`.
210    pub fn directional() -> Self {
211        Self::new(ShadowCamera::Orthographic(OrthographicCamera::new(
212            -5.0, 5.0, 5.0, -5.0, 0.5, 500.0,
213        )))
214    }
215
216    fn new(camera: ShadowCamera) -> Self {
217        Self {
218            camera,
219            intensity: 1.0,
220            bias: 0.0,
221            normal_bias: 0.0,
222            radius: 1.0,
223            blur_samples: 8,
224            map_size: Vector2::new(512.0, 512.0),
225            matrix: Matrix4::identity(),
226            focus: 1.0,
227            aspect: 1.0,
228            filter_node: None,
229            shadow_node: None,
230            point_depth_texture: None,
231        }
232    }
233
234    /// `light.shadow.map.depthTexture` for a point light: the cube depth
235    /// texture its shadow renders into, made now — `mapSize.width` texels a
236    /// face — if nothing has asked for it yet.
237    ///
238    /// Three's `shadow.map` is created by the shadow node's first setup, and
239    /// `GodraysNode.setup()` reads it then. The port's display nodes are built
240    /// before any frame, so they take the handle here instead and the renderer
241    /// draws into whichever texture this returned. A `mapSize` changed after
242    /// the first call does not resize it.
243    pub fn point_depth_texture(&mut self) -> CubeDepthTexture {
244        let size = self.map_size.x as u32;
245        self.point_depth_texture
246            .get_or_insert_with(|| CubeDepthTexture::new(size))
247            .clone()
248    }
249
250    /// `SpotLightShadow.updateMatrices()`'s projection half: the spot light's
251    /// cone angle and cutoff distance drive the shadow camera.
252    pub(crate) fn update_spot_projection(&mut self, angle: f64, distance: f64) {
253        let fov = RAD2DEG * 2.0 * angle * self.focus;
254        let aspect = (self.map_size.x / self.map_size.y) * self.aspect;
255        let far = if distance != 0.0 {
256            distance
257        } else {
258            self.camera.far()
259        };
260
261        if let ShadowCamera::Perspective(camera) = &mut self.camera {
262            if fov != camera.fov || aspect != camera.aspect || far != camera.far {
263                camera.fov = fov;
264                camera.aspect = aspect;
265                camera.far = far;
266                camera.update_projection_matrix();
267            }
268        }
269    }
270
271    /// `PointLightShadow.updateMatrices( light )`'s matrix half:
272    /// `shadowMatrix.makeTranslation( - lightPositionWorld )` — the shadow
273    /// coordinate is the light-to-fragment vector, and `far = light.distance ||
274    /// camera.far` (the camera far plane the `viewZ` test reads).
275    pub(crate) fn update_point_matrices(&mut self, light_position_world: Vector3, distance: f64) {
276        let far = if distance != 0.0 {
277            distance
278        } else {
279            self.camera.far()
280        };
281        if far != self.camera.far() {
282            self.camera.set_far(far);
283            self.camera.update_projection_matrix();
284        }
285        let mut matrix = Matrix4::identity();
286        matrix.make_translation(
287            -light_position_world.x,
288            -light_position_world.y,
289            -light_position_world.z,
290        );
291        self.matrix = matrix;
292    }
293
294    /// `LightShadow.updateMatrices( light )` — `light.matrixWorld`'s position
295    /// and `light.target.matrixWorld`'s position, already extracted.
296    pub fn update_matrices(&mut self, light_position_world: Vector3, look_target: Vector3) {
297        self.camera.place(light_position_world, &look_target);
298        self.update_matrix();
299    }
300
301    /// `LightShadow._updateMatrix()` with no atlas viewport. Under
302    /// `WebGPUCoordinateSystem` the Z row is the identity, because the
303    /// projection matrix already produces `[0, 1]`.
304    fn update_matrix(&mut self) {
305        let mut proj_screen_matrix = self.camera.projection_matrix();
306        proj_screen_matrix.multiply(&self.camera.matrix_world_inverse());
307
308        let mut shadow_matrix = Matrix4::identity();
309        shadow_matrix.set(
310            0.5, 0.0, 0.0, 0.5, //
311            0.0, 0.5, 0.0, 0.5, //
312            0.0, 0.0, 1.0, 0.0, //
313            0.0, 0.0, 0.0, 1.0,
314        );
315        shadow_matrix.multiply(&proj_screen_matrix);
316
317        self.matrix = shadow_matrix;
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn clone_does_not_share_the_point_depth_texture() {
327        let mut shadow = LightShadow::point();
328        shadow.point_depth_texture();
329        let copy = shadow.clone();
330        assert!(shadow.point_depth_texture.is_some());
331        assert!(copy.point_depth_texture.is_none());
332    }
333}