Skip to main content

euv_core/game/engine3d/raytrace/scene/
impl.rs

1use super::*;
2
3/// Default environment dome returning dark background.
4impl Default for RtEnvironment {
5    /// Returns a black zero-radiance environment dome.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Black environment.
10    fn default() -> Self {
11        Self::Black
12    }
13}
14
15/// Default matte diffuse material constructor for `RtMaterial`.
16impl Default for RtMaterial {
17    /// Returns a neutral mid-gray Lambertian diffuse material.
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - Default diffuse material.
22    fn default() -> Self {
23        Self::lambert(Vec3::splat(0.75))
24    }
25}
26
27/// Physical BSDF constructors, Beer-Lambert transmittance, and `euv-core` material converters for `RtMaterial`.
28impl RtMaterial {
29    /// Creates an ideal Lambertian matte diffuse material.
30    ///
31    /// # Arguments
32    ///
33    /// - `Vec3` - Linear RGB surface albedo in `[0.0, 1.0]`.
34    ///
35    /// # Returns
36    ///
37    /// - `Self` - Diffuse `RtMaterial`.
38    #[must_use]
39    pub fn lambert(albedo: Vec3) -> Self {
40        Self {
41            kind: RtMaterialKind::Diffuse,
42            albedo: Vec3::new(
43                albedo.get_x().clamp(0.0, 1.0),
44                albedo.get_y().clamp(0.0, 1.0),
45                albedo.get_z().clamp(0.0, 1.0),
46            ),
47            metallic: 0.0,
48            roughness: 1.0,
49            ior: RT_DEFAULT_GLASS_IOR,
50            transmission: 0.0,
51            absorption: Vec3::zero(),
52            clearcoat: 0.0,
53            clearcoat_roughness: 0.05,
54            emission: Vec3::zero(),
55            oren_nayar_sigma: 0.0,
56        }
57    }
58
59    /// Creates an Oren-Nayar micro-rough diffuse material modeling dusty or plaster surfaces.
60    ///
61    /// # Arguments
62    ///
63    /// - `Vec3` - Linear RGB diffuse albedo.
64    /// - `f32` - Microfacet slope standard deviation `sigma` in `[0.0, 1.0]`.
65    ///
66    /// # Returns
67    ///
68    /// - `Self` - Oren-Nayar diffuse `RtMaterial`.
69    #[must_use]
70    pub fn oren_nayar(albedo: Vec3, sigma: f32) -> Self {
71        let mut mat: Self = Self::lambert(albedo);
72        mat.set_oren_nayar_sigma(sigma.clamp(0.0, 1.0));
73        mat
74    }
75
76    /// Creates a GGX microfacet metallic conductor material.
77    ///
78    /// # Arguments
79    ///
80    /// - `Vec3` - Linear RGB conductor reflectance `F0`.
81    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
82    ///
83    /// # Returns
84    ///
85    /// - `Self` - Metallic conductor `RtMaterial`.
86    #[must_use]
87    pub fn metal(albedo: Vec3, roughness: f32) -> Self {
88        Self {
89            kind: RtMaterialKind::Metal,
90            albedo: Vec3::new(
91                albedo.get_x().clamp(0.0, 1.0),
92                albedo.get_y().clamp(0.0, 1.0),
93                albedo.get_z().clamp(0.0, 1.0),
94            ),
95            metallic: 1.0,
96            roughness: roughness.clamp(0.0, 1.0),
97            ior: RT_DEFAULT_GLASS_IOR,
98            transmission: 0.0,
99            absorption: Vec3::zero(),
100            clearcoat: 0.0,
101            clearcoat_roughness: 0.05,
102            emission: Vec3::zero(),
103            oren_nayar_sigma: 0.0,
104        }
105    }
106
107    /// Creates a sharp mirror conductor material with zero microfacet roughness.
108    ///
109    /// # Arguments
110    ///
111    /// - `Vec3` - Linear RGB mirror reflectance tint.
112    ///
113    /// # Returns
114    ///
115    /// - `Self` - Ideal mirror `RtMaterial`.
116    #[must_use]
117    pub fn mirror(albedo: Vec3) -> Self {
118        Self::metal(albedo, 0.0)
119    }
120
121    /// Creates a refractive dielectric material (glass or water) with Schlick/Snell optics and Beer-Lambert absorption.
122    ///
123    /// # Arguments
124    ///
125    /// - `Vec3` - Surface transmission/reflection albedo multiplier.
126    /// - `f32` - Index of refraction (`> 1.0`, e.g., `1.5` for glass or `1.333` for water).
127    /// - `f32` - Surface microfacet roughness (`0.0` for crystal-clear glass).
128    /// - `Vec3` - Beer-Lambert volumetric absorption coefficient `sigma_a >= 0` (`1 / meters`).
129    ///
130    /// # Returns
131    ///
132    /// - `Self` - Dielectric `RtMaterial`.
133    #[must_use]
134    pub fn dielectric(albedo: Vec3, ior: f32, roughness: f32, absorption: Vec3) -> Self {
135        Self {
136            kind: RtMaterialKind::Dielectric,
137            albedo: Vec3::new(
138                albedo.get_x().clamp(0.0, 1.0),
139                albedo.get_y().clamp(0.0, 1.0),
140                albedo.get_z().clamp(0.0, 1.0),
141            ),
142            metallic: 0.0,
143            roughness: roughness.clamp(0.0, 1.0),
144            ior: ior.clamp(1.001, 3.0),
145            transmission: 1.0,
146            absorption: Vec3::new(
147                absorption.get_x().max(0.0),
148                absorption.get_y().max(0.0),
149                absorption.get_z().max(0.0),
150            ),
151            clearcoat: 0.0,
152            clearcoat_roughness: 0.04,
153            emission: Vec3::zero(),
154            oren_nayar_sigma: 0.0,
155        }
156    }
157
158    /// Creates a crystal-clear lossless dielectric glass material with the given index of refraction.
159    ///
160    /// # Arguments
161    ///
162    /// - `f32` - Index of refraction (e.g., `1.5`).
163    ///
164    /// # Returns
165    ///
166    /// - `Self` - Clear glass `RtMaterial`.
167    #[must_use]
168    pub fn glass(ior: f32) -> Self {
169        Self::dielectric(Vec3::splat(1.0), ior, 0.0, Vec3::zero())
170    }
171
172    /// Creates a clearcoat layered material combining a base diffuse/specular coat with a glossy dielectric varnish.
173    ///
174    /// # Arguments
175    ///
176    /// - `Vec3` - Base linear RGB albedo.
177    /// - `f32` - Base layer roughness in `[0.0, 1.0]`.
178    /// - `f32` - Clearcoat weight in `[0.0, 1.0]`.
179    /// - `f32` - Clearcoat roughness in `[0.0, 1.0]`.
180    ///
181    /// # Returns
182    ///
183    /// - `Self` - Principled clearcoat `RtMaterial`.
184    #[must_use]
185    pub fn clearcoat(
186        albedo: Vec3,
187        roughness: f32,
188        clearcoat: f32,
189        clearcoat_roughness: f32,
190    ) -> Self {
191        Self {
192            kind: RtMaterialKind::Principled,
193            albedo: Vec3::new(
194                albedo.get_x().clamp(0.0, 1.0),
195                albedo.get_y().clamp(0.0, 1.0),
196                albedo.get_z().clamp(0.0, 1.0),
197            ),
198            metallic: 0.0,
199            roughness: roughness.clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
200            ior: RT_DEFAULT_GLASS_IOR,
201            transmission: 0.0,
202            absorption: Vec3::zero(),
203            clearcoat: clearcoat.clamp(0.0, 1.0),
204            clearcoat_roughness: clearcoat_roughness.clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
205            emission: Vec3::zero(),
206            oren_nayar_sigma: 0.0,
207        }
208    }
209
210    /// Creates a pure HDR emissive area light material.
211    ///
212    /// # Arguments
213    ///
214    /// - `Vec3` - Linear HDR emitted radiance RGB.
215    ///
216    /// # Returns
217    ///
218    /// - `Self` - Emissive `RtMaterial`.
219    #[must_use]
220    pub fn emissive(radiance: Vec3) -> Self {
221        Self {
222            kind: RtMaterialKind::Emissive,
223            albedo: Vec3::zero(),
224            metallic: 0.0,
225            roughness: 1.0,
226            ior: RT_DEFAULT_GLASS_IOR,
227            transmission: 0.0,
228            absorption: Vec3::zero(),
229            clearcoat: 0.0,
230            clearcoat_roughness: 0.04,
231            emission: Vec3::new(
232                radiance.get_x().max(0.0),
233                radiance.get_y().max(0.0),
234                radiance.get_z().max(0.0),
235            ),
236            oren_nayar_sigma: 0.0,
237        }
238    }
239
240    /// Creates a unified Principled BSDF material combining metallic, roughness, IOR, and transmission.
241    ///
242    /// # Arguments
243    ///
244    /// - `Vec3` - Base linear RGB albedo.
245    /// - `f32` - Metallic factor in `[0.0, 1.0]`.
246    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
247    /// - `f32` - Dielectric IOR.
248    /// - `f32` - Transmission weight in `[0.0, 1.0]`.
249    ///
250    /// # Returns
251    ///
252    /// - `Self` - Principled `RtMaterial`.
253    #[must_use]
254    pub fn principled(
255        albedo: Vec3,
256        metallic: f32,
257        roughness: f32,
258        ior: f32,
259        transmission: f32,
260    ) -> Self {
261        Self {
262            kind: RtMaterialKind::Principled,
263            albedo: Vec3::new(
264                albedo.get_x().clamp(0.0, 1.0),
265                albedo.get_y().clamp(0.0, 1.0),
266                albedo.get_z().clamp(0.0, 1.0),
267            ),
268            metallic: metallic.clamp(0.0, 1.0),
269            roughness: roughness.clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
270            ior: ior.clamp(1.001, 3.0),
271            transmission: transmission.clamp(0.0, 1.0),
272            absorption: Vec3::zero(),
273            clearcoat: 0.0,
274            clearcoat_roughness: 0.05,
275            emission: Vec3::zero(),
276            oren_nayar_sigma: 0.0,
277        }
278    }
279
280    /// Converts an `euv-core` `PbrMaterial` into a physically based `RtMaterial`.
281    ///
282    /// # Arguments
283    ///
284    /// - `&PbrMaterial` - Source `World3D` PBR material.
285    ///
286    /// # Returns
287    ///
288    /// - `Self` - Converted ray-tracing material.
289    #[must_use]
290    pub fn from_pbr_material(material: &PbrMaterial) -> Self {
291        let emissive: Vec3 = material.get_emissive();
292        let has_emissive: bool =
293            emissive.get_x() > 1e-4 || emissive.get_y() > 1e-4 || emissive.get_z() > 1e-4;
294        let metallic: f32 = material.get_metallic().clamp(0.0, 1.0);
295        let roughness: f32 = material.get_roughness().clamp(RT_SCENE_MIN_ROUGHNESS, 1.0);
296        let base_color: Vec3 = material.get_base_color();
297        let kind: RtMaterialKind = if metallic >= 0.85 {
298            RtMaterialKind::Metal
299        } else if metallic <= 0.05 && roughness >= 0.75 && !has_emissive {
300            RtMaterialKind::Diffuse
301        } else {
302            RtMaterialKind::Principled
303        };
304        Self {
305            kind,
306            albedo: Vec3::new(
307                base_color.get_x().clamp(0.0, 1.0),
308                base_color.get_y().clamp(0.0, 1.0),
309                base_color.get_z().clamp(0.0, 1.0),
310            ),
311            metallic,
312            roughness,
313            ior: RT_DEFAULT_GLASS_IOR,
314            transmission: 0.0,
315            absorption: Vec3::zero(),
316            clearcoat: (material.get_reflectivity() * 0.5).clamp(0.0, 1.0),
317            clearcoat_roughness: (roughness * 0.5).clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
318            emission: Vec3::new(
319                emissive.get_x().max(0.0),
320                emissive.get_y().max(0.0),
321                emissive.get_z().max(0.0),
322            ),
323            oren_nayar_sigma: 0.0,
324        }
325    }
326
327    /// Converts an `euv-core` Blender/glTF `PrincipledMaterial3D` into a physically based `RtMaterial`.
328    ///
329    /// # Arguments
330    ///
331    /// - `&PrincipledMaterial3D` - Source principled material descriptor.
332    ///
333    /// # Returns
334    ///
335    /// - `Self` - Converted ray-tracing material including IOR, transmission, clearcoat, and Beer-Lambert volume absorption.
336    #[must_use]
337    pub fn from_principled_material(material: &PrincipledMaterial3D) -> Self {
338        let bc: [f32; 4] = material.get_base_color_factor();
339        let albedo: Vec3 = Vec3::new(
340            bc[0].clamp(0.0, 1.0),
341            bc[1].clamp(0.0, 1.0),
342            bc[2].clamp(0.0, 1.0),
343        );
344        let ef: [f32; 3] = material.get_emissive_factor();
345        let es: f32 = material.get_emissive_strength().max(0.0);
346        let emission: Vec3 = Vec3::new(
347            (ef[0] * es).max(0.0),
348            (ef[1] * es).max(0.0),
349            (ef[2] * es).max(0.0),
350        );
351        let transmission: f32 = material.get_transmission_factor().clamp(0.0, 1.0);
352        let att_dist: f32 = material.get_attenuation_distance();
353        let att_col: [f32; 3] = material.get_attenuation_color();
354        let absorption: Vec3 = if att_dist.is_finite() && att_dist > 1e-4 && transmission > 1e-4 {
355            let inv_d: f32 = 1.0 / att_dist;
356            Vec3::new(
357                (-att_col[0].clamp(1e-4, 1.0).ln()) * inv_d,
358                (-att_col[1].clamp(1e-4, 1.0).ln()) * inv_d,
359                (-att_col[2].clamp(1e-4, 1.0).ln()) * inv_d,
360            )
361        } else {
362            Vec3::zero()
363        };
364        let metallic: f32 = material.get_metallic_factor().clamp(0.0, 1.0);
365        let roughness: f32 = material
366            .get_roughness_factor()
367            .clamp(RT_SCENE_MIN_ROUGHNESS, 1.0);
368        let kind: RtMaterialKind = if transmission >= 0.9 && metallic < 0.05 {
369            RtMaterialKind::Dielectric
370        } else if metallic >= 0.95 && transmission < 0.05 {
371            RtMaterialKind::Metal
372        } else {
373            RtMaterialKind::Principled
374        };
375        Self {
376            kind,
377            albedo,
378            metallic,
379            roughness,
380            ior: material.get_ior().clamp(1.001, 3.0),
381            transmission,
382            absorption,
383            clearcoat: material.get_clearcoat_factor().clamp(0.0, 1.0),
384            clearcoat_roughness: material
385                .get_clearcoat_roughness_factor()
386                .clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
387            emission,
388            oren_nayar_sigma: 0.0,
389        }
390    }
391
392    /// Evaluates Beer-Lambert volumetric transmittance `exp(-sigma_a * distance)` over an interior ray segment.
393    ///
394    /// # Arguments
395    ///
396    /// - `&Self` - Material reference.
397    /// - `f32` - Interior travel distance in meters.
398    ///
399    /// # Returns
400    ///
401    /// - `Vec3` - Component-wise optical transmittance in `(0.0, 1.0]`.
402    #[must_use]
403    pub fn beer_lambert_transmittance(&self, distance: f32) -> Vec3 {
404        let d: f32 = distance.max(0.0);
405        let sigma: Vec3 = self.get_absorption();
406        Vec3::new(
407            (-sigma.get_x().max(0.0) * d).exp().clamp(0.0, 1.0),
408            (-sigma.get_y().max(0.0) * d).exp().clamp(0.0, 1.0),
409            (-sigma.get_z().max(0.0) * d).exp().clamp(0.0, 1.0),
410        )
411    }
412
413    /// Returns `true` when this material emits non-zero HDR radiance.
414    ///
415    /// # Arguments
416    ///
417    /// - `&Self` - Material reference.
418    ///
419    /// # Returns
420    ///
421    /// - `bool` - Whether emission exceeds zero.
422    #[must_use]
423    pub fn is_emissive(&self) -> bool {
424        let e: Vec3 = self.get_emission();
425        e.get_x() > 0.0 || e.get_y() > 0.0 || e.get_z() > 0.0
426    }
427
428    /// Returns `true` when this material acts as a pure Dirac delta mirror or clear dielectric.
429    ///
430    /// # Arguments
431    ///
432    /// - `&Self` - Material reference.
433    ///
434    /// # Returns
435    ///
436    /// - `bool` - Whether BSDF scattering is a delta distribution.
437    #[must_use]
438    pub fn is_delta_specular(&self) -> bool {
439        match self.get_kind() {
440            RtMaterialKind::Metal => self.get_roughness() <= 0.005,
441            RtMaterialKind::Dielectric => self.get_roughness() <= 0.005,
442            _ => false,
443        }
444    }
445}
446
447/// Constructors, importance sampling, and direct area-light intersection for `RtLight`.
448impl RtLight {
449    /// Creates a directional sun/sky light with optional angular radius for physically soft shadows.
450    ///
451    /// # Arguments
452    ///
453    /// - `Vec3` - Direction pointing from the scene toward the light source.
454    /// - `Vec3` - Linear HDR light color.
455    /// - `f32` - Radiant irradiance multiplier.
456    /// - `f32` - Angular half-angle in radians (`0.0` for razor-sharp sun shadows).
457    ///
458    /// # Returns
459    ///
460    /// - `Self` - Directional `RtLight`.
461    #[must_use]
462    pub fn directional(
463        direction: Vec3,
464        color: Vec3,
465        intensity: f32,
466        angular_radius_rad: f32,
467    ) -> Self {
468        Self {
469            kind: RtLightKind::Directional {
470                direction: direction.normalize(),
471                angular_radius_rad: angular_radius_rad.clamp(0.0, FRAC_PI_3),
472            },
473            color,
474            intensity: intensity.max(0.0),
475        }
476    }
477
478    /// Creates an omnidirectional spherical point light with inverse-square attenuation.
479    ///
480    /// # Arguments
481    ///
482    /// - `Vec3` - World-space light center.
483    /// - `Vec3` - Linear HDR light color.
484    /// - `f32` - Luminous intensity.
485    /// - `f32` - Spherical radius in meters (`0.0` for delta point light).
486    ///
487    /// # Returns
488    ///
489    /// - `Self` - Point `RtLight`.
490    #[must_use]
491    pub fn point(position: Vec3, color: Vec3, intensity: f32, radius: f32) -> Self {
492        Self {
493            kind: RtLightKind::Point {
494                position,
495                radius: radius.max(0.0),
496            },
497            color,
498            intensity: intensity.max(0.0),
499        }
500    }
501
502    /// Creates a focused spotlight with inner/outer cone angles in degrees and optional soft emitter radius.
503    ///
504    /// # Arguments
505    ///
506    /// - `Vec3` - World-space emitter origin.
507    /// - `Vec3` - Beam forward direction.
508    /// - `Vec3` - Linear HDR light color.
509    /// - `f32` - Luminous intensity.
510    /// - `f32` - Inner full-brightness half-angle in degrees.
511    /// - `f32` - Outer cutoff half-angle in degrees.
512    /// - `f32` - Emitter radius in meters.
513    ///
514    /// # Returns
515    ///
516    /// - `Self` - Spotlight `RtLight`.
517    #[must_use]
518    pub fn spot(
519        position: Vec3,
520        direction: Vec3,
521        color: Vec3,
522        intensity: f32,
523        inner_deg: f32,
524        outer_deg: f32,
525        radius: f32,
526    ) -> Self {
527        let inner_clamped: f32 = inner_deg.clamp(0.5, 89.0);
528        let outer_clamped: f32 = outer_deg.clamp(inner_clamped + 0.5, 89.5);
529        Self {
530            kind: RtLightKind::Spot {
531                position,
532                direction: direction.normalize(),
533                inner_cos: inner_clamped.to_radians().cos(),
534                outer_cos: outer_clamped.to_radians().cos(),
535                radius: radius.max(0.0),
536            },
537            color,
538            intensity: intensity.max(0.0),
539        }
540    }
541
542    /// Creates a physically based rectangular area light emitter oriented along `normal`.
543    ///
544    /// # Arguments
545    ///
546    /// - `Vec3` - World-space rectangle center.
547    /// - `Vec3` - Outward emitting surface normal.
548    /// - `Vec2` - Emitter `(width, height)` dimensions in meters.
549    /// - `Vec3` - Linear HDR emission color.
550    /// - `f32` - Emitted radiance multiplier.
551    /// - `bool` - Whether both sides of the rectangle emit radiance.
552    ///
553    /// # Returns
554    ///
555    /// - `Self` - Rectangular area `RtLight`.
556    #[must_use]
557    pub fn rect_area(
558        position: Vec3,
559        normal: Vec3,
560        dimensions: Vec2,
561        color: Vec3,
562        intensity: f32,
563        two_sided: bool,
564    ) -> Self {
565        let n: Vec3 = normal.normalize();
566        let (right, up): (Vec3, Vec3) = build_orthonormal_basis(n);
567        Self {
568            kind: RtLightKind::RectArea {
569                position,
570                right,
571                up,
572                normal: n,
573                width: dimensions.get_x().max(1e-3),
574                height: dimensions.get_y().max(1e-3),
575                two_sided,
576            },
577            color,
578            intensity: intensity.max(0.0),
579        }
580    }
581
582    /// Creates a physically based circular disk area light emitter oriented along `normal`.
583    ///
584    /// # Arguments
585    ///
586    /// - `Vec3` - World-space disk center.
587    /// - `Vec3` - Outward emitting surface normal.
588    /// - `f32` - Disk radius in meters.
589    /// - `Vec3` - Linear HDR emission color.
590    /// - `f32` - Emitted radiance multiplier.
591    /// - `bool` - Whether both sides of the disk emit radiance.
592    ///
593    /// # Returns
594    ///
595    /// - `Self` - Circular disk area `RtLight`.
596    #[must_use]
597    pub fn disk_area(
598        position: Vec3,
599        normal: Vec3,
600        radius: f32,
601        color: Vec3,
602        intensity: f32,
603        two_sided: bool,
604    ) -> Self {
605        let n: Vec3 = normal.normalize();
606        let (right, up): (Vec3, Vec3) = build_orthonormal_basis(n);
607        Self {
608            kind: RtLightKind::DiskArea {
609                position,
610                right,
611                up,
612                normal: n,
613                radius: radius.max(1e-3),
614                two_sided,
615            },
616            color,
617            intensity: intensity.max(0.0),
618        }
619    }
620
621    /// Importance-samples a direct lighting direction and solid-angle PDF from `hit_point`.
622    ///
623    /// # Arguments
624    ///
625    /// - `&Self` - Light emitter reference.
626    /// - `Vec3` - World-space shaded surface position.
627    /// - `[f32; 2]` - Uniform quasi-random or pseudo-random pair in `[0.0, 1.0)^2`.
628    ///
629    /// # Returns
630    ///
631    /// - `RtLightSample` - Sampled direction, distance, incident radiance, solid-angle PDF, and delta flag.
632    #[must_use]
633    pub fn sample_light(&self, hit_point: Vec3, xi: [f32; 2]) -> RtLightSample {
634        let power: Vec3 = self.get_color().scale(self.get_intensity());
635        match self.get_kind() {
636            RtLightKind::Directional {
637                direction,
638                angular_radius_rad,
639            } => {
640                let axis: Vec3 = direction.normalize();
641                if angular_radius_rad <= 1e-5 {
642                    return RtLightSample::new(axis, RT_RAY_T_MAX, power, 1.0, true);
643                }
644                let cos_max: f32 = angular_radius_rad.cos().clamp(-0.999, 0.999_999);
645                let cos_theta: f32 = (1.0 - xi[0]) + xi[0] * cos_max;
646                let sin_theta: f32 = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();
647                let phi: f32 = TAU * xi[1];
648                let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(axis);
649                let sampled_dir: Vec3 = tangent
650                    .scale(sin_theta * phi.cos())
651                    .add(bitangent.scale(sin_theta * phi.sin()))
652                    .add(axis.scale(cos_theta))
653                    .normalize();
654                RtLightSample::new(sampled_dir, RT_RAY_T_MAX, power, 1.0, true)
655            }
656            RtLightKind::Point { position, radius } => {
657                let to_center: Vec3 = position.sub(hit_point);
658                let center_dist_sq: f32 = to_center.length_sq().max(1e-4);
659                let target: Vec3 = if radius > 1e-5 {
660                    let axis: Vec3 = to_center.scale(1.0 / center_dist_sq.sqrt());
661                    let (t, b): (Vec3, Vec3) = build_orthonormal_basis(axis);
662                    let disk: [f32; 2] = concentric_sample_disk(xi);
663                    position
664                        .add(t.scale(disk[0] * radius))
665                        .add(b.scale(disk[1] * radius))
666                } else {
667                    position
668                };
669                let to_sample: Vec3 = target.sub(hit_point);
670                let dist_sq: f32 = to_sample.length_sq().max(1e-4);
671                let dist: f32 = dist_sq.sqrt();
672                let dir: Vec3 = to_sample.scale(1.0 / dist);
673                RtLightSample::new(dir, dist, power.scale(1.0 / dist_sq), 1.0, true)
674            }
675            RtLightKind::Spot {
676                position,
677                direction,
678                inner_cos,
679                outer_cos,
680                radius,
681            } => {
682                let to_center: Vec3 = position.sub(hit_point);
683                let center_dist_sq: f32 = to_center.length_sq().max(1e-4);
684                let target: Vec3 = if radius > 1e-5 {
685                    let axis: Vec3 = to_center.scale(1.0 / center_dist_sq.sqrt());
686                    let (t, b): (Vec3, Vec3) = build_orthonormal_basis(axis);
687                    let disk: [f32; 2] = concentric_sample_disk(xi);
688                    position
689                        .add(t.scale(disk[0] * radius))
690                        .add(b.scale(disk[1] * radius))
691                } else {
692                    position
693                };
694                let to_sample: Vec3 = target.sub(hit_point);
695                let dist_sq: f32 = to_sample.length_sq().max(1e-4);
696                let dist: f32 = dist_sq.sqrt();
697                let dir: Vec3 = to_sample.scale(1.0 / dist);
698                let cos_angle: f32 = dir.scale(-1.0).dot(direction.normalize());
699                let span: f32 = (inner_cos - outer_cos).max(1e-4);
700                let t_cone: f32 = ((cos_angle - outer_cos) / span).clamp(0.0, 1.0);
701                let falloff: f32 = t_cone * t_cone;
702                RtLightSample::new(dir, dist, power.scale(falloff / dist_sq), 1.0, true)
703            }
704            RtLightKind::RectArea {
705                position,
706                right,
707                up,
708                normal,
709                width,
710                height,
711                two_sided,
712            } => {
713                let u_off: f32 = (xi[0] - 0.5) * width;
714                let v_off: f32 = (xi[1] - 0.5) * height;
715                let sample_pt: Vec3 = position.add(right.scale(u_off)).add(up.scale(v_off));
716                let to_light: Vec3 = sample_pt.sub(hit_point);
717                let dist_sq: f32 = to_light.length_sq();
718                if dist_sq <= RT_SCENE_EPSILON {
719                    return RtLightSample::new(
720                        Vec3::new(0.0, 1.0, 0.0),
721                        0.0,
722                        Vec3::zero(),
723                        0.0,
724                        false,
725                    );
726                }
727                let dist: f32 = dist_sq.sqrt();
728                let dir: Vec3 = to_light.scale(1.0 / dist);
729                let raw_cos: f32 = normal.dot(dir.scale(-1.0));
730                let cos_light: f32 = if two_sided { raw_cos.abs() } else { raw_cos };
731                if cos_light <= RT_SCENE_EPSILON {
732                    return RtLightSample::new(dir, dist, Vec3::zero(), 0.0, false);
733                }
734                let area: f32 = (width * height).max(RT_SCENE_EPSILON);
735                let pdf: f32 = dist_sq / (area * cos_light);
736                RtLightSample::new(dir, dist, power, pdf, false)
737            }
738            RtLightKind::DiskArea {
739                position,
740                right,
741                up,
742                normal,
743                radius,
744                two_sided,
745            } => {
746                let disk: [f32; 2] = concentric_sample_disk(xi);
747                let sample_pt: Vec3 = position
748                    .add(right.scale(disk[0] * radius))
749                    .add(up.scale(disk[1] * radius));
750                let to_light: Vec3 = sample_pt.sub(hit_point);
751                let dist_sq: f32 = to_light.length_sq();
752                if dist_sq <= RT_SCENE_EPSILON {
753                    return RtLightSample::new(
754                        Vec3::new(0.0, 1.0, 0.0),
755                        0.0,
756                        Vec3::zero(),
757                        0.0,
758                        false,
759                    );
760                }
761                let dist: f32 = dist_sq.sqrt();
762                let dir: Vec3 = to_light.scale(1.0 / dist);
763                let raw_cos: f32 = normal.dot(dir.scale(-1.0));
764                let cos_light: f32 = if two_sided { raw_cos.abs() } else { raw_cos };
765                if cos_light <= RT_SCENE_EPSILON {
766                    return RtLightSample::new(dir, dist, Vec3::zero(), 0.0, false);
767                }
768                let area: f32 = (PI * radius * radius).max(RT_SCENE_EPSILON);
769                let pdf: f32 = dist_sq / (area * cos_light);
770                RtLightSample::new(dir, dist, power, pdf, false)
771            }
772        }
773    }
774
775    /// Intersects a ray with an explicit finite area light (`RectArea` or `DiskArea`) returning `(distance, radiance, solid_angle_pdf)`.
776    ///
777    /// # Arguments
778    ///
779    /// - `&Self` - Light emitter reference.
780    /// - `&Ray3D` - World-space ray.
781    /// - `f32` - Minimum accepted distance.
782    /// - `f32` - Maximum accepted distance.
783    ///
784    /// # Returns
785    ///
786    /// - `Option<(f32, Vec3, f32)>` - Hit distance, emitted HDR radiance, and solid-angle sampling PDF for MIS.
787    #[must_use]
788    pub fn intersect_area(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<(f32, Vec3, f32)> {
789        let power: Vec3 = self.get_color().scale(self.get_intensity());
790        let origin: Vec3 = ray.get_origin();
791        let dir: Vec3 = ray.get_direction();
792        match self.get_kind() {
793            RtLightKind::RectArea {
794                position,
795                right,
796                up,
797                normal,
798                width,
799                height,
800                two_sided,
801            } => {
802                let denom: f32 = normal.dot(dir);
803                if denom.abs() < RT_SCENE_EPSILON {
804                    return None;
805                }
806                let cos_light: f32 = if two_sided { -denom.abs() } else { denom };
807                let front_cos: f32 = -cos_light;
808                if !two_sided && front_cos <= RT_SCENE_EPSILON {
809                    return None;
810                }
811                let dist: f32 = position.sub(origin).dot(normal) / denom;
812                if !dist.is_finite() {
813                    return None;
814                }
815                if dist < t_min || dist > t_max {
816                    return None;
817                }
818                let rel: Vec3 = origin.add(dir.scale(dist)).sub(position);
819                let u_proj: f32 = rel.dot(right);
820                let v_proj: f32 = rel.dot(up);
821                if u_proj.abs() > width * 0.5 || v_proj.abs() > height * 0.5 {
822                    return None;
823                }
824                let area: f32 = (width * height).max(RT_SCENE_EPSILON);
825                let pdf: f32 = (dist * dist) / (area * denom.abs().max(RT_SCENE_EPSILON));
826                Some((dist, power, pdf))
827            }
828            RtLightKind::DiskArea {
829                position,
830                normal,
831                radius,
832                two_sided,
833                ..
834            } => {
835                let denom: f32 = normal.dot(dir);
836                if denom.abs() < RT_SCENE_EPSILON {
837                    return None;
838                }
839                if !two_sided && (-denom) <= RT_SCENE_EPSILON {
840                    return None;
841                }
842                let dist: f32 = position.sub(origin).dot(normal) / denom;
843                if !dist.is_finite() {
844                    return None;
845                }
846                if dist < t_min || dist > t_max {
847                    return None;
848                }
849                let rel: Vec3 = origin.add(dir.scale(dist)).sub(position);
850                if rel.length_sq() > radius * radius {
851                    return None;
852                }
853                let area: f32 = (PI * radius * radius).max(RT_SCENE_EPSILON);
854                let pdf: f32 = (dist * dist) / (area * denom.abs().max(RT_SCENE_EPSILON));
855                Some((dist, power, pdf))
856            }
857            _ => None,
858        }
859    }
860}
861
862/// Default pinhole camera positioned on `+Z` looking toward the origin.
863impl Default for RtCamera {
864    /// Creates a default 16:9 pinhole camera at `(0, 1.5, 5.0)` looking at `(0, 1.0, 0)`.
865    ///
866    /// # Returns
867    ///
868    /// - `Self` - Default `RtCamera`.
869    fn default() -> Self {
870        Self::look_at(
871            Vec3::new(0.0, 1.5, 5.0),
872            Vec3::new(0.0, 1.0, 0.0),
873            Vec3::new(0.0, 1.0, 0.0),
874            RT_DEFAULT_FOV_DEG,
875            16.0 / 9.0,
876        )
877    }
878}
879
880/// Look-at construction, thin-lens depth of field, jittered ray generation, and motion hashing for `RtCamera`.
881impl RtCamera {
882    /// Constructs a pinhole camera looking from `position` toward `target`.
883    ///
884    /// # Arguments
885    ///
886    /// - `Vec3` - World-space eye position.
887    /// - `Vec3` - World-space look target.
888    /// - `Vec3` - World-space up reference vector.
889    /// - `f32` - Vertical field of view in degrees.
890    /// - `f32` - Viewport aspect ratio (`width / height`).
891    ///
892    /// # Returns
893    ///
894    /// - `Self` - Configured pinhole `RtCamera`.
895    #[must_use]
896    pub fn look_at(
897        position: Vec3,
898        target: Vec3,
899        world_up: Vec3,
900        fov_y_deg: f32,
901        aspect: f32,
902    ) -> Self {
903        let forward: Vec3 = target.sub(position).normalize();
904        let up_ref: Vec3 = if forward.dot(world_up.normalize()).abs() > 0.999 {
905            Vec3::new(0.0, 0.0, 1.0)
906        } else {
907            world_up.normalize()
908        };
909        let right: Vec3 = forward.cross(up_ref).normalize();
910        let up: Vec3 = right.cross(forward).normalize();
911        let focal_dist: f32 = target.sub(position).length().max(0.1);
912        Self {
913            position,
914            forward,
915            right,
916            up,
917            fov_y_rad: fov_y_deg.clamp(5.0, 150.0).to_radians(),
918            aspect: aspect.max(0.05),
919            aperture_radius: 0.0,
920            focal_distance: focal_dist,
921        }
922    }
923
924    /// Configures thin-lens Depth-of-Field optics on this camera.
925    ///
926    /// # Arguments
927    ///
928    /// - `Self` - Base camera.
929    /// - `f32` - Lens aperture radius in meters (`0.0` = sharp pinhole).
930    /// - `f32` - Distance to the sharp focal plane in meters.
931    ///
932    /// # Returns
933    ///
934    /// - `Self` - Camera with thin-lens depth-of-field parameters.
935    #[must_use]
936    pub fn with_thin_lens(mut self, aperture_radius: f32, focal_distance: f32) -> Self {
937        self.set_aperture_radius(aperture_radius.max(0.0));
938        self.set_focal_distance(focal_distance.max(0.05));
939        self
940    }
941
942    /// Converts an existing `euv-core` `Camera3D` into a matching `RtCamera`.
943    ///
944    /// # Arguments
945    ///
946    /// - `&Camera3D` - Source 3D viewport camera.
947    /// - `f32` - Viewport width-to-height aspect ratio.
948    ///
949    /// # Returns
950    ///
951    /// - `Self` - Matching ray-tracing camera.
952    #[must_use]
953    pub fn from_camera3d(camera: &Camera3D, aspect: f32) -> Self {
954        let pos: Vec3 = camera.get_position();
955        let forward: Vec3 = camera.forward();
956        let right: Vec3 = camera.right();
957        let up: Vec3 = right.cross(forward).normalize();
958        let fov_rad: f32 = Camera3D::effective_vertical_fov_rad(camera.get_fov_deg(), aspect);
959        Self {
960            position: pos,
961            forward,
962            right,
963            up,
964            fov_y_rad: fov_rad,
965            aspect: aspect.max(0.05),
966            aperture_radius: 0.0,
967            focal_distance: 5.0,
968        }
969    }
970
971    /// Generates a world-space primary ray for pixel `(px, py)` with sub-pixel anti-aliasing jitter and thin-lens aperture sampling.
972    ///
973    /// # Arguments
974    ///
975    /// - `&Self` - Camera reference.
976    /// - `[u32; 2]` - Integer pixel coordinates `[px, py]`.
977    /// - `[u32; 2]` - Viewport resolution `[width, height]`.
978    /// - `[f32; 2]` - Sub-pixel offset in `[0.0, 1.0)^2` (e.g., from `r2_subpixel_jitter` or Halton).
979    /// - `[f32; 2]` - Uniform lens sample in `[0.0, 1.0)^2` for thin-lens DoF.
980    ///
981    /// # Returns
982    ///
983    /// - `Ray3D` - Normalized world-space camera ray.
984    #[must_use]
985    pub fn generate_ray(
986        &self,
987        pixel: [u32; 2],
988        resolution: [u32; 2],
989        pixel_jitter: [f32; 2],
990        lens_sample: [f32; 2],
991    ) -> Ray3D {
992        let w: f32 = resolution[0].max(1) as f32;
993        let h: f32 = resolution[1].max(1) as f32;
994        let u: f32 = ((pixel[0] as f32) + pixel_jitter[0].clamp(0.0, 1.0)) / w;
995        let v: f32 = ((pixel[1] as f32) + pixel_jitter[1].clamp(0.0, 1.0)) / h;
996        let half_h: f32 = (self.get_fov_y_rad() * 0.5).tan();
997        let half_w: f32 = half_h * self.get_aspect();
998        let ndc_x: f32 = (2.0 * u - 1.0) * half_w;
999        let ndc_y: f32 = (1.0 - 2.0 * v) * half_h;
1000        let forward: Vec3 = self.get_forward();
1001        let right: Vec3 = self.get_right();
1002        let up: Vec3 = self.get_up();
1003        let pinhole_dir: Vec3 = forward
1004            .add(right.scale(ndc_x))
1005            .add(up.scale(ndc_y))
1006            .normalize();
1007        let aperture: f32 = self.get_aperture_radius();
1008        let origin: Vec3 = self.get_position();
1009        if aperture <= RT_SCENE_EPSILON {
1010            return Ray3D::new(origin, pinhole_dir);
1011        }
1012        let cos_view: f32 = pinhole_dir.dot(forward).max(1e-4);
1013        let t_focus: f32 = self.get_focal_distance() / cos_view;
1014        let focus_point: Vec3 = origin.add(pinhole_dir.scale(t_focus));
1015        let disk: [f32; 2] = concentric_sample_disk(lens_sample);
1016        let lens_origin: Vec3 = origin
1017            .add(right.scale(disk[0] * aperture))
1018            .add(up.scale(disk[1] * aperture));
1019        Ray3D::new(lens_origin, focus_point.sub(lens_origin))
1020    }
1021
1022    /// Computes a deterministic bit-exact 64-bit fingerprint of camera pose and optics for temporal accumulation reset detection.
1023    ///
1024    /// # Arguments
1025    ///
1026    /// - `&Self` - Camera reference.
1027    ///
1028    /// # Returns
1029    ///
1030    /// - `u64` - Stable 64-bit hash changing whenever any camera parameter mutates.
1031    #[must_use]
1032    pub fn motion_fingerprint(&self) -> u64 {
1033        let mut h: u64 = RT_FNV_OFFSET_BASIS;
1034        h = fnv1a_mix_vec3(h, self.get_position());
1035        h = fnv1a_mix_vec3(h, self.get_forward());
1036        h = fnv1a_mix_vec3(h, self.get_right());
1037        h = fnv1a_mix_vec3(h, self.get_up());
1038        h = fnv1a_mix_f32(h, self.get_fov_y_rad());
1039        h = fnv1a_mix_f32(h, self.get_aspect());
1040        h = fnv1a_mix_f32(h, self.get_aperture_radius());
1041        fnv1a_mix_f32(h, self.get_focal_distance())
1042    }
1043}
1044
1045/// Default empty ray-tracing scene constructor for `RaytraceScene`.
1046impl Default for RaytraceScene {
1047    /// Creates an empty `RaytraceScene` with a default matte material at slot `0`.
1048    ///
1049    /// # Returns
1050    ///
1051    /// - `Self` - Empty scene ready for geometry and lights.
1052    fn default() -> Self {
1053        Self::new()
1054    }
1055}
1056
1057/// Geometry management, unified ray queries, environment shading, and `World3D` conversion for `RaytraceScene`.
1058impl RaytraceScene {
1059    /// Creates an empty ray-tracing scene with a default neutral diffuse material registered at index `0`.
1060    ///
1061    /// # Returns
1062    ///
1063    /// - `Self` - Empty `RaytraceScene`.
1064    #[must_use]
1065    pub fn new() -> Self {
1066        Self {
1067            blas_list: Vec::new(),
1068            tlas: Tlas3D::new(),
1069            primitives: Vec::new(),
1070            sdf_tracers: Vec::new(),
1071            materials: vec![RtMaterial::default()],
1072            lights: Vec::new(),
1073            environment: RtEnvironment::Black,
1074            camera: RtCamera::default(),
1075            revision: 1,
1076        }
1077    }
1078
1079    /// Increments the scene revision counter so temporal accumulators invalidate stale frames.
1080    ///
1081    /// # Arguments
1082    ///
1083    /// - `&Self` - Mutable scene reference.
1084    pub fn bump_revision(&mut self) {
1085        let next: u64 = self.get_revision().wrapping_add(1);
1086        self.set_revision(next);
1087    }
1088
1089    /// Registers a material and returns its `material_id`.
1090    ///
1091    /// # Arguments
1092    ///
1093    /// - `&Self` - Mutable scene reference.
1094    /// - `RtMaterial` - Physical material descriptor.
1095    ///
1096    /// # Returns
1097    ///
1098    /// - `u32` - Registered material index.
1099    pub fn add_material(&mut self, material: RtMaterial) -> u32 {
1100        let id: u32 = self.get_materials().len() as u32;
1101        self.get_mut_materials().push(material);
1102        self.bump_revision();
1103        id
1104    }
1105
1106    /// Registers a prebuilt `Blas3D` and returns its `blas_id`.
1107    ///
1108    /// # Arguments
1109    ///
1110    /// - `&Self` - Mutable scene reference.
1111    /// - `Blas3D` - Bottom-level triangle BVH.
1112    ///
1113    /// # Returns
1114    ///
1115    /// - `u32` - Registered BLAS index.
1116    pub fn add_blas(&mut self, blas: Blas3D) -> u32 {
1117        let id: u32 = self.get_blas_list().len() as u32;
1118        self.get_mut_blas_list().push(blas);
1119        self.bump_revision();
1120        id
1121    }
1122
1123    /// Builds and registers a `Blas3D` from an existing `Mesh3D` and returns its `blas_id`.
1124    ///
1125    /// # Arguments
1126    ///
1127    /// - `&Self` - Mutable scene reference.
1128    /// - `&Mesh3D` - Source mesh geometry.
1129    ///
1130    /// # Returns
1131    ///
1132    /// - `u32` - Registered BLAS index.
1133    pub fn add_mesh(&mut self, mesh: &Mesh3D) -> u32 {
1134        let blas: Blas3D = Blas3D::from_mesh(mesh);
1135        self.add_blas(blas)
1136    }
1137
1138    /// Adds a transformed mesh instance referencing `blas_id` and returns its stable `instance_id`.
1139    ///
1140    /// # Arguments
1141    ///
1142    /// - `&Self` - Mutable scene reference.
1143    /// - `u32` - Registered BLAS index.
1144    /// - `Mat4` - Local-to-world affine transform matrix.
1145    /// - `u32` - Material index.
1146    ///
1147    /// # Returns
1148    ///
1149    /// - `usize` - Stable TLAS instance identifier.
1150    pub fn add_instance(&mut self, blas_id: u32, transform: Mat4, material_id: u32) -> usize {
1151        let local_bounds: AxisAlignedBox3D = self
1152            .get_blas_list()
1153            .get(blas_id as usize)
1154            .map_or(AxisAlignedBox3D::empty(), |blas: &Blas3D| blas.get_bounds());
1155        let instance: RtInstance = RtInstance::new(blas_id, transform, material_id, local_bounds);
1156        let id: usize = self.get_mut_tlas().add_instance(instance);
1157        self.bump_revision();
1158        id
1159    }
1160
1161    /// Updates an existing instance's world transform without rebuilding its underlying `Blas3D`.
1162    ///
1163    /// # Arguments
1164    ///
1165    /// - `&Self` - Mutable scene reference.
1166    /// - `usize` - Stable instance identifier.
1167    /// - `Mat4` - Updated local-to-world affine transform.
1168    ///
1169    /// # Returns
1170    ///
1171    /// - `bool` - `true` when the instance existed and was updated.
1172    pub fn update_instance_transform(&mut self, instance_id: usize, transform: Mat4) -> bool {
1173        let blas_id_opt: Option<u32> = self
1174            .get_tlas()
1175            .get_instances()
1176            .get(instance_id)
1177            .map(|inst: &RtInstance| inst.get_blas_id());
1178        let blas_id: u32 = match blas_id_opt {
1179            Some(id) => id,
1180            None => return false,
1181        };
1182        let local_bounds: AxisAlignedBox3D = self
1183            .get_blas_list()
1184            .get(blas_id as usize)
1185            .map_or(AxisAlignedBox3D::empty(), |blas: &Blas3D| blas.get_bounds());
1186        let updated: bool =
1187            self.get_mut_tlas()
1188                .update_instance_transform(instance_id, transform, local_bounds);
1189        if updated {
1190            self.bump_revision();
1191        }
1192        updated
1193    }
1194
1195    /// Appends an analytic primitive to the scene and returns its index.
1196    ///
1197    /// # Arguments
1198    ///
1199    /// - `&Self` - Mutable scene reference.
1200    /// - `RtPrimitive` - Bound analytic primitive.
1201    ///
1202    /// # Returns
1203    ///
1204    /// - `usize` - Analytic primitive index.
1205    pub fn add_primitive(&mut self, primitive: RtPrimitive) -> usize {
1206        let id: usize = self.get_primitives().len();
1207        self.get_mut_primitives().push(primitive);
1208        self.bump_revision();
1209        id
1210    }
1211
1212    /// Appends an implicit SDF sphere-tracer volume to the scene and returns its index.
1213    ///
1214    /// # Arguments
1215    ///
1216    /// - `&Self` - Mutable scene reference.
1217    /// - `SdfSphereTracer` - Configured SDF volume.
1218    ///
1219    /// # Returns
1220    ///
1221    /// - `usize` - SDF volume index.
1222    pub fn add_sdf_tracer(&mut self, tracer: SdfSphereTracer) -> usize {
1223        let id: usize = self.get_sdf_tracers().len();
1224        self.get_mut_sdf_tracers().push(tracer);
1225        self.bump_revision();
1226        id
1227    }
1228
1229    /// Appends a physical light emitter to the scene and returns its index.
1230    ///
1231    /// # Arguments
1232    ///
1233    /// - `&Self` - Mutable scene reference.
1234    /// - `RtLight` - Light descriptor.
1235    ///
1236    /// # Returns
1237    ///
1238    /// - `usize` - Light index.
1239    pub fn add_light(&mut self, light: RtLight) -> usize {
1240        let id: usize = self.get_lights().len();
1241        self.get_mut_lights().push(light);
1242        self.bump_revision();
1243        id
1244    }
1245
1246    /// Rebuilds the scene TLAS using the binned Surface Area Heuristic.
1247    ///
1248    /// # Arguments
1249    ///
1250    /// - `&Self` - Mutable scene reference.
1251    pub fn rebuild_tlas(&mut self) {
1252        self.get_mut_tlas().rebuild();
1253        self.bump_revision();
1254    }
1255
1256    /// Refits the scene TLAS bottom-up in O(N) with zero heap allocation after moving instances.
1257    ///
1258    /// # Arguments
1259    ///
1260    /// - `&Self` - Mutable scene reference.
1261    pub fn refit_tlas(&mut self) {
1262        self.get_mut_tlas().refit();
1263        self.bump_revision();
1264    }
1265
1266    /// Returns the `RtMaterial` registered at `material_id`, falling back to a default diffuse material if out of bounds.
1267    ///
1268    /// # Arguments
1269    ///
1270    /// - `&Self` - Scene reference.
1271    /// - `u32` - Material identifier.
1272    ///
1273    /// # Returns
1274    ///
1275    /// - `RtMaterial` - Resolved material descriptor.
1276    #[must_use]
1277    pub fn material(&self, material_id: u32) -> RtMaterial {
1278        self.get_materials()
1279            .get(material_id as usize)
1280            .copied()
1281            .unwrap_or_default()
1282    }
1283
1284    /// Traces a world-space ray against the TLAS, analytic primitives, and SDF volumes returning the globally closest hit.
1285    ///
1286    /// # Arguments
1287    ///
1288    /// - `&Self` - Scene reference.
1289    /// - `&Ray3D` - World-space normalized ray.
1290    /// - `f32` - Minimum accepted hit distance.
1291    /// - `f32` - Maximum accepted hit distance.
1292    ///
1293    /// # Returns
1294    ///
1295    /// - `Option<RtHit>` - Globally closest surface hit if any.
1296    #[must_use]
1297    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RtHit> {
1298        let mut best_t: f32 = t_max;
1299        let mut best_hit: Option<RtHit> =
1300            self.get_tlas()
1301                .trace_closest(self.get_blas_list().as_slice(), ray, t_min, best_t);
1302        if let Some(hit) = best_hit {
1303            best_t = hit.get_distance();
1304        }
1305        for (idx, prim) in self.get_primitives().iter().enumerate() {
1306            if let Some(hit) = prim.intersect(ray, t_min, best_t, idx as u32) {
1307                best_t = hit.get_distance();
1308                best_hit = Some(hit);
1309            }
1310        }
1311        let prim_offset: u32 = self.get_primitives().len() as u32;
1312        for (idx, sdf) in self.get_sdf_tracers().iter().enumerate() {
1313            if let Some(hit) = sdf.trace(ray, t_min, best_t, prim_offset + (idx as u32)) {
1314                best_t = hit.get_distance();
1315                best_hit = Some(hit);
1316            }
1317        }
1318        best_hit
1319    }
1320
1321    /// Tests whether a world-space ray is occluded by any TLAS mesh, analytic primitive, or SDF volume in `[t_min, t_max]`.
1322    ///
1323    /// # Arguments
1324    ///
1325    /// - `&Self` - Scene reference.
1326    /// - `&Ray3D` - World-space shadow or ambient-occlusion ray.
1327    /// - `f32` - Minimum accepted hit distance.
1328    /// - `f32` - Maximum accepted hit distance.
1329    ///
1330    /// # Returns
1331    ///
1332    /// - `bool` - `true` when any occluder intersects the ray segment.
1333    #[must_use]
1334    pub fn trace_any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1335        if self
1336            .get_tlas()
1337            .trace_any_hit(self.get_blas_list().as_slice(), ray, t_min, t_max)
1338        {
1339            return true;
1340        }
1341        for prim in self.get_primitives() {
1342            if prim.any_hit(ray, t_min, t_max) {
1343                return true;
1344            }
1345        }
1346        for sdf in self.get_sdf_tracers() {
1347            if sdf.any_hit(ray, t_min, t_max) {
1348                return true;
1349            }
1350        }
1351        false
1352    }
1353
1354    /// Intersects a ray against all finite area lights in the scene returning `(light_index, distance, radiance, solid_angle_pdf)` of the closest hit.
1355    ///
1356    /// # Arguments
1357    ///
1358    /// - `&Self` - Scene reference.
1359    /// - `&Ray3D` - World-space ray.
1360    /// - `f32` - Minimum accepted distance.
1361    /// - `f32` - Maximum accepted distance.
1362    ///
1363    /// # Returns
1364    ///
1365    /// - `Option<(usize, f32, Vec3, f32)>` - Closest intersected area light metadata if any.
1366    #[must_use]
1367    pub fn intersect_area_lights(
1368        &self,
1369        ray: &Ray3D,
1370        t_min: f32,
1371        t_max: f32,
1372    ) -> Option<(usize, f32, Vec3, f32)> {
1373        let mut best_t: f32 = t_max;
1374        let mut result: Option<(usize, f32, Vec3, f32)> = None;
1375        for (idx, light) in self.get_lights().iter().enumerate() {
1376            if let Some((dist, rad, pdf)) = light.intersect_area(ray, t_min, best_t) {
1377                best_t = dist;
1378                result = Some((idx, dist, rad, pdf));
1379            }
1380        }
1381        result
1382    }
1383
1384    /// Evaluates the background environment radiance along unit world-space direction `direction`.
1385    ///
1386    /// # Arguments
1387    ///
1388    /// - `&Self` - Scene reference.
1389    /// - `Vec3` - Escaping world-space ray direction.
1390    ///
1391    /// # Returns
1392    ///
1393    /// - `Vec3` - Linear HDR RGB sky or environment radiance.
1394    #[must_use]
1395    pub fn evaluate_environment(&self, direction: Vec3) -> Vec3 {
1396        let dir: Vec3 = direction.normalize();
1397        match self.get_environment() {
1398            RtEnvironment::Black => Vec3::zero(),
1399            RtEnvironment::Solid(color) => Vec3::new(
1400                color.get_x().max(0.0),
1401                color.get_y().max(0.0),
1402                color.get_z().max(0.0),
1403            ),
1404            RtEnvironment::GradientSky {
1405                zenith,
1406                horizon,
1407                ground,
1408                sun_dir,
1409                sun_color,
1410                sun_angular_radius_rad,
1411            } => {
1412                let y: f32 = dir.get_y();
1413                let mut sky: Vec3 = if y >= 0.0 {
1414                    let t: f32 = y.powf(0.55).clamp(0.0, 1.0);
1415                    horizon.lerp(zenith, t)
1416                } else {
1417                    let t: f32 = (-y).powf(0.45).clamp(0.0, 1.0);
1418                    horizon.lerp(ground, t)
1419                };
1420                if sun_angular_radius_rad > 1e-5 {
1421                    let cos_sun: f32 = dir.dot(sun_dir.normalize());
1422                    let cos_edge: f32 = sun_angular_radius_rad.cos();
1423                    if cos_sun >= cos_edge {
1424                        sky = sky.add(sun_color);
1425                    }
1426                }
1427                Vec3::new(
1428                    sky.get_x().max(0.0),
1429                    sky.get_y().max(0.0),
1430                    sky.get_z().max(0.0),
1431                )
1432            }
1433        }
1434    }
1435
1436    /// Bridges an existing `euv-core` `World3D` scene directly into a ready-to-trace `RaytraceScene`.
1437    ///
1438    /// # Arguments
1439    ///
1440    /// - `&World3D` - Source `euv-core` 3D world containing meshes, objects, lights, sky, and camera.
1441    /// - `f32` - Target viewport width-to-height aspect ratio.
1442    ///
1443    /// # Returns
1444    ///
1445    /// - `Self` - Populated `RaytraceScene` with built BLAS/TLAS acceleration structures.
1446    #[must_use]
1447    pub fn from_world3d(world: &World3D, aspect: f32) -> Self {
1448        let mut scene: Self = Self::new();
1449        let mesh_chains: &[MeshLodChain] = world.get_mesh_library().as_slice();
1450        let mut mesh_to_blas: Vec<Option<u32>> = Vec::with_capacity(mesh_chains.len());
1451        for chain in mesh_chains {
1452            if let Some(lod0) = chain.get_levels().first() {
1453                let blas_id: u32 = scene.add_mesh(lod0);
1454                mesh_to_blas.push(Some(blas_id));
1455            } else {
1456                mesh_to_blas.push(None);
1457            }
1458        }
1459        let principled_table: &[PrincipledMaterial3D] = world.get_principled_materials().as_slice();
1460        for (obj_idx, obj) in world.get_objects().iter().enumerate() {
1461            if !world.is_object_visible(obj_idx) {
1462                continue;
1463            }
1464            let mesh_id: usize = obj.get_mesh_id();
1465            let blas_id_opt: Option<u32> =
1466                if let Some(deformed) = world.deformed_mesh_for_object(obj_idx) {
1467                    Some(scene.add_mesh(deformed))
1468                } else {
1469                    mesh_to_blas.get(mesh_id).copied().flatten()
1470                };
1471            let blas_id: u32 = match blas_id_opt {
1472                Some(id) => id,
1473                None => continue,
1474            };
1475            let rt_mat: RtMaterial = match obj.try_get_principled_material_id() {
1476                Some(p_id) => match principled_table.get(p_id as usize) {
1477                    Some(p_mat) => RtMaterial::from_principled_material(p_mat),
1478                    None => RtMaterial::from_pbr_material(&obj.get_material()),
1479                },
1480                None => RtMaterial::from_pbr_material(&obj.get_material()),
1481            };
1482            let mat_id: u32 = scene.add_material(rt_mat);
1483            let model_mat: Mat4 = obj.get_transform().to_mat4();
1484            let _: usize = scene.add_instance(blas_id, model_mat, mat_id);
1485        }
1486        let sun: DirectionalLight3D = world.get_sun();
1487        let _: usize = scene.add_light(RtLight::directional(
1488            sun.get_direction(),
1489            sun.get_color(),
1490            2.2,
1491            0.015,
1492        ));
1493        scene.set_environment(RtEnvironment::GradientSky {
1494            zenith: sun.get_sky_zenith(),
1495            horizon: sun.get_sky_horizon(),
1496            ground: sun.get_sky_horizon().scale(0.25),
1497            sun_dir: sun.get_direction().normalize(),
1498            sun_color: sun.get_color().scale(6.0),
1499            sun_angular_radius_rad: 0.02,
1500        });
1501        for pt in world.get_point_lights() {
1502            let _: usize = scene.add_light(RtLight::point(
1503                pt.get_position(),
1504                pt.get_color(),
1505                pt.get_intensity(),
1506                (pt.get_radius() * 0.05).clamp(0.0, 0.25),
1507            ));
1508        }
1509        for sp in world.get_spot_lights() {
1510            let inner_deg: f32 = sp.get_inner_cos().clamp(-1.0, 1.0).acos().to_degrees();
1511            let outer_deg: f32 = sp.get_outer_cos().clamp(-1.0, 1.0).acos().to_degrees();
1512            let _: usize = scene.add_light(RtLight::spot(
1513                sp.get_position(),
1514                sp.get_direction(),
1515                sp.get_color(),
1516                sp.get_intensity(),
1517                inner_deg,
1518                outer_deg,
1519                0.05,
1520            ));
1521        }
1522        for area in world.get_area_lights() {
1523            let light: RtLight = match area.get_shape() {
1524                AreaLightShape3D::Rectangle => RtLight::rect_area(
1525                    area.get_position(),
1526                    area.get_direction(),
1527                    Vec2::new(area.get_width(), area.get_height()),
1528                    area.get_color(),
1529                    area.get_intensity(),
1530                    area.get_two_sided(),
1531                ),
1532                AreaLightShape3D::Disk => RtLight::disk_area(
1533                    area.get_position(),
1534                    area.get_direction(),
1535                    0.5 * area.get_width().max(area.get_height()),
1536                    area.get_color(),
1537                    area.get_intensity(),
1538                    area.get_two_sided(),
1539                ),
1540            };
1541            let _: usize = scene.add_light(light);
1542        }
1543        let world_cam: Camera3D = world.get_camera();
1544        scene.set_camera(RtCamera::from_camera3d(&world_cam, aspect));
1545        scene.rebuild_tlas();
1546        scene
1547    }
1548}
1549
1550/// Default empty builder constructor for `RaytraceSceneBuilder`.
1551impl Default for RaytraceSceneBuilder {
1552    /// Creates an empty `RaytraceSceneBuilder`.
1553    ///
1554    /// # Returns
1555    ///
1556    /// - `Self` - Empty builder.
1557    fn default() -> Self {
1558        Self::new()
1559    }
1560}
1561
1562/// Fluent scene assembly helpers and curated presets (Cornell Box, Glass Gallery, Lit Outdoor) for `RaytraceSceneBuilder`.
1563impl RaytraceSceneBuilder {
1564    /// Creates a new fluent `RaytraceSceneBuilder`.
1565    ///
1566    /// # Returns
1567    ///
1568    /// - `Self` - Builder wrapping an empty `RaytraceScene`.
1569    #[must_use]
1570    pub fn new() -> Self {
1571        Self {
1572            scene: RaytraceScene::new(),
1573        }
1574    }
1575
1576    /// Configures the camera on the scene under construction.
1577    ///
1578    /// # Arguments
1579    ///
1580    /// - `Self` - Builder value.
1581    /// - `RtCamera` - Camera configuration.
1582    ///
1583    /// # Returns
1584    ///
1585    /// - `Self` - Updated builder.
1586    #[must_use]
1587    pub fn with_camera(mut self, camera: RtCamera) -> Self {
1588        self.get_mut_scene().set_camera(camera);
1589        self
1590    }
1591
1592    /// Configures the background environment dome on the scene under construction.
1593    ///
1594    /// # Arguments
1595    ///
1596    /// - `Self` - Builder value.
1597    /// - `RtEnvironment` - Environment dome.
1598    ///
1599    /// # Returns
1600    ///
1601    /// - `Self` - Updated builder.
1602    #[must_use]
1603    pub fn with_environment(mut self, environment: RtEnvironment) -> Self {
1604        self.get_mut_scene().set_environment(environment);
1605        self
1606    }
1607
1608    /// Adds a light emitter to the scene under construction.
1609    ///
1610    /// # Arguments
1611    ///
1612    /// - `Self` - Builder value.
1613    /// - `RtLight` - Physical light emitter.
1614    ///
1615    /// # Returns
1616    ///
1617    /// - `Self` - Updated builder.
1618    #[must_use]
1619    pub fn with_light(mut self, light: RtLight) -> Self {
1620        let _: usize = self.get_mut_scene().add_light(light);
1621        self
1622    }
1623
1624    /// Finalizes the scene, rebuilding the TLAS and returning the completed `RaytraceScene`.
1625    ///
1626    /// # Arguments
1627    ///
1628    /// - `Self` - Completed builder.
1629    ///
1630    /// # Returns
1631    ///
1632    /// - `RaytraceScene` - Ready-to-trace scene.
1633    #[must_use]
1634    pub fn build(mut self) -> RaytraceScene {
1635        self.get_mut_scene().rebuild_tlas();
1636        let Self { scene } = self;
1637        scene
1638    }
1639
1640    /// Constructs the classic Cornell Box showcase scene featuring matte walls, ceiling area light, rotated box mesh, glossy metal sphere, and refractive Beer-Lambert glass sphere.
1641    ///
1642    /// # Arguments
1643    ///
1644    /// - `f32` - Viewport width-to-height aspect ratio.
1645    ///
1646    /// # Returns
1647    ///
1648    /// - `RaytraceScene` - Ready-to-trace Cornell Box scene.
1649    #[must_use]
1650    pub fn cornell_box(aspect: f32) -> RaytraceScene {
1651        let mut scene: RaytraceScene = RaytraceScene::new();
1652        let white_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.76, 0.75, 0.72)));
1653        let red_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.68, 0.12, 0.10)));
1654        let green_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.14, 0.52, 0.18)));
1655        let metal_mat: u32 =
1656            scene.add_material(RtMaterial::metal(Vec3::new(0.95, 0.80, 0.45), 0.14));
1657        let glass_mat: u32 = scene.add_material(RtMaterial::dielectric(
1658            Vec3::splat(1.0),
1659            RT_DEFAULT_GLASS_IOR,
1660            0.0,
1661            Vec3::new(0.18, 0.04, 0.08),
1662        ));
1663        let _: usize = scene.add_primitive(RtPrimitive::new(
1664            RtPrimitiveShape::Quad {
1665                corner: Vec3::new(-2.0, 0.0, -2.0),
1666                edge_u: Vec3::new(0.0, 0.0, 4.0),
1667                edge_v: Vec3::new(4.0, 0.0, 0.0),
1668            },
1669            white_mat,
1670        ));
1671        let _: usize = scene.add_primitive(RtPrimitive::new(
1672            RtPrimitiveShape::Quad {
1673                corner: Vec3::new(-2.0, 4.0, -2.0),
1674                edge_u: Vec3::new(4.0, 0.0, 0.0),
1675                edge_v: Vec3::new(0.0, 0.0, 4.0),
1676            },
1677            white_mat,
1678        ));
1679        let _: usize = scene.add_primitive(RtPrimitive::new(
1680            RtPrimitiveShape::Quad {
1681                corner: Vec3::new(-2.0, 0.0, -2.0),
1682                edge_u: Vec3::new(4.0, 0.0, 0.0),
1683                edge_v: Vec3::new(0.0, 4.0, 0.0),
1684            },
1685            white_mat,
1686        ));
1687        let _: usize = scene.add_primitive(RtPrimitive::new(
1688            RtPrimitiveShape::Quad {
1689                corner: Vec3::new(-2.0, 0.0, -2.0),
1690                edge_u: Vec3::new(0.0, 4.0, 0.0),
1691                edge_v: Vec3::new(0.0, 0.0, 4.0),
1692            },
1693            red_mat,
1694        ));
1695        let _: usize = scene.add_primitive(RtPrimitive::new(
1696            RtPrimitiveShape::Quad {
1697                corner: Vec3::new(2.0, 0.0, -2.0),
1698                edge_u: Vec3::new(0.0, 0.0, 4.0),
1699                edge_v: Vec3::new(0.0, 4.0, 0.0),
1700            },
1701            green_mat,
1702        ));
1703        let cube_mesh: Mesh3D = Mesh3D::box_mesh(
1704            RT_CORNELL_BOX_CUBE_NAME,
1705            1.1,
1706            1.8,
1707            1.1,
1708            true,
1709            PbrMaterial::default(),
1710        );
1711        let cube_blas: u32 = scene.add_mesh(&cube_mesh);
1712        let cube_xform: Mat4 = Mat4::from_trs(Vec3::new(-0.75, 0.0, -0.65), 0.38, Vec3::splat(1.0));
1713        let _: usize = scene.add_instance(cube_blas, cube_xform, white_mat);
1714        let _: usize = scene.add_primitive(RtPrimitive::new(
1715            RtPrimitiveShape::Sphere {
1716                center: Vec3::new(0.85, 0.65, -0.45),
1717                radius: 0.65,
1718            },
1719            metal_mat,
1720        ));
1721        let _: usize = scene.add_primitive(RtPrimitive::new(
1722            RtPrimitiveShape::Sphere {
1723                center: Vec3::new(-0.15, 0.55, 0.72),
1724                radius: 0.55,
1725            },
1726            glass_mat,
1727        ));
1728        let _: usize = scene.add_light(RtLight::rect_area(
1729            Vec3::new(0.0, 3.97, 0.0),
1730            Vec3::new(0.0, -1.0, 0.0),
1731            Vec2::new(1.4, 1.4),
1732            Vec3::new(1.0, 0.94, 0.84),
1733            16.0,
1734            false,
1735        ));
1736        scene.set_environment(RtEnvironment::Black);
1737        scene.set_camera(RtCamera::look_at(
1738            Vec3::new(0.0, 2.0, 5.4),
1739            Vec3::new(0.0, 1.85, 0.0),
1740            Vec3::new(0.0, 1.0, 0.0),
1741            42.0,
1742            aspect,
1743        ));
1744        scene.rebuild_tlas();
1745        scene
1746    }
1747
1748    /// Constructs a reflective and refractive glass gallery showcasing Beer-Lambert absorption, clearcoat, mirror chrome, and SDF CSG geometry.
1749    ///
1750    /// # Arguments
1751    ///
1752    /// - `f32` - Viewport width-to-height aspect ratio.
1753    ///
1754    /// # Returns
1755    ///
1756    /// - `RaytraceScene` - Ready-to-trace glass gallery scene.
1757    #[must_use]
1758    pub fn glass_gallery(aspect: f32) -> RaytraceScene {
1759        let mut scene: RaytraceScene = RaytraceScene::new();
1760        let floor_mat: u32 = scene.add_material(RtMaterial::clearcoat(
1761            Vec3::new(0.18, 0.20, 0.24),
1762            0.35,
1763            0.85,
1764            0.05,
1765        ));
1766        let pedestal_mat: u32 =
1767            scene.add_material(RtMaterial::oren_nayar(Vec3::new(0.72, 0.70, 0.66), 0.4));
1768        let chrome_mat: u32 = scene.add_material(RtMaterial::mirror(Vec3::splat(0.96)));
1769        let emerald_glass: u32 = scene.add_material(RtMaterial::dielectric(
1770            Vec3::splat(1.0),
1771            1.52,
1772            0.0,
1773            Vec3::new(0.85, 0.12, 0.35),
1774        ));
1775        let sapphire_glass: u32 = scene.add_material(RtMaterial::dielectric(
1776            Vec3::splat(1.0),
1777            1.45,
1778            0.03,
1779            Vec3::new(0.75, 0.30, 0.05),
1780        ));
1781        let _: usize = scene.add_primitive(RtPrimitive::new(
1782            RtPrimitiveShape::Plane {
1783                point: Vec3::zero(),
1784                normal: Vec3::new(0.0, 1.0, 0.0),
1785            },
1786            floor_mat,
1787        ));
1788        let ped_mesh: Mesh3D = Mesh3D::box_mesh(
1789            RT_GALLERY_PEDESTAL_NAME,
1790            4.2,
1791            0.25,
1792            2.2,
1793            true,
1794            PbrMaterial::default(),
1795        );
1796        let ped_blas: u32 = scene.add_mesh(&ped_mesh);
1797        let _: usize = scene.add_instance(ped_blas, Mat4::identity(), pedestal_mat);
1798        let _: usize = scene.add_primitive(RtPrimitive::new(
1799            RtPrimitiveShape::Sphere {
1800                center: Vec3::new(-1.3, 0.9, 0.0),
1801                radius: 0.65,
1802            },
1803            emerald_glass,
1804        ));
1805        let _: usize = scene.add_primitive(RtPrimitive::new(
1806            RtPrimitiveShape::Sphere {
1807                center: Vec3::new(1.3, 0.9, 0.0),
1808                radius: 0.65,
1809            },
1810            chrome_mat,
1811        ));
1812        let mut sdf: SdfSphereTracer = SdfSphereTracer::new(
1813            sapphire_glass,
1814            AxisAlignedBox3D::new(Vec3::new(-0.8, 0.2, -0.8), Vec3::new(0.8, 1.8, 0.8)),
1815        );
1816        let s_box: u32 = sdf.push_op(RtSdfOp::Box {
1817            center: Vec3::new(0.0, 0.95, 0.0),
1818            half_extents: Vec3::splat(0.45),
1819            rounding: 0.06,
1820        });
1821        let s_cut: u32 = sdf.push_op(RtSdfOp::Sphere {
1822            center: Vec3::new(0.0, 0.95, 0.0),
1823            radius: 0.56,
1824        });
1825        let _: u32 = sdf.push_op(RtSdfOp::SmoothSubtract {
1826            base: s_box,
1827            cutout: s_cut,
1828            smoothness: 0.04,
1829        });
1830        let _: usize = scene.add_sdf_tracer(sdf);
1831        let _: usize = scene.add_light(RtLight::rect_area(
1832            Vec3::new(-2.4, 3.6, 2.0),
1833            Vec3::new(0.45, -0.8, -0.38),
1834            Vec2::new(2.0, 1.2),
1835            Vec3::new(1.0, 0.96, 0.90),
1836            9.0,
1837            false,
1838        ));
1839        let _: usize = scene.add_light(RtLight::disk_area(
1840            Vec3::new(2.8, 3.2, -1.6),
1841            Vec3::new(-0.6, -0.7, 0.35),
1842            0.9,
1843            Vec3::new(0.75, 0.88, 1.0),
1844            8.0,
1845            false,
1846        ));
1847        scene.set_environment(RtEnvironment::GradientSky {
1848            zenith: Vec3::new(0.08, 0.12, 0.22),
1849            horizon: Vec3::new(0.22, 0.26, 0.34),
1850            ground: Vec3::new(0.05, 0.06, 0.08),
1851            sun_dir: Vec3::new(0.4, 0.8, 0.4).normalize(),
1852            sun_color: Vec3::new(2.0, 1.8, 1.6),
1853            sun_angular_radius_rad: 0.03,
1854        });
1855        scene.set_camera(
1856            RtCamera::look_at(
1857                Vec3::new(0.0, 1.65, 4.4),
1858                Vec3::new(0.0, 0.85, 0.0),
1859                Vec3::new(0.0, 1.0, 0.0),
1860                40.0,
1861                aspect,
1862            )
1863            .with_thin_lens(0.04, 4.4),
1864        );
1865        scene.rebuild_tlas();
1866        scene
1867    }
1868
1869    /// Constructs a sunlit outdoor preset with soft solar shadows, architectural monolith instances, metal and glass spheres, and physical sky dome.
1870    ///
1871    /// # Arguments
1872    ///
1873    /// - `f32` - Viewport width-to-height aspect ratio.
1874    ///
1875    /// # Returns
1876    ///
1877    /// - `RaytraceScene` - Ready-to-trace outdoor scene.
1878    #[must_use]
1879    pub fn lit_outdoor(aspect: f32) -> RaytraceScene {
1880        let mut scene: RaytraceScene = RaytraceScene::new();
1881        let ground_mat: u32 =
1882            scene.add_material(RtMaterial::oren_nayar(Vec3::new(0.42, 0.46, 0.38), 0.5));
1883        let stone_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.78, 0.74, 0.68)));
1884        let chrome_mat: u32 =
1885            scene.add_material(RtMaterial::metal(Vec3::new(0.92, 0.94, 0.96), 0.08));
1886        let water_glass: u32 = scene.add_material(RtMaterial::dielectric(
1887            Vec3::splat(1.0),
1888            RT_DEFAULT_WATER_IOR,
1889            0.01,
1890            Vec3::new(0.32, 0.08, 0.04),
1891        ));
1892        let _: usize = scene.add_primitive(RtPrimitive::new(
1893            RtPrimitiveShape::Plane {
1894                point: Vec3::zero(),
1895                normal: Vec3::new(0.0, 1.0, 0.0),
1896            },
1897            ground_mat,
1898        ));
1899        let mono_mesh: Mesh3D = Mesh3D::box_mesh(
1900            RT_OUTDOOR_MONOLITH_NAME,
1901            1.2,
1902            2.8,
1903            1.2,
1904            true,
1905            PbrMaterial::default(),
1906        );
1907        let mono_blas: u32 = scene.add_mesh(&mono_mesh);
1908        let _: usize = scene.add_instance(
1909            mono_blas,
1910            Mat4::from_trs(Vec3::new(-1.8, 0.0, -1.4), 0.25, Vec3::splat(1.0)),
1911            stone_mat,
1912        );
1913        let _: usize = scene.add_instance(
1914            mono_blas,
1915            Mat4::from_trs(Vec3::new(1.9, 0.0, -2.0), -0.32, Vec3::new(0.8, 0.7, 0.8)),
1916            stone_mat,
1917        );
1918        let _: usize = scene.add_primitive(RtPrimitive::new(
1919            RtPrimitiveShape::Sphere {
1920                center: Vec3::new(-0.35, 0.75, 0.4),
1921                radius: 0.75,
1922            },
1923            chrome_mat,
1924        ));
1925        let _: usize = scene.add_primitive(RtPrimitive::new(
1926            RtPrimitiveShape::Sphere {
1927                center: Vec3::new(1.05, 0.6, 0.95),
1928                radius: 0.6,
1929            },
1930            water_glass,
1931        ));
1932        let sun_dir: Vec3 = Vec3::new(0.55, 0.72, 0.42).normalize();
1933        let _: usize = scene.add_light(RtLight::directional(
1934            sun_dir,
1935            Vec3::new(1.0, 0.94, 0.84),
1936            3.2,
1937            0.025,
1938        ));
1939        scene.set_environment(RtEnvironment::GradientSky {
1940            zenith: Vec3::new(0.18, 0.42, 0.88),
1941            horizon: Vec3::new(0.68, 0.80, 0.96),
1942            ground: Vec3::new(0.20, 0.22, 0.18),
1943            sun_dir,
1944            sun_color: Vec3::new(10.0, 9.0, 7.5),
1945            sun_angular_radius_rad: 0.025,
1946        });
1947        scene.set_camera(RtCamera::look_at(
1948            Vec3::new(0.2, 1.8, 5.8),
1949            Vec3::new(0.0, 0.9, -0.3),
1950            Vec3::new(0.0, 1.0, 0.0),
1951            44.0,
1952            aspect,
1953        ));
1954        scene.rebuild_tlas();
1955        scene
1956    }
1957}