Skip to main content

sgl_3d/content/
lighting.rs

1//! The frame's lights and authored look, as the game describes them in
2//! `FrameInput`: directional lights, the hemisphere fill, the environment
3//! (a map or a procedural sky) with its lighting and backdrop, and the mist.
4//! Metres, radians about +Y and linear RGB. Point and spot lights are scene
5//! content (`Light`); SGL3D packs all of these into its frame data itself.
6use super::identity::EnvironmentId;
7use glam::Vec3;
8
9/// What surrounds the frame: what its backdrop shows and its environment light comes from.
10#[derive(Clone, Copy, Debug, Default, PartialEq)]
11pub enum FrameEnvironment {
12    /// No environment: black.
13    #[default]
14    None,
15    /// One of the scene's environment maps; an ended identity is `None`.
16    Map(EnvironmentId),
17    /// A procedural sky lit by `FrameInput::directional_lights`.
18    Sky(Sky),
19}
20
21/// A procedural, physically based sky (Hillaire 2020, as Bevy's atmosphere
22/// ports it): the air of an Earth-like planet whose surface lies
23/// `ground_height` below the camera, lit by the frame's directional lights,
24/// whose `illuminance` and `color` are then their light above the air and
25/// whose `angular_diameter` sizes their discs. SGL3D owns the model: the
26/// planet's radii, the media's coefficients and profiles, the tables'
27/// sizes and the sample counts. The game says what and how much: the
28/// densities as scales of Earth's, the ground's albedo and the discs.
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct Sky {
31    /// World Y of the planet's surface below the camera, in the scene's render frame, metres.
32    pub ground_height: f32,
33    /// Density of the air's molecules (Rayleigh), as a scale of Earth's. Default 1.
34    pub rayleigh: f32,
35    /// Density of haze (Mie aerosols), as a scale of a clear Earth day's. Default 1.
36    pub mie: f32,
37    /// Density of ozone, as a scale of Earth's. Default 1.
38    pub ozone: f32,
39    /// Linear RGB albedo of the planet's ground, 0..=1. Default 0.3.
40    pub ground_albedo: [f32; 3],
41    /// Scales each directional light's disc in the backdrop; 0 draws none. Default 1.
42    pub sun_disc: f32,
43    /// How much air each metre of view distance counts as: 1 is the planet's, 0 no aerial
44    /// perspective, above 1 hazier (a small world reads as a large one). Default 1.
45    pub aerial_perspective: f32,
46}
47
48impl Default for Sky {
49    /// Earth, as Wicked Engine and Hillaire's sample hold it: the ground at
50    /// world Y 0, clear air of Earth's densities over ground of albedo 0.3,
51    /// the lights' discs at their own size and radiance, and the air's aerial
52    /// perspective at its own distance.
53    fn default() -> Self {
54        Self {
55            ground_height: 0.,
56            rayleigh: 1.,
57            mie: 1.,
58            ozone: 1.,
59            ground_albedo: [0.3; 3],
60            sun_disc: 1.,
61            aerial_perspective: 1.,
62        }
63    }
64}
65
66impl Sky {
67    /// As the sky stage takes it: a negative or non-finite density, disc
68    /// scale or aerial perspective is 0, each albedo channel is clamped to 0..=1 (NaN as 0), and
69    /// a non-finite ground height is 0.
70    pub(crate) fn resolved(&self) -> Self {
71        let scale = |value: f32| {
72            if value.is_finite() && value > 0. {
73                value
74            } else {
75                0.
76            }
77        };
78        let albedo = |value: f32| {
79            if value.is_nan() {
80                0.
81            } else {
82                value.clamp(0., 1.)
83            }
84        };
85        Self {
86            ground_height: if self.ground_height.is_finite() {
87                self.ground_height
88            } else {
89                0.
90            },
91            rayleigh: scale(self.rayleigh),
92            mie: scale(self.mie),
93            ozone: scale(self.ozone),
94            ground_albedo: self.ground_albedo.map(albedo),
95            sun_disc: scale(self.sun_disc),
96            aerial_perspective: scale(self.aerial_perspective),
97        }
98    }
99}
100
101/// A light at infinity, such as the sun or the moon (Bevy's
102/// `DirectionalLight`, Godot's `DirectionalLight3D`, Filament's directional
103/// light).
104#[derive(Clone, Copy, Debug, PartialEq)]
105pub struct DirectionalLight {
106    /// Where the light shines, from the light toward what it lights; any
107    /// nonzero length. A zero or non-finite direction is no light.
108    pub direction: Vec3,
109    /// Linear RGB, nonnegative.
110    pub color: [f32; 3],
111    /// Illuminance at normal incidence (lux), on the scale of scene lights'
112    /// candela; zero turns the light off.
113    pub illuminance: f32,
114    /// The light's shadow, `None` for none. One directional light has a
115    /// shadow: the first that is on and has one.
116    pub shadow: Option<DirectionalShadow>,
117    /// Scales the light it scatters in the volumetric fog, nonnegative
118    /// (Godot's `light_volumetric_fog_energy`): 1 is physical, 2 doubles
119    /// it, and at most 0.001 (Godot's cutoff) leaves the light out of the
120    /// fog, which then skips its attenuation and shadow lookup. Surfaces
121    /// take the light alike whatever its value, and its shadow is still
122    /// drawn for them. A negative or non-finite value leaves it out too.
123    pub fog_energy: f32,
124    /// How dark its shadow is, 0..=1 (Godot's `shadow_opacity`), on surfaces
125    /// and in the volumetric fog alike: 1 hides all of its light behind its
126    /// casters, 0.4 lets 0.6 of it through, and at most 0.001 (Godot's
127    /// cutoff) draws no shadow and skips the lookup. Above 1 is 1; a
128    /// negative or non-finite value draws none.
129    pub shadow_opacity: f32,
130    /// The angle the light's disc spans in the sky, in radians: the sun's,
131    /// about 0.00925 (0.53°), is the default. Its specular highlights spread
132    /// over the disc's reflection, so the sun on water shows a disc, and
133    /// ray-traced shadows' and the dynamic GI volume's visibility rays each
134    /// leave toward the light in a direction within the disc, so the shadow
135    /// softens with the distance from its caster; 0 is a point's highlight
136    /// and a hard shadow. Clamped to 0..=π/2 (NaN as 0).
137    pub angular_diameter: f32,
138}
139
140impl DirectionalLight {
141    /// The sun's angular diameter seen from the Earth, in radians (0.53°).
142    pub const SUN_ANGULAR_DIAMETER: f32 = 0.53 * std::f32::consts::PI / 180.;
143}
144
145impl Default for DirectionalLight {
146    /// Godot's `DirectionalLight3D` defaults: white, shining along -Z (as
147    /// Godot's and Bevy's untransformed lights do), of π lux (its light
148    /// energy of 1, which its renderer scales by π), with no shadow (at
149    /// opacity 1 when it has one) and fog energy 1, and the sun's angular
150    /// diameter. Set what differs and take the rest with
151    /// `..Default::default()`.
152    fn default() -> Self {
153        Self {
154            direction: Vec3::NEG_Z,
155            color: [1.; 3],
156            illuminance: std::f32::consts::PI,
157            shadow: None,
158            fog_energy: 1.,
159            shadow_opacity: 1.,
160            angular_diameter: Self::SUN_ANGULAR_DIAMETER,
161        }
162    }
163}
164
165/// A directional light's cascaded shadow, which SGL3D splits and fits from
166/// the camera (Godot's `DirectionalLight3D` splits, Bevy's cascade fit).
167/// The camera's view depth from its near plane to `distance` is split into
168/// `cascades`, each a shadow map of the same size covering a farther and
169/// larger part of the view, so texels near the camera are small. SGL3D
170/// places the splits as Godot does by default: each cascade but the last
171/// ends 0.1, 0.2 and 0.5 of the way from the near plane to `distance`, and
172/// the last at `distance`.
173#[derive(Clone, Copy, Debug, PartialEq)]
174pub struct DirectionalShadow {
175    /// The farthest view depth that is shadowed, in metres (Godot's
176    /// `directional_shadow_max_distance`, Bevy's `maximum_distance`), at
177    /// least 1 mm beyond the camera's near plane, as Godot keeps it, and at
178    /// most 8192 m, the top of Godot's `directional_shadow_max_distance`
179    /// range (NaN as 0). `DirectionalLight::shadow` as `None` casts
180    /// no shadow.
181    pub distance: f32,
182    /// How many cascades split `distance`, 1 to 4; others are clamped.
183    pub cascades: u32,
184}
185
186impl DirectionalShadow {
187    /// Bevy's `CascadeShadowConfigBuilder` defaults (150 m and 4 cascades),
188    /// as `Default::default()` returns them, for a `const` to build from:
189    ///
190    /// ```
191    /// use sgl_3d::DirectionalShadow;
192    /// const COURSE_SHADOW: DirectionalShadow = DirectionalShadow {
193    ///     distance: 200.,
194    ///     ..DirectionalShadow::DEFAULT
195    /// };
196    /// ```
197    pub const DEFAULT: Self = Self {
198        distance: 150.,
199        cascades: 4,
200    };
201}
202
203impl Default for DirectionalShadow {
204    /// [`DirectionalShadow::DEFAULT`]. Set what differs and take the rest
205    /// with `..Default::default()`.
206    fn default() -> Self {
207        Self::DEFAULT
208    }
209}
210
211impl DirectionalLight {
212    /// The light reaches anything: positive illuminance and a direction
213    /// that normalises. A light that is off is packed as no light and casts
214    /// no shadow.
215    pub(crate) fn is_on(&self) -> bool {
216        self.illuminance > 0. && self.direction.try_normalize().is_some()
217    }
218}
219
220/// A sky and ground fill (Three.js's `HemisphereLight`): a surface facing
221/// straight up receives `sky_color` and one facing straight down
222/// `ground_color`, blended by the normal's height, times `intensity`, as
223/// irradiance on the directional lights' scale. It lights diffuse surfaces
224/// only.
225#[derive(Clone, Copy, Debug, Default, PartialEq)]
226pub struct HemisphereLight {
227    /// Linear RGB, nonnegative.
228    pub sky_color: [f32; 3],
229    /// Linear RGB, nonnegative.
230    pub ground_color: [f32; 3],
231    /// Nonnegative; zero turns the fill off.
232    pub intensity: f32,
233}
234
235/// The frame environment's map turned about +Y and scaled where it lights
236/// one lobe: `FrameInput::diffuse_environment` or `reflection_environment`.
237/// No yaw turns a procedural sky, which its lights place.
238/// Bevy's `EnvironmentMapLight` and Filament's `IndirectLight` carry the same
239/// rotation and intensity but scale diffuse and specular together.
240#[derive(Clone, Copy, Debug, PartialEq)]
241pub struct EnvironmentLight {
242    /// Radians about +Y.
243    pub yaw: f32,
244    /// Nonnegative scale of the map's radiance.
245    pub intensity: f32,
246}
247
248impl Default for EnvironmentLight {
249    /// The map unturned at its own radiance (yaw 0, intensity 1), as
250    /// Three.js r185's `Scene.environmentRotation` and
251    /// `environmentIntensity`.
252    fn default() -> Self {
253        Self {
254            yaw: 0.,
255            intensity: 1.,
256        }
257    }
258}
259
260/// What the camera sees where no surface is (Godot's background mode,
261/// Filament's `Skybox`).
262#[derive(Clone, Copy, Debug, PartialEq)]
263pub enum Backdrop {
264    /// The frame environment's panorama (Bevy's `Skybox`), turned `yaw`
265    /// radians about +Y, its radiance scaled by `brightness`; or its
266    /// procedural sky, scaled by `brightness`, which `yaw` does not turn.
267    Environment { yaw: f32, brightness: f32 },
268    /// One linear RGB colour.
269    Color([f32; 3]),
270}
271
272/// The look of the mist billboards at the scene's mist positions
273/// (`Scene::update_mist`), shaded by animated noise.
274#[derive(Clone, Copy, Debug, PartialEq)]
275pub struct Mist {
276    /// Linear RGB where the noise is thin.
277    pub thin_color: [f32; 3],
278    /// Linear RGB where the noise is dense.
279    pub dense_color: [f32; 3],
280    /// The densest noise's opacity, 0..=1; zero hides the mist.
281    pub opacity: f32,
282    /// Each billboard's width in metres.
283    pub width: f32,
284    /// Each billboard's height in metres.
285    pub height: f32,
286    /// How fast and which way the noise moves across each billboard, in
287    /// billboard widths per second rightward and heights per second upward
288    /// on screen.
289    pub drift: [f32; 2],
290}
291
292impl Default for Mist {
293    /// Hidden: black, opacity 0, on 1 m square billboards, drifting slowly
294    /// up and to the left. Set the colours and opacity to show it.
295    fn default() -> Self {
296        Self {
297            thin_color: [0.; 3],
298            dense_color: [0.; 3],
299            opacity: 0.,
300            width: 1.,
301            height: 1.,
302            // SGL3D's own, from Hyperdrive: its noise, 7 by 3 cells across
303            // a billboard (mist.wgsl), moved -0.025 and 0.035 cells a second.
304            drift: [-0.025 / 7., 0.035 / 3.],
305        }
306    }
307}