euv-core 0.56.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use super::*;

/// Default clear-day Earth atmosphere for `PhysicalSky3D`.
impl Default for PhysicalSky3D {
    /// Creates a physically parameterized Earth sea-level atmospheric sky model.
    ///
    /// # Returns
    ///
    /// - `Self` - Default Earth `PhysicalSky3D`.
    fn default() -> Self {
        Self {
            planet_radius_m: EARTH_PLANET_RADIUS_M,
            atmosphere_radius_m: EARTH_ATMOSPHERE_RADIUS_M,
            observer_altitude_m: 100.0,
            rayleigh_scale_height_m: EARTH_RAYLEIGH_SCALE_HEIGHT_M,
            mie_scale_height_m: EARTH_MIE_SCALE_HEIGHT_M,
            mie_anisotropy_g: 0.78,
            ozone_strength: 1.0,
            solar_irradiance: DEFAULT_SOLAR_IRRADIANCE,
            sun_angular_radius_rad: DEFAULT_SUN_ANGULAR_RADIUS_RAD,
            ground_albedo: Vec3::new(0.22, 0.24, 0.28),
            starfield_intensity: 0.35,
            primary_steps: 14,
            light_steps: 6,
        }
    }
}

/// Physical single-scattering Rayleigh + Mie + Ozone evaluation, solar transmittance, and aerial perspective for `PhysicalSky3D`.
impl PhysicalSky3D {
    /// Creates a default Earth physical atmospheric sky model.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `PhysicalSky3D`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Computes instantaneous Rayleigh, Mie, and Ozone relative densities `(rho_r, rho_m, rho_o)` at `altitude_m`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Altitude above planet surface in meters.
    ///
    /// # Returns
    ///
    /// - `(f32, f32, f32)` - Relative densities `(rayleigh, mie, ozone)`.
    #[must_use]
    fn sample_densities(&self, altitude_m: f32) -> (f32, f32, f32) {
        let alt: f32 = altitude_m.max(0.0);
        let rho_r: f32 = (-alt / self.get_rayleigh_scale_height_m().max(100.0)).exp();
        let rho_m: f32 = (-alt / self.get_mie_scale_height_m().max(50.0)).exp();
        let ozone_dist: f32 = (alt - EARTH_OZONE_CENTER_ALT_M).abs() / EARTH_OZONE_HALF_WIDTH_M;
        let rho_o: f32 = (1.0 - ozone_dist).clamp(0.0, 1.0) * self.get_ozone_strength().max(0.0);
        (rho_r, rho_m, rho_o)
    }

    /// Integrates atmospheric optical depths `(tau_r, tau_m, tau_o)` along a ray segment `[0, segment_len]`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Ray origin relative to planet center.
    /// - `Vec3` - Unit ray direction.
    /// - `f32` - Total march distance in meters.
    /// - `usize` - Number of midpoint integration steps.
    ///
    /// # Returns
    ///
    /// - `(f32, f32, f32)` - Accumulated optical depths `(tau_r, tau_m, tau_o)`.
    #[must_use]
    fn optical_depth_segment(
        &self,
        origin: Vec3,
        dir: Vec3,
        segment_len: f32,
        steps: usize,
    ) -> (f32, f32, f32) {
        let count: usize = steps.max(1);
        let step_len: f32 = segment_len / (count as f32);
        let planet_r: f32 = self.get_planet_radius_m();
        let mut od_r: f32 = 0.0;
        let mut od_m: f32 = 0.0;
        let mut od_o: f32 = 0.0;
        for idx in 0..count {
            let t: f32 = ((idx as f32) + 0.5) * step_len;
            let pos: Vec3 = origin.add(dir.scale(t));
            let alt: f32 = pos.length() - planet_r;
            let (dr, dm, do3): (f32, f32, f32) = self.sample_densities(alt);
            od_r += dr * step_len;
            od_m += dm * step_len;
            od_o += do3 * step_len;
        }
        (od_r, od_m, od_o)
    }

    /// Converts Rayleigh, Mie, and Ozone optical depths into RGB transmittance `exp(-tau)`.
    ///
    /// # Arguments
    ///
    /// - `(f32, f32, f32)` - Optical depths `(tau_r, tau_m, tau_o)`.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Spectral RGB atmospheric transmittance in `[0.0, 1.0]`.
    #[must_use]
    fn transmittance_from_optical_depth(od: (f32, f32, f32)) -> Vec3 {
        let (od_r, od_m, od_o): (f32, f32, f32) = od;
        let tr: f32 = (-(RAYLEIGH_SCATTER_COEFF[0] * od_r
            + MIE_EXTINCTION_COEFF * od_m
            + OZONE_ABSORPTION_COEFF[0] * od_o))
            .exp()
            .clamp(0.0, 1.0);
        let tg: f32 = (-(RAYLEIGH_SCATTER_COEFF[1] * od_r
            + MIE_EXTINCTION_COEFF * od_m
            + OZONE_ABSORPTION_COEFF[1] * od_o))
            .exp()
            .clamp(0.0, 1.0);
        let tb: f32 = (-(RAYLEIGH_SCATTER_COEFF[2] * od_r
            + MIE_EXTINCTION_COEFF * od_m
            + OZONE_ABSORPTION_COEFF[2] * od_o))
            .exp()
            .clamp(0.0, 1.0);
        Vec3::new(tr, tg, tb)
    }

    /// Evaluates direct solar atmospheric transmittance from observer altitude along `sun_dir`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Unit direction pointing toward the sun.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear RGB solar transmittance in `[0.0, 1.0]` (`zero` when eclipsed below Earth).
    #[must_use]
    pub fn sun_transmittance(&self, sun_dir: Vec3) -> Vec3 {
        let s_dir: Vec3 = sun_dir.normalize();
        let planet_r: f32 = self.get_planet_radius_m();
        let atmo_r: f32 = self.get_atmosphere_radius_m().max(planet_r + 1_000.0);
        let origin: Vec3 = Vec3::new(0.0, planet_r + self.get_observer_altitude_m().max(1.0), 0.0);
        if let Some((hit_near, _)) = ray_sphere_intersect(origin, s_dir, planet_r)
            && hit_near > 0.0
        {
            return Vec3::zero();
        }
        let Some((_, atmo_far)) = ray_sphere_intersect(origin, s_dir, atmo_r) else {
            return Vec3::zero();
        };
        if atmo_far <= 0.0 {
            return Vec3::zero();
        }
        let od: (f32, f32, f32) = self.optical_depth_segment(
            origin,
            s_dir,
            atmo_far,
            self.get_light_steps().clamp(2, 16),
        );
        Self::transmittance_from_optical_depth(od)
    }

    /// Evaluates single-scattering atmospheric radiance `(inscatter, transmittance)` over `[0, max_dist]`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Unit view ray direction.
    /// - `Vec3` - Unit direction pointing toward the sun.
    /// - `f32` - Maximum integration distance in meters (`f32::INFINITY` for sky dome).
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3)` - `(in_scattered_radiance, ray_transmittance)`.
    #[must_use]
    fn integrate_atmosphere(&self, view_dir: Vec3, sun_dir: Vec3, max_dist: f32) -> (Vec3, Vec3) {
        let v_dir: Vec3 = view_dir.normalize();
        let s_dir: Vec3 = sun_dir.normalize();
        let planet_r: f32 = self.get_planet_radius_m();
        let atmo_r: f32 = self.get_atmosphere_radius_m().max(planet_r + 1_000.0);
        let origin: Vec3 = Vec3::new(0.0, planet_r + self.get_observer_altitude_m().max(1.0), 0.0);
        let Some((_, atmo_far)) = ray_sphere_intersect(origin, v_dir, atmo_r) else {
            return (Vec3::zero(), Vec3::splat(1.0));
        };
        if atmo_far <= 0.0 {
            return (Vec3::zero(), Vec3::splat(1.0));
        }
        let mut march_dist: f32 = atmo_far.min(max_dist.max(0.0));
        if let Some((ground_near, _)) = ray_sphere_intersect(origin, v_dir, planet_r)
            && ground_near > 0.0
        {
            march_dist = march_dist.min(ground_near);
        }
        if march_dist <= 1.0e-3 {
            return (Vec3::zero(), Vec3::splat(1.0));
        }
        let steps: usize = self.get_primary_steps().clamp(4, 32);
        let light_steps: usize = self.get_light_steps().clamp(2, 12);
        let ds: f32 = march_dist / (steps as f32);
        let mu: f32 = v_dir.dot(s_dir).clamp(-1.0, 1.0);
        let phase_r: f32 = rayleigh_phase(mu);
        let phase_m: f32 = cornette_shanks_mie_phase(mu, self.get_mie_anisotropy_g());
        let mut view_od_r: f32 = 0.0;
        let mut view_od_m: f32 = 0.0;
        let mut view_od_o: f32 = 0.0;
        let mut sum_r: Vec3 = Vec3::zero();
        let mut sum_m: Vec3 = Vec3::zero();
        for idx in 0..steps {
            let t: f32 = ((idx as f32) + 0.5) * ds;
            let sample_pos: Vec3 = origin.add(v_dir.scale(t));
            let alt: f32 = sample_pos.length() - planet_r;
            let (dr, dm, do3): (f32, f32, f32) = self.sample_densities(alt);
            view_od_r += dr * ds;
            view_od_m += dm * ds;
            view_od_o += do3 * ds;
            let planet_shadowed: bool = match ray_sphere_intersect(sample_pos, s_dir, planet_r) {
                Some((hit_near, _)) => hit_near > 0.0,
                None => false,
            };
            if planet_shadowed {
                continue;
            }
            let Some((_, sun_atmo_far)) = ray_sphere_intersect(sample_pos, s_dir, atmo_r) else {
                continue;
            };
            if sun_atmo_far <= 0.0 {
                continue;
            }
            let (s_od_r, s_od_m, s_od_o): (f32, f32, f32) =
                self.optical_depth_segment(sample_pos, s_dir, sun_atmo_far, light_steps);
            let total_t: Vec3 = Self::transmittance_from_optical_depth((
                view_od_r + s_od_r,
                view_od_m + s_od_m,
                view_od_o + s_od_o,
            ));
            sum_r = sum_r.add(total_t.scale(dr * ds));
            sum_m = sum_m.add(total_t.scale(dm * ds));
        }
        let beta_r: Vec3 = Vec3::new(
            RAYLEIGH_SCATTER_COEFF[0],
            RAYLEIGH_SCATTER_COEFF[1],
            RAYLEIGH_SCATTER_COEFF[2],
        );
        let solar: f32 = self.get_solar_irradiance().max(0.0);
        let scatter_r: Vec3 = sum_r.mul(beta_r).scale(phase_r);
        let scatter_m: Vec3 = sum_m.scale(MIE_SCATTER_COEFF * phase_m);
        let inscatter: Vec3 = scatter_r.add(scatter_m).scale(solar);
        let view_t: Vec3 =
            Self::transmittance_from_optical_depth((view_od_r, view_od_m, view_od_o));
        (inscatter, view_t)
    }

    /// Evaluates full physical atmospheric sky radiance along `view_dir` for solar direction `sun_dir` (including Rayleigh/Mie/Ozone, crisp solar disc, twilight, and night starfield).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Unit sky lookup direction.
    /// - `Vec3` - Unit direction pointing toward the sun.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Strictly finite, non-negative linear HDR RGB sky radiance.
    #[must_use]
    pub fn evaluate_sky_radiance(&self, view_dir: Vec3, sun_dir: Vec3) -> Vec3 {
        let v_dir: Vec3 = view_dir.normalize();
        let s_dir: Vec3 = sun_dir.normalize();
        let sample_dir: Vec3 = if v_dir.get_y() < 0.0 {
            Vec3::new(v_dir.get_x(), 0.02, v_dir.get_z()).normalize()
        } else {
            v_dir
        };
        let (mut radiance, view_t): (Vec3, Vec3) =
            self.integrate_atmosphere(sample_dir, s_dir, f32::INFINITY);
        let sun_elev: f32 = s_dir.get_y();
        let day_factor: f32 = ((sun_elev + 0.14) / 0.34).clamp(0.0, 1.0);
        let night_factor: f32 = 1.0 - day_factor;
        if v_dir.get_y() >= 0.0 {
            let cos_sun: f32 = v_dir.dot(s_dir).clamp(-1.0, 1.0);
            let disc_cos: f32 = self.get_sun_angular_radius_rad().max(0.001).cos();
            let halo_cos: f32 = (self.get_sun_angular_radius_rad().max(0.001) * 2.5).cos();
            if sun_elev > -0.02 && cos_sun >= halo_cos {
                let disc_t: f32 =
                    ((cos_sun - halo_cos) / (disc_cos - halo_cos).max(1.0e-6)).clamp(0.0, 1.0);
                let disc_smooth: f32 = disc_t * disc_t * (3.0 - 2.0 * disc_t);
                let disc_rad: Vec3 = view_t.scale(self.get_solar_irradiance() * 6.0 * disc_smooth);
                radiance = radiance.add(disc_rad);
            }
            if night_factor > 1.0e-4 {
                let sky_t: f32 = v_dir.get_y().clamp(0.0, 1.0);
                let night_horizon: Vec3 = Vec3::new(0.0045, 0.0075, 0.0155);
                let night_zenith: Vec3 = Vec3::new(0.0018, 0.0036, 0.0095);
                let airglow: Vec3 = night_horizon.lerp(night_zenith, sky_t).scale(night_factor);
                let moon_dir: Vec3 =
                    Vec3::new(-s_dir.get_x(), (-s_dir.get_y()).max(0.15), -s_dir.get_z())
                        .normalize();
                let moon_glow: f32 = v_dir.dot(moon_dir).max(0.0).powi(16) * 0.012 * night_factor;
                let stars: Vec3 = procedural_night_starfield(
                    v_dir,
                    self.get_starfield_intensity() * night_factor,
                );
                radiance = radiance
                    .add(airglow)
                    .add(Vec3::new(0.72, 0.80, 1.0).scale(moon_glow))
                    .add(stars);
            }
        } else {
            let ground_t: f32 = (-v_dir.get_y()).clamp(0.0, 1.0);
            let ground_lit: Vec3 = self
                .get_ground_albedo()
                .scale((0.003 + 0.18 * day_factor) * (1.0 - 0.5 * ground_t));
            radiance = radiance.lerp(ground_lit, ground_t.sqrt());
        }
        Vec3::new(
            if radiance.get_x().is_finite() {
                radiance.get_x().max(0.0)
            } else {
                0.0
            },
            if radiance.get_y().is_finite() {
                radiance.get_y().max(0.0)
            } else {
                0.0
            },
            if radiance.get_z().is_finite() {
                radiance.get_z().max(0.0)
            } else {
                0.0
            },
        )
    }

    /// Blends distant scene radiance through finite-distance atmospheric aerial perspective haze.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Unattenuated linear HDR scene surface radiance.
    /// - `f32` - Distance from camera to scene surface in meters.
    /// - `Vec3` - Unit view direction.
    /// - `Vec3` - Unit sun direction.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Aerial-perspective attenuated and in-scattered HDR radiance.
    #[must_use]
    pub fn evaluate_aerial_perspective(
        &self,
        scene_radiance: Vec3,
        distance_m: f32,
        view_dir: Vec3,
        sun_dir: Vec3,
    ) -> Vec3 {
        let safe_dist: f32 = if distance_m.is_finite() {
            distance_m.max(0.0)
        } else {
            0.0
        };
        let (inscatter, transmittance): (Vec3, Vec3) =
            self.integrate_atmosphere(view_dir, sun_dir, safe_dist);
        let safe_scene: Vec3 = Vec3::new(
            scene_radiance.get_x().max(0.0),
            scene_radiance.get_y().max(0.0),
            scene_radiance.get_z().max(0.0),
        );
        safe_scene.mul(transmittance).add(inscatter)
    }
}

/// Default midday mid-latitude `DayNightCycle3D`.
impl Default for DayNightCycle3D {
    /// Creates a `DayNightCycle3D` initialized to vernal-equinox solar noon (`12.0` hours, `35 deg` latitude).
    ///
    /// # Returns
    ///
    /// - `Self` - Default day/night cycle controller.
    fn default() -> Self {
        Self::new(12.0, 35.0, 81.0)
    }
}

/// Solar ephemeris progression, directional Sun/Moon light synthesis, and automatic `EnvironmentIbl3D` rebuilds for `DayNightCycle3D`.
impl DayNightCycle3D {
    /// Creates a `DayNightCycle3D` configured for `time_of_day_hours`, `latitude_deg`, and `day_of_year`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Initial local solar time in hours (`0.0..24.0`).
    /// - `f32` - Observer geographic latitude in degrees (`-89.0..=89.0`).
    /// - `f32` - Day of year (`1.0..=365.0`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured day/night controller with `ibl_dirty = true`.
    #[must_use]
    pub fn new(time_of_day_hours: f32, latitude_deg: f32, day_of_year: f32) -> Self {
        let wrapped_h: f32 = if time_of_day_hours.is_finite() {
            time_of_day_hours.rem_euclid(24.0)
        } else {
            12.0
        };
        let clamped_lat: f32 = if latitude_deg.is_finite() {
            latitude_deg.clamp(-89.0, 89.0)
        } else {
            35.0
        };
        let clamped_doy: f32 = if day_of_year.is_finite() {
            day_of_year.clamp(1.0, 365.0)
        } else {
            81.0
        };
        let initial_sun: Vec3 = solar_ephemeris_direction(wrapped_h, clamped_lat, clamped_doy);
        Self {
            time_of_day_hours: wrapped_h,
            latitude_deg: clamped_lat,
            day_of_year: clamped_doy,
            time_scale_hours_per_sec: 1.0 / 60.0,
            ibl_rebuild_threshold_rad: DEFAULT_IBL_REBUILD_ANGLE_RAD,
            last_ibl_sun_dir: initial_sun,
            ibl_dirty: true,
            ibl_generation: 0,
            sky: PhysicalSky3D::default(),
        }
    }

    /// Computes the current unit solar direction vector from the continuous ephemeris.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Unit vector pointing toward the sun.
    #[must_use]
    pub fn sun_direction(&self) -> Vec3 {
        solar_ephemeris_direction(
            self.get_time_of_day_hours(),
            self.get_latitude_deg(),
            self.get_day_of_year(),
        )
    }

    /// Computes the synchronized lunar direction vector opposite the sun with slight orbital inclination.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Unit vector pointing toward the moon.
    #[must_use]
    pub fn moon_direction(&self) -> Vec3 {
        let sun: Vec3 = self.sun_direction();
        Vec3::new(-sun.get_x(), -sun.get_y() + 0.08, -sun.get_z() * 0.96).normalize()
    }

    /// Advances the time of day by `dt_seconds * time_scale_hours_per_sec` and marks `ibl_dirty` when solar motion exceeds the angular threshold.
    ///
    /// # Arguments
    ///
    /// - `f32` - Frame delta time in seconds.
    pub fn advance(&mut self, dt_seconds: f32) {
        if !dt_seconds.is_finite() || dt_seconds == 0.0 {
            return;
        }
        let next_h: f32 = (self.get_time_of_day_hours()
            + dt_seconds * self.get_time_scale_hours_per_sec())
        .rem_euclid(24.0);
        self.set_time_hours(next_h);
    }

    /// Sets `time_of_day_hours` wrapped into `[0.0, 24.0)` and updates the automatic `EnvironmentIbl3D` dirty trigger.
    ///
    /// # Arguments
    ///
    /// - `f32` - New local solar time in hours.
    pub fn set_time_hours(&mut self, hours: f32) {
        let wrapped: f32 = if hours.is_finite() {
            hours.rem_euclid(24.0)
        } else {
            12.0
        };
        self.set_time_of_day_hours(wrapped);
        let cur_sun: Vec3 = self.sun_direction();
        let dot_val: f32 = cur_sun.dot(self.get_last_ibl_sun_dir()).clamp(-1.0, 1.0);
        let angle_delta: f32 = dot_val.acos();
        if angle_delta >= self.get_ibl_rebuild_threshold_rad().max(1.0e-4) {
            self.set_ibl_dirty(true);
        }
    }

    /// Evaluates current physical sky zenith and horizon linear RGB colors.
    ///
    /// # Returns
    ///
    /// - `(Vec3, Vec3)` - `(zenith_rgb, horizon_rgb)` linear HDR colors.
    #[must_use]
    pub fn zenith_and_horizon_colors(&self) -> (Vec3, Vec3) {
        let sun: Vec3 = self.sun_direction();
        let sky: PhysicalSky3D = self.get_sky();
        let zenith: Vec3 = sky.evaluate_sky_radiance(Vec3::new(0.0, 1.0, 0.0), sun);
        let horiz_dir: Vec3 = Vec3::new(sun.get_x(), 0.04, sun.get_z()).normalize();
        let horizon: Vec3 = sky.evaluate_sky_radiance(horiz_dir, sun);
        (zenith, horizon)
    }

    /// Synthesizes the synchronized active Sun (day/twilight) or Moon (night) `RigDirectionalLight3D`.
    ///
    /// # Returns
    ///
    /// - `RigDirectionalLight3D` - Active directional sky light.
    #[must_use]
    pub fn active_directional_light(&self) -> RigDirectionalLight3D {
        let sun: Vec3 = self.sun_direction();
        if sun.get_y() > 0.01 {
            let trans: Vec3 = self.get_sky().sun_transmittance(sun);
            let elev_boost: f32 = (sun.get_y() / 0.25).clamp(0.15, 1.0);
            let sun_lum: f32 = (6.5 * elev_boost).max(0.2);
            RigDirectionalLight3D::new(sun, trans, sun_lum)
        } else {
            let moon: Vec3 = self.moon_direction();
            let moon_elev: f32 = moon.get_y().max(0.05);
            RigDirectionalLight3D::new(
                moon,
                Vec3::new(0.55, 0.68, 0.98),
                0.28 * moon_elev.clamp(0.15, 1.0),
            )
        }
    }

    /// Synthesizes a compatible `euv-core` world `DirectionalLight3D` synchronized with this cycle's sky zenith and horizon.
    ///
    /// # Returns
    ///
    /// - `DirectionalLight3D` - Synchronized world directional light.
    #[must_use]
    pub fn world_directional_light(&self) -> DirectionalLight3D {
        let (zenith, horizon): (Vec3, Vec3) = self.zenith_and_horizon_colors();
        self.active_directional_light().to_world_directional(
            zenith,
            horizon,
            self.get_time_of_day_hours(),
        )
    }

    /// Automatically rebuilds `cached_ibl` from `PhysicalSky3D` whenever `ibl_dirty` is set or `cached_ibl` is `None`.
    ///
    /// # Arguments
    ///
    /// - `&mut Option<EnvironmentIbl3D>` - Destination cached IBL environment slot.
    /// - `u32` - Octahedral prefiltered specular base face resolution.
    /// - `u32` - Split-Sum BRDF LUT edge resolution.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when an `EnvironmentIbl3D` rebuild was triggered, `false` when cached IBL remained valid.
    pub fn rebuild_ibl_if_needed(
        &mut self,
        cached_ibl: &mut Option<EnvironmentIbl3D>,
        oct_size: u32,
        lut_size: u32,
    ) -> bool {
        if !self.get_ibl_dirty() && cached_ibl.is_some() {
            return false;
        }
        let sun_dir: Vec3 = self.sun_direction();
        let sky: PhysicalSky3D = self.get_sky();
        let baked: EnvironmentIbl3D = EnvironmentIbl3D::from_sampler(
            |dir: Vec3| -> Vec3 { sky.evaluate_sky_radiance(dir, sun_dir) },
            oct_size.max(8),
            lut_size.max(8),
        );
        *cached_ibl = Some(baked);
        self.set_last_ibl_sun_dir(sun_dir);
        self.set_ibl_dirty(false);
        self.set_ibl_generation(self.get_ibl_generation().saturating_add(1));
        true
    }
}