three_rs/lights/light_object.rs
1//! The `Payload::Light` half of every light: what `AmbientLight`,
2//! `PointLight`, `SpotLight`, `DirectionalLight`, `HemisphereLight` and
3//! `LightProbe` add to `Object3D`.
4//!
5//! One struct covers all six because the renderer's light list is uniform —
6//! `LightsNode.setupLights()` switches on the light's type, which `kind`
7//! records.
8
9use super::{Light, LightShadow};
10use crate::core::{Object3D, ObjectRef};
11use crate::math::{Color, Matrix4, SphericalHarmonics3, Vector3};
12use crate::objects::Payload;
13
14/// Which `Light` subclass this is. `LightsNode` sorts and sets up lights by
15/// type, and the node graph differs per type.
16#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
17#[non_exhaustive]
18pub enum LightKind {
19 /// `AmbientLight`.
20 Ambient,
21 /// `PointLight`.
22 Point,
23 /// `SpotLight`.
24 Spot,
25 /// `DirectionalLight`.
26 Directional,
27 /// `HemisphereLight`.
28 Hemisphere,
29 /// `LightProbe` — irradiance from nine spherical-harmonic coefficients,
30 /// added to `irradiance` like an ambient light and never a direct term.
31 Probe,
32}
33
34/// `class <X>Light extends Light extends Object3D`, minus the `Object3D` half
35/// (which is the scene-graph [`ObjectRef`] carrying this as a [`Payload`]).
36pub struct LightObject {
37 /// The `color`/`intensity` state common to every light kind.
38 pub light: Light,
39 /// Which `Light` subclass this is.
40 pub kind: LightKind,
41 /// `PointLight.distance` / `SpotLight.distance` — the cutoff distance, `0`
42 /// meaning no cutoff. The shader calls it `cutoffDistance`.
43 pub distance: f64,
44 /// `PointLight.decay` / `SpotLight.decay`, default 2.
45 pub decay: f64,
46 /// `SpotLight.angle`, in radians.
47 pub angle: f64,
48 /// `SpotLight.penumbra`.
49 pub penumbra: f64,
50 /// `HemisphereLight.groundColor`.
51 pub ground_color: Color,
52 /// `LightProbe.sh` — the probe's irradiance as order-2 spherical
53 /// harmonics. All zero, and unread, on every other kind.
54 pub sh: SphericalHarmonics3,
55 /// `SpotLight.target` / `DirectionalLight.target` — an `Object3D` at the
56 /// origin by default, never added to the scene, so its `matrixWorld` is
57 /// just its local matrix.
58 pub target: Option<ObjectRef>,
59 /// `Object3D.castShadow`.
60 pub cast_shadow: bool,
61 /// `light.shadow` — present for the shadow-casting light types. Boxed
62 /// because the shadow owns a camera, which owns an `Object3D`, which can
63 /// own a light.
64 pub shadow: Option<Box<LightShadow>>,
65}
66
67/// `SpotLight.copy()` / `DirectionalLight.copy()` clone the target rather
68/// than sharing it, because the target is a real `Object3D` with its own
69/// transform.
70impl Clone for LightObject {
71 fn clone(&self) -> Self {
72 Self {
73 light: self.light.clone(),
74 kind: self.kind,
75 distance: self.distance,
76 decay: self.decay,
77 angle: self.angle,
78 penumbra: self.penumbra,
79 ground_color: self.ground_color,
80 sh: self.sh,
81 target: self.target.as_ref().map(|t| t.borrow().clone().into_node()),
82 cast_shadow: self.cast_shadow,
83 shadow: self.shadow.clone(),
84 }
85 }
86}
87
88impl LightObject {
89 fn base(kind: LightKind, color: Color, intensity: f64) -> Self {
90 Self {
91 light: Light::new(color, intensity),
92 kind,
93 distance: 0.0,
94 decay: 2.0,
95 angle: std::f64::consts::FRAC_PI_3,
96 penumbra: 0.0,
97 ground_color: Color::new(0.0, 0.0, 0.0),
98 sh: SphericalHarmonics3::default(),
99 target: None,
100 cast_shadow: false,
101 shadow: None,
102 }
103 }
104
105 /// `light.color.clone().multiplyScalar( light.intensity )` —
106 /// `AnalyticLightNode.update()`'s single `vec3` colour uniform.
107 pub(crate) fn color_intensity(&self) -> Color {
108 let c = self.light.color;
109 let i = self.light.intensity;
110 Color::new(c.r * i, c.g * i, c.b * i)
111 }
112
113 /// `LightProbeNode.update()`: each coefficient times the intensity,
114 /// padded to the `vec4` a `uniformArray()` element occupies.
115 pub(crate) fn sh_intensity(&self) -> [[f32; 4]; 9] {
116 let i = self.light.intensity;
117 self.sh
118 .coefficients
119 .map(|c| [(c.x * i) as f32, (c.y * i) as f32, (c.z * i) as f32, 0.0])
120 }
121
122 /// `cos( light.angle )` — `SpotLightNode.update()`.
123 pub(crate) fn cone_cos(&self) -> f64 {
124 self.angle.cos()
125 }
126
127 /// `cos( light.angle * ( 1 - light.penumbra ) )`.
128 pub(crate) fn penumbra_cos(&self) -> f64 {
129 (self.angle * (1.0 - self.penumbra)).cos()
130 }
131
132 /// The world-space position the lighting uniforms are built from
133 /// (`Object3D.matrixWorld`'s translation). The matrix lives on the node, so
134 /// the caller passes it in.
135 pub(crate) fn world_position(matrix_world: &Matrix4) -> Vector3 {
136 let mut v = Vector3::default();
137 v.set_from_matrix_position(matrix_world);
138 v
139 }
140
141 /// `HemisphereLightNode.update()`: the ground colour carries the intensity
142 /// just as the sky colour does.
143 pub(crate) fn ground_color_intensity(&self) -> Color {
144 let c = self.ground_color;
145 let i = self.light.intensity;
146 Color::new(c.r * i, c.g * i, c.b * i)
147 }
148
149 /// `set power( power )` — `PointLight` only.
150 pub fn set_power(&mut self, power: f64) {
151 self.light.intensity = power / (4.0 * std::f64::consts::PI);
152 }
153
154 /// `get power()` — luminous power in lumens, `intensity * 4π`.
155 pub fn power(&self) -> f64 {
156 self.light.intensity * 4.0 * std::f64::consts::PI
157 }
158
159 /// `light.target.matrixWorld`'s translation, or the origin when the light
160 /// has no target.
161 pub(crate) fn target_world_position(&self) -> Vector3 {
162 match &self.target {
163 Some(target) => {
164 let m = target.borrow().matrix_world;
165 Self::world_position(&m)
166 }
167 None => Vector3::new(0.0, 0.0, 0.0),
168 }
169 }
170}
171
172fn into_node(object_type: &'static str, light: LightObject) -> ObjectRef {
173 let object = Object3D {
174 object_type,
175 is_light: true,
176 payload: Payload::Light(light),
177 ..Default::default()
178 };
179 object.into_node()
180}
181
182/// `class AmbientLight extends Light` — `new AmbientLight( color, intensity )`.
183pub struct AmbientLight;
184
185impl AmbientLight {
186 /// `new AmbientLight( color, intensity )`, as a scene-graph [`ObjectRef`]. An
187 /// ambient light adds no shadow and no direction: `LightsNode` reads only
188 /// its colour and intensity.
189 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
190 pub fn new(color: Color, intensity: f64) -> ObjectRef {
191 into_node(
192 "AmbientLight",
193 LightObject::base(LightKind::Ambient, color, intensity),
194 )
195 }
196}
197
198/// `class PointLight extends Light`.
199pub struct PointLight;
200
201impl PointLight {
202 /// `new PointLight( color, intensity, distance = 0, decay = 2 )`, as a
203 /// scene-graph [`ObjectRef`]. `object.is_light` is what
204 /// `Renderer._projectObject()` branches on, so the node is collected into
205 /// `RenderList.lights` and never drawn — while anything added under it (the
206 /// bulb sphere of `webgpu_lights_phong`) is an ordinary child and draws
207 /// through the walk.
208 ///
209 /// `this.shadow = new PointLightShadow()` — present whether or not the
210 /// light casts; `Object3D.castShadow` is the switch.
211 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
212 pub fn new(color: Color, intensity: f64, distance: f64) -> ObjectRef {
213 let mut light = LightObject::base(LightKind::Point, color, intensity);
214 light.distance = distance;
215 light.shadow = Some(Box::new(LightShadow::point()));
216 into_node("PointLight", light)
217 }
218}
219
220/// `class HemisphereLight extends Light`.
221pub struct HemisphereLight;
222
223impl HemisphereLight {
224 /// `new HemisphereLight( skyColor, groundColor, intensity = 1 )`.
225 ///
226 /// The constructor does one thing beyond `Light`'s: `this.position.copy(
227 /// Object3D.DEFAULT_UP )`. That matters, because `HemisphereLightNode` takes
228 /// its direction from `lightPosition( light ).normalize()` — at the origin
229 /// the normalize would be undefined.
230 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
231 pub fn new(sky_color: Color, ground_color: Color, intensity: f64) -> ObjectRef {
232 let mut light = LightObject::base(LightKind::Hemisphere, sky_color, intensity);
233 light.ground_color = ground_color;
234 let node = into_node("HemisphereLight", light);
235 node.borrow_mut().position.set(0.0, 1.0, 0.0);
236 node
237 }
238}
239
240/// `class SpotLight extends Light`.
241pub struct SpotLight;
242
243impl SpotLight {
244 /// `new SpotLight( color, intensity )` — `distance 0`, `angle π/3`,
245 /// `penumbra 0`, `decay 2`, a target at the origin and a
246 /// `SpotLightShadow`.
247 ///
248 /// Like `HemisphereLight`, the constructor sets `this.position.copy(
249 /// Object3D.DEFAULT_UP )`. A page that never moves the light sees it:
250 /// `webgpu_backdrop` hangs its spot light on the camera, so the light
251 /// sits one unit above the eye and the highlights sit high on the spheres.
252 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
253 pub fn new(color: Color, intensity: f64) -> ObjectRef {
254 let mut light = LightObject::base(LightKind::Spot, color, intensity);
255 light.target = Some(Object3D::new_node());
256 light.shadow = Some(Box::new(LightShadow::spot()));
257 let node = into_node("SpotLight", light);
258 node.borrow_mut().position.set(0.0, 1.0, 0.0);
259 node
260 }
261}
262
263/// `class DirectionalLight extends Light`.
264pub struct DirectionalLight;
265
266impl DirectionalLight {
267 /// `new DirectionalLight( color, intensity )` — a target at the origin,
268 /// a `DirectionalLightShadow`, and `this.position.copy(
269 /// Object3D.DEFAULT_UP )`, so an unmoved light shines straight down.
270 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
271 pub fn new(color: Color, intensity: f64) -> ObjectRef {
272 let mut light = LightObject::base(LightKind::Directional, color, intensity);
273 light.target = Some(Object3D::new_node());
274 light.shadow = Some(Box::new(LightShadow::directional()));
275 let node = into_node("DirectionalLight", light);
276 node.borrow_mut().position.set(0.0, 1.0, 0.0);
277 node
278 }
279}
280
281/// `class LightProbe extends Light`.
282///
283/// A probe holds the irradiance of an environment as nine spherical-harmonic
284/// coefficients (see [`SphericalHarmonics3`]) and lights a material by
285/// `LightProbeNode`: `irradiance += getShIrradianceAt( normalWorld, sh *
286/// intensity )`. It has no direction, no shadow, and its position is not
287/// read by the lighting — only `LightProbeHelper` honours it.
288pub struct LightProbe;
289
290impl LightProbe {
291 /// `new LightProbe( sh = new SphericalHarmonics3(), intensity = 1 )`. The
292 /// colour is `Light`'s default, white; `LightProbeNode` never reads it.
293 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
294 pub fn new(sh: SphericalHarmonics3, intensity: f64) -> ObjectRef {
295 let mut light = LightObject::base(LightKind::Probe, Color::default(), intensity);
296 light.sh = sh;
297 into_node("LightProbe", light)
298 }
299
300 /// `lightProbe.copy( source )`'s `Light` half: the colour, the intensity
301 /// and `sh.copy( source.sh )`.
302 ///
303 /// Three's `copy()` also runs `Object3D.copy()`, which the port has no
304 /// general form of; `webgpu_lightprobe` copies a probe straight from
305 /// `LightProbeGenerator`, which sits at the origin untransformed, and then
306 /// sets the position itself, so the transform is left as it is here.
307 ///
308 /// # Panics
309 ///
310 /// If either node is not a light.
311 pub fn copy(target: &ObjectRef, source: &ObjectRef) {
312 let (light, sh) = {
313 let source = source.borrow();
314 let source = source
315 .light()
316 .expect("three-rs: LightProbe::copy reads a light");
317 (source.light.clone(), source.sh)
318 };
319 let mut target = target.borrow_mut();
320 let target = target
321 .light_mut()
322 .expect("three-rs: LightProbe::copy writes a light");
323 target.light = light;
324 target.sh = sh;
325 }
326}