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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
use super::*;

/// Deterministic PCG32 seeding and uniform float generation for `RtRng`.
impl RtRng {
    /// Creates a deterministic `RtRng` initialized from a 64-bit seed.
    ///
    /// # Arguments
    ///
    /// - `u64` - Seed integer.
    ///
    /// # Returns
    ///
    /// - `Self` - Seeded RNG instance.
    #[must_use]
    pub fn from_seed(seed: u64) -> Self {
        let mut rng: Self = Self {
            state: 0,
            inc: RT_PCG_INC | 1,
        };
        let _: u32 = rng.next_u32();
        let next_state: u64 = rng.get_state().wrapping_add(seed);
        rng.set_state(next_state);
        let _: u32 = rng.next_u32();
        rng
    }

    /// Creates a decorrelated deterministic `RtRng` for a specific pixel, sample index, and base seed using Wang hashing.
    ///
    /// # Arguments
    ///
    /// - `u32` - Linear pixel index.
    /// - `u32` - Progressive sample index.
    /// - `u32` - User-configured base seed.
    ///
    /// # Returns
    ///
    /// - `Self` - Decorrelated per-pixel RNG.
    #[must_use]
    pub fn from_pixel_sample(pixel_index: u32, sample_index: u32, base_seed: u32) -> Self {
        let h0: u32 = wang_hash(pixel_index ^ wang_hash(sample_index.wrapping_mul(16_645_251)));
        let h1: u32 = wang_hash(base_seed ^ wang_hash(sample_index.wrapping_add(1_013_904_223)));
        let combined: u64 = ((h0 as u64) << 32) | (h1 as u64);
        Self::from_seed(combined)
    }

    /// Advances the PCG32 state and returns a uniformly distributed `u32`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable RNG reference.
    ///
    /// # Returns
    ///
    /// - `u32` - Next pseudo-random 32-bit unsigned integer.
    pub fn next_u32(&mut self) -> u32 {
        let old_state: u64 = self.get_state();
        let next_state: u64 = old_state
            .wrapping_mul(RT_PCG_MULT)
            .wrapping_add(self.get_inc());
        self.set_state(next_state);
        let xorshifted: u32 = (((old_state >> 18) ^ old_state) >> 27) as u32;
        let rot: u32 = (old_state >> 59) as u32;
        xorshifted.rotate_right(rot)
    }

    /// Generates a uniform floating-point number in `[0.0, 1.0)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable RNG reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Uniform random float in `[0.0, 1.0)`.
    pub fn next_f32(&mut self) -> f32 {
        let bits: u32 = self.next_u32() >> 8;
        (bits as f32) * (1.0 / 16_777_216.0)
    }

    /// Generates a pair of independent uniform floating-point numbers in `[0.0, 1.0)^2`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable RNG reference.
    ///
    /// # Returns
    ///
    /// - `[f32; 2]` - Pair of independent random floats.
    pub fn next_f32_pair(&mut self) -> [f32; 2] {
        [self.next_f32(), self.next_f32()]
    }
}

/// Ray counter accumulation and summation helpers for `RtRayCounter`.
impl RtRayCounter {
    /// Increments the primary ray count by `count`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable ray counter.
    /// - `u64` - Number of primary rays to add.
    pub fn add_primary(&mut self, count: u64) {
        let next: u64 = self.get_primary_rays().saturating_add(count);
        self.set_primary_rays(next);
    }

    /// Increments the shadow/occlusion ray count by `count`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable ray counter.
    /// - `u64` - Number of shadow rays to add.
    pub fn add_shadow(&mut self, count: u64) {
        let next: u64 = self.get_shadow_rays().saturating_add(count);
        self.set_shadow_rays(next);
    }

    /// Increments the secondary bounce ray count by `count`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable ray counter.
    /// - `u64` - Number of secondary bounce rays to add.
    pub fn add_bounce(&mut self, count: u64) {
        let next: u64 = self.get_bounce_rays().saturating_add(count);
        self.set_bounce_rays(next);
    }

    /// Merges another `RtRayCounter` into `self`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable ray counter.
    /// - `Self` - Counter values to accumulate.
    pub fn merge(&mut self, other: Self) {
        self.add_primary(other.get_primary_rays());
        self.add_shadow(other.get_shadow_rays());
        self.add_bounce(other.get_bounce_rays());
    }

    /// Returns the total rays cast across primary, shadow, and bounce categories.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Ray counter reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Total ray count.
    #[must_use]
    pub fn total_rays(&self) -> u64 {
        self.get_primary_rays()
            .saturating_add(self.get_shadow_rays())
            .saturating_add(self.get_bounce_rays())
    }
}

/// Default configuration for `WhittedIntegrator`.
impl Default for WhittedIntegrator {
    /// Creates a `WhittedIntegrator` with 6-bounce recursion and 4 soft shadow samples.
    ///
    /// # Returns
    ///
    /// - `Self` - Default Whitted integrator.
    fn default() -> Self {
        Self {
            max_depth: RT_DEFAULT_WHITTED_DEPTH,
            shadow_samples: RT_DEFAULT_WHITTED_SHADOW_SAMPLES,
            ambient_scale: 0.08,
            firefly_clamp: RT_DEFAULT_FIREFLY_CLAMP,
        }
    }
}

/// Recursive Whitted reflection, Snell refraction with Beer-Lambert attenuation, and soft shadow shading for `WhittedIntegrator`.
impl WhittedIntegrator {
    /// Traces a primary camera ray using recursive Whitted shading and records primary G-buffer attributes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Whitted integrator configuration.
    /// - `&RaytraceScene` - Scene to intersect.
    /// - `&Ray3D` - Primary world-space ray.
    /// - `&mut RtRng` - Deterministic RNG for soft area shadow sampling.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `RtSampleOutput` - Shaded HDR radiance plus primary albedo, normal, and linear depth.
    #[must_use]
    pub fn trace_ray(
        &self,
        scene: &RaytraceScene,
        ray: &Ray3D,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> RtSampleOutput {
        counter.add_primary(1);
        let geom_hit: Option<RtHit> = scene.trace_closest(ray, RT_RAY_T_MIN, RT_RAY_T_MAX);
        let max_t: f32 = geom_hit.map_or(RT_RAY_T_MAX, |h: RtHit| h.get_distance());
        if let Some((_, light_t, light_rad, _)) =
            scene.intersect_area_lights(ray, RT_RAY_T_MIN, max_t)
        {
            let clean: Vec3 = sanitize_radiance(light_rad, self.get_firefly_clamp());
            return RtSampleOutput::new(
                clean,
                Vec3::splat(1.0),
                ray.get_direction().scale(-1.0),
                light_t,
                true,
            );
        }
        let hit: RtHit = match geom_hit {
            Some(h) => h,
            None => {
                let sky: Vec3 = sanitize_radiance(
                    scene.evaluate_environment(ray.get_direction()),
                    self.get_firefly_clamp(),
                );
                return RtSampleOutput::new(sky, sky, Vec3::zero(), RT_SKY_DEPTH, false);
            }
        };
        let mat: RtMaterial = scene.material(hit.get_material_id());
        let rad: Vec3 = self.shade_hit(scene, ray, hit, 0, rng, counter);
        let clean: Vec3 = sanitize_radiance(rad, self.get_firefly_clamp());
        RtSampleOutput::new(
            clean,
            mat.get_albedo(),
            hit.get_shading_normal(),
            hit.get_distance(),
            true,
        )
    }

    /// Recursively traces a secondary ray at recursion level `depth`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Whitted integrator configuration.
    /// - `&RaytraceScene` - Scene to intersect.
    /// - `&Ray3D` - Secondary ray.
    /// - `u32` - Current recursion depth.
    /// - `&mut RtRng` - Deterministic RNG.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR RGB radiance returning along `ray`.
    #[must_use]
    fn trace_recursive(
        &self,
        scene: &RaytraceScene,
        ray: &Ray3D,
        depth: u32,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> Vec3 {
        let geom_hit: Option<RtHit> = scene.trace_closest(ray, RT_RAY_T_MIN, RT_RAY_T_MAX);
        let max_t: f32 = geom_hit.map_or(RT_RAY_T_MAX, |h: RtHit| h.get_distance());
        if let Some((_, _, light_rad, _)) = scene.intersect_area_lights(ray, RT_RAY_T_MIN, max_t) {
            return light_rad;
        }
        match geom_hit {
            Some(hit) => self.shade_hit(scene, ray, hit, depth, rng, counter),
            None => scene.evaluate_environment(ray.get_direction()),
        }
    }

    /// Evaluates Whitted shading (direct lighting, Fresnel reflection, Snell refraction, Beer-Lambert attenuation) at `hit`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Whitted integrator configuration.
    /// - `&RaytraceScene` - Scene reference.
    /// - `&Ray3D` - Incident ray.
    /// - `RtHit` - Surface intersection record.
    /// - `u32` - Current recursion depth.
    /// - `&mut RtRng` - Deterministic RNG.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR RGB radiance at `hit`.
    #[must_use]
    fn shade_hit(
        &self,
        scene: &RaytraceScene,
        ray: &Ray3D,
        hit: RtHit,
        depth: u32,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> Vec3 {
        let mat: RtMaterial = scene.material(hit.get_material_id());
        if mat.get_kind() == RtMaterialKind::Emissive {
            return mat.get_emission();
        }
        let normal: Vec3 = hit.get_shading_normal();
        let geom_n: Vec3 = hit.get_geometric_normal();
        let wo: Vec3 = ray.get_direction().scale(-1.0);
        let cos_i: f32 = wo.dot(normal).clamp(0.0, 1.0);
        let beer_atten: Vec3 = if !hit.get_front_face()
            && (mat.get_kind() == RtMaterialKind::Dielectric || mat.get_transmission() > 0.0)
        {
            mat.beer_lambert_transmittance(hit.get_distance())
        } else {
            Vec3::splat(1.0)
        };
        if mat.get_kind() == RtMaterialKind::Dielectric {
            if depth >= self.get_max_depth() {
                return Vec3::zero();
            }
            let ior: f32 = mat.get_ior().clamp(1.001, 3.0);
            let (eta_i, eta_t): (f32, f32) = if hit.get_front_face() {
                (1.0, ior)
            } else {
                (ior, 1.0)
            };
            let fresnel_r: f32 = fresnel_dielectric(cos_i, eta_i, eta_t);
            let refl_dir: Vec3 = ray.get_direction().reflect(normal).normalize();
            let refl_origin: Vec3 = offset_ray_origin(hit.get_point(), geom_n, refl_dir);
            let refl_ray: Ray3D = Ray3D::new(refl_origin, refl_dir);
            counter.add_bounce(1);
            let refl_rad: Vec3 = self.trace_recursive(scene, &refl_ray, depth + 1, rng, counter);
            let combined: Vec3 = if fresnel_r >= 0.9999 {
                refl_rad
            } else if let Some(refr_dir) = refract_snell(ray.get_direction(), normal, eta_i / eta_t)
            {
                let refr_origin: Vec3 = offset_ray_origin(hit.get_point(), geom_n, refr_dir);
                let refr_ray: Ray3D = Ray3D::new(refr_origin, refr_dir);
                counter.add_bounce(1);
                let refr_rad: Vec3 =
                    self.trace_recursive(scene, &refr_ray, depth + 1, rng, counter);
                refl_rad
                    .scale(fresnel_r)
                    .add(refr_rad.scale(1.0 - fresnel_r))
            } else {
                refl_rad
            };
            let tinted: Vec3 = combined.mul(mat.get_albedo());
            return tinted.mul(beer_atten);
        }
        let mut total: Vec3 = mat.get_emission();
        let direct: Vec3 = self.evaluate_direct_lights(scene, &mat, hit, wo, rng, counter);
        total = total.add(direct);
        let env_ambient: Vec3 = scene.evaluate_environment(normal);
        let ambient_fill: Vec3 = mat
            .get_albedo()
            .mul(env_ambient)
            .scale(self.get_ambient_scale() * (1.0 - mat.get_metallic()));
        total = total.add(ambient_fill);
        let should_reflect: bool = depth < self.get_max_depth()
            && (mat.get_kind() == RtMaterialKind::Metal
                || mat.get_clearcoat() > 0.05
                || (mat.get_kind() == RtMaterialKind::Principled && mat.get_roughness() < 0.35));
        if should_reflect {
            let refl_dir: Vec3 = ray.get_direction().reflect(normal).normalize();
            if refl_dir.dot(geom_n) > 0.0 {
                let refl_origin: Vec3 = offset_ray_origin(hit.get_point(), geom_n, refl_dir);
                let refl_ray: Ray3D = Ray3D::new(refl_origin, refl_dir);
                counter.add_bounce(1);
                let refl_rad: Vec3 =
                    self.trace_recursive(scene, &refl_ray, depth + 1, rng, counter);
                let f0: Vec3 = if mat.get_kind() == RtMaterialKind::Metal {
                    mat.get_albedo()
                } else {
                    Vec3::splat(0.04).lerp(mat.get_albedo(), mat.get_metallic())
                };
                let fresnel: Vec3 = fresnel_schlick(cos_i, f0);
                let gloss_fade: f32 = (1.0 - mat.get_roughness() * 0.8).clamp(0.1, 1.0);
                let refl_weight: Vec3 = if mat.get_kind() == RtMaterialKind::Metal {
                    fresnel
                } else {
                    fresnel.scale(gloss_fade.max(mat.get_clearcoat()))
                };
                total = total.add(refl_rad.mul(refl_weight));
            }
        }
        total.mul(beer_atten)
    }

    /// Evaluates direct multi-sample soft shadows and BSDF shading over all lights in `scene`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Whitted integrator configuration.
    /// - `&RaytraceScene` - Scene reference.
    /// - `&RtMaterial` - Surface material.
    /// - `RtHit` - Surface hit record.
    /// - `Vec3` - Outgoing view vector `wo`.
    /// - `&mut RtRng` - Deterministic RNG.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Summed direct HDR RGB radiance.
    #[must_use]
    fn evaluate_direct_lights(
        &self,
        scene: &RaytraceScene,
        material: &RtMaterial,
        hit: RtHit,
        wo: Vec3,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> Vec3 {
        let mut sum: Vec3 = Vec3::zero();
        let normal: Vec3 = hit.get_shading_normal();
        let geom_n: Vec3 = hit.get_geometric_normal();
        let soft_samples: u32 = self.get_shadow_samples().max(1);
        for light in scene.get_lights() {
            let is_soft: bool = match light.get_kind() {
                RtLightKind::Directional {
                    angular_radius_rad, ..
                } => angular_radius_rad > 1e-5,
                RtLightKind::Point { radius, .. } | RtLightKind::Spot { radius, .. } => {
                    radius > 1e-5
                }
                RtLightKind::RectArea { .. } | RtLightKind::DiskArea { .. } => true,
            };
            let n_samples: u32 = if is_soft { soft_samples } else { 1 };
            let inv_n: f32 = 1.0 / (n_samples as f32);
            let mut light_accum: Vec3 = Vec3::zero();
            for _ in 0..n_samples {
                let sample: RtLightSample =
                    light.sample_light(hit.get_point(), rng.next_f32_pair());
                let pdf: f32 = sample.get_pdf();
                if pdf <= RT_MIN_PDF {
                    continue;
                }
                let wi: Vec3 = sample.get_direction();
                let n_dot_l: f32 = normal.dot(wi);
                if n_dot_l <= RT_MIN_PDF {
                    continue;
                }
                let shadow_origin: Vec3 = offset_ray_origin(hit.get_point(), geom_n, wi);
                let shadow_max: f32 =
                    (sample.get_distance() - RT_SURFACE_BIAS * 2.0).max(RT_RAY_T_MIN);
                let shadow_ray: Ray3D = Ray3D::new(shadow_origin, wi);
                counter.add_shadow(1);
                if scene.trace_any_hit(&shadow_ray, RT_RAY_T_MIN, shadow_max) {
                    continue;
                }
                let (brdf, _): (Vec3, f32) = eval_material_bsdf_and_pdf(material, normal, wo, wi);
                let contrib: Vec3 = brdf
                    .mul(sample.get_radiance())
                    .scale(n_dot_l / pdf.max(RT_MIN_PDF));
                light_accum = light_accum.add(contrib);
            }
            sum = sum.add(light_accum.scale(inv_n));
        }
        sum
    }
}

/// Default configuration for `PathTraceIntegrator`.
impl Default for PathTraceIntegrator {
    /// Creates an unbiased Monte Carlo PBR `PathTraceIntegrator` with MIS NEE, power heuristic, and Russian roulette.
    ///
    /// # Returns
    ///
    /// - `Self` - Default path-tracing integrator.
    fn default() -> Self {
        Self {
            max_bounces: RT_DEFAULT_MAX_BOUNCES,
            rr_start_bounce: RT_DEFAULT_RR_START_BOUNCE,
            firefly_clamp: RT_DEFAULT_FIREFLY_CLAMP,
            enable_nee: true,
            enable_mis: true,
            use_power_heuristic: true,
        }
    }
}

/// Unbiased iterative Monte Carlo PBR path tracing with GGX VNDF, MIS NEE, Beer-Lambert dielectrics, and Russian roulette.
impl PathTraceIntegrator {
    /// Computes the configured MIS weight (`power` or `balance` heuristic).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Path tracer configuration.
    /// - `f32` - Primary strategy PDF.
    /// - `f32` - Competing strategy PDF.
    ///
    /// # Returns
    ///
    /// - `f32` - MIS weight in `[0.0, 1.0]`.
    #[must_use]
    fn mis_weight(&self, pdf_a: f32, pdf_b: f32) -> f32 {
        if self.get_use_power_heuristic() {
            mis_weight_power(pdf_a, pdf_b)
        } else {
            mis_weight_balance(pdf_a, pdf_b)
        }
    }

    /// Traces a single Monte Carlo path sample for `ray` with zero heap allocations and full G-buffer output.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Path tracer configuration.
    /// - `&RaytraceScene` - Scene to trace.
    /// - `&Ray3D` - Primary world-space camera ray.
    /// - `&mut RtRng` - Deterministic per-pixel RNG.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `RtSampleOutput` - Sanitized HDR path radiance plus primary G-buffer attributes.
    #[must_use]
    pub fn trace_ray(
        &self,
        scene: &RaytraceScene,
        ray: &Ray3D,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> RtSampleOutput {
        counter.add_primary(1);
        let mut current_ray: Ray3D = *ray;
        let mut throughput: Vec3 = Vec3::splat(1.0);
        let mut radiance: Vec3 = Vec3::zero();
        let mut prev_was_delta: bool = true;
        let mut prev_bsdf_pdf: f32 = 0.0;
        let mut primary_albedo: Vec3 = Vec3::zero();
        let mut primary_normal: Vec3 = Vec3::zero();
        let mut primary_depth: f32 = RT_SKY_DEPTH;
        let mut primary_hit: bool = false;
        let lights: &[RtLight] = scene.get_lights().as_slice();
        let n_lights: usize = lights.len();
        let max_bounces: u32 = self.get_max_bounces();
        let clamp_luma: f32 = self.get_firefly_clamp();
        for bounce in 0..=max_bounces {
            let geom_hit: Option<RtHit> =
                scene.trace_closest(&current_ray, RT_RAY_T_MIN, RT_RAY_T_MAX);
            let max_t: f32 = geom_hit.map_or(RT_RAY_T_MAX, |h: RtHit| h.get_distance());
            if let Some((_, light_t, light_rad, light_pdf)) =
                scene.intersect_area_lights(&current_ray, RT_RAY_T_MIN, max_t)
            {
                let mis_w: f32 = if bounce == 0
                    || prev_was_delta
                    || !self.get_enable_nee()
                    || !self.get_enable_mis()
                    || n_lights == 0
                {
                    1.0
                } else {
                    let combined_light_pdf: f32 = light_pdf / (n_lights as f32);
                    self.mis_weight(prev_bsdf_pdf, combined_light_pdf)
                };
                let contrib: Vec3 =
                    sanitize_radiance(throughput.mul(light_rad).scale(mis_w), clamp_luma);
                radiance = radiance.add(contrib);
                if bounce == 0 {
                    primary_albedo = Vec3::splat(1.0);
                    primary_normal = current_ray.get_direction().scale(-1.0);
                    primary_depth = light_t;
                    primary_hit = true;
                }
                break;
            }
            let hit: RtHit = match geom_hit {
                Some(h) => h,
                None => {
                    let env_rad: Vec3 = scene.evaluate_environment(current_ray.get_direction());
                    let contrib: Vec3 = sanitize_radiance(throughput.mul(env_rad), clamp_luma);
                    radiance = radiance.add(contrib);
                    if bounce == 0 {
                        primary_albedo = sanitize_radiance(env_rad, clamp_luma);
                    }
                    break;
                }
            };
            let mat: RtMaterial = scene.material(hit.get_material_id());
            if bounce == 0 {
                primary_albedo = mat.get_albedo();
                primary_normal = hit.get_shading_normal();
                primary_depth = hit.get_distance();
                primary_hit = true;
            }
            if !hit.get_front_face()
                && (mat.get_kind() == RtMaterialKind::Dielectric || mat.get_transmission() > 0.0)
            {
                let beer: Vec3 = mat.beer_lambert_transmittance(hit.get_distance());
                throughput = throughput.mul(beer);
            }
            if mat.is_emissive() {
                let emitted: Vec3 =
                    sanitize_radiance(throughput.mul(mat.get_emission()), clamp_luma);
                radiance = radiance.add(emitted);
                if mat.get_kind() == RtMaterialKind::Emissive {
                    break;
                }
            }
            let normal: Vec3 = hit.get_shading_normal();
            let geom_n: Vec3 = hit.get_geometric_normal();
            let wo: Vec3 = current_ray.get_direction().scale(-1.0);
            if self.get_enable_nee()
                && n_lights > 0
                && !mat.is_delta_specular()
                && mat.get_kind() != RtMaterialKind::Dielectric
            {
                let pick_idx: usize = (rng.next_u32() as usize) % n_lights;
                let pick_pdf: f32 = 1.0 / (n_lights as f32);
                let sample: RtLightSample =
                    lights[pick_idx].sample_light(hit.get_point(), rng.next_f32_pair());
                let raw_pdf: f32 = sample.get_pdf();
                let wi: Vec3 = sample.get_direction();
                let n_dot_l: f32 = normal.dot(wi);
                if raw_pdf > RT_MIN_PDF && n_dot_l > RT_MIN_PDF {
                    let shadow_origin: Vec3 = offset_ray_origin(hit.get_point(), geom_n, wi);
                    let shadow_max: f32 =
                        (sample.get_distance() - RT_SURFACE_BIAS * 2.0).max(RT_RAY_T_MIN);
                    let shadow_ray: Ray3D = Ray3D::new(shadow_origin, wi);
                    counter.add_shadow(1);
                    if !scene.trace_any_hit(&shadow_ray, RT_RAY_T_MIN, shadow_max) {
                        let (bsdf, bsdf_pdf): (Vec3, f32) =
                            eval_material_bsdf_and_pdf(&mat, normal, wo, wi);
                        let light_pdf: f32 = (raw_pdf * pick_pdf).max(RT_MIN_PDF);
                        let mis_w: f32 = if sample.get_is_delta() || !self.get_enable_mis() {
                            1.0
                        } else {
                            self.mis_weight(light_pdf, bsdf_pdf)
                        };
                        let direct_raw: Vec3 = throughput
                            .mul(bsdf)
                            .mul(sample.get_radiance())
                            .scale((n_dot_l * mis_w) / light_pdf);
                        let direct_clean: Vec3 = sanitize_radiance(direct_raw, clamp_luma);
                        radiance = radiance.add(direct_clean);
                    }
                }
            }
            if bounce == max_bounces {
                break;
            }
            if bounce >= self.get_rr_start_bounce() {
                let max_ch: f32 = throughput
                    .get_x()
                    .max(throughput.get_y())
                    .max(throughput.get_z());
                if max_ch <= RT_MIN_PDF {
                    break;
                }
                let survive: f32 = max_ch.clamp(RT_RR_MIN_SURVIVAL, RT_RR_MAX_SURVIVAL);
                if rng.next_f32() > survive {
                    break;
                }
                throughput = throughput.scale(1.0 / survive);
            }
            let bsdf_sample: RtBsdfSample =
                match sample_material_bsdf(&mat, normal, hit.get_front_face(), wo, rng) {
                    Some(s) => s,
                    None => break,
                };
            let weight: Vec3 = bsdf_sample.get_weight();
            if !weight.get_x().is_finite()
                || !weight.get_y().is_finite()
                || !weight.get_z().is_finite()
            {
                break;
            }
            throughput = throughput.mul(weight);
            if throughput
                .get_x()
                .max(throughput.get_y())
                .max(throughput.get_z())
                <= RT_MIN_PDF
            {
                break;
            }
            prev_was_delta = bsdf_sample.get_is_delta();
            prev_bsdf_pdf = bsdf_sample.get_pdf();
            let next_origin: Vec3 =
                offset_ray_origin(hit.get_point(), geom_n, bsdf_sample.get_wi());
            current_ray = Ray3D::new(next_origin, bsdf_sample.get_wi());
            counter.add_bounce(1);
        }
        RtSampleOutput::new(
            sanitize_radiance(radiance, clamp_luma),
            primary_albedo,
            primary_normal,
            primary_depth,
            primary_hit,
        )
    }
}

/// Default configuration for `RtaoIntegrator`.
impl Default for RtaoIntegrator {
    /// Creates an 8-ray hemisphere RTAO integrator with a 2.0m occlusion radius.
    ///
    /// # Returns
    ///
    /// - `Self` - Default RTAO integrator.
    fn default() -> Self {
        Self {
            sample_count: RT_DEFAULT_AO_SAMPLES,
            radius: RT_DEFAULT_AO_RADIUS,
            bias: RT_SURFACE_BIAS,
        }
    }
}

/// Multi-ray cosine-weighted hemisphere ambient occlusion tracing for `RtaoIntegrator`.
impl RtaoIntegrator {
    /// Traces a primary ray and estimates hemisphere ambient occlusion in `[0.0, 1.0]` at the hit point.
    ///
    /// # Arguments
    ///
    /// - `&Self` - RTAO integrator configuration.
    /// - `&RaytraceScene` - Scene to query.
    /// - `&Ray3D` - Primary camera ray.
    /// - `&mut RtRng` - Deterministic RNG.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `RtSampleOutput` - Grayscale occlusion radiance `[ao, ao, ao]` plus primary G-buffer.
    #[must_use]
    pub fn trace_ray(
        &self,
        scene: &RaytraceScene,
        ray: &Ray3D,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> RtSampleOutput {
        counter.add_primary(1);
        let hit: RtHit = match scene.trace_closest(ray, RT_RAY_T_MIN, RT_RAY_T_MAX) {
            Some(h) => h,
            None => {
                return RtSampleOutput::new(
                    Vec3::splat(1.0),
                    Vec3::splat(1.0),
                    Vec3::zero(),
                    RT_SKY_DEPTH,
                    false,
                );
            }
        };
        let n_rays: u32 = self.get_sample_count().max(1);
        let radius: f32 = self.get_radius().max(0.01);
        let bias: f32 = self.get_bias().max(1e-5);
        let normal: Vec3 = hit.get_shading_normal();
        let origin: Vec3 = hit.get_point().add(hit.get_geometric_normal().scale(bias));
        let mut unoccluded: u32 = 0;
        for _ in 0..n_rays {
            let (dir, _): (Vec3, f32) = sample_cosine_hemisphere(normal, rng.next_f32_pair());
            let ao_ray: Ray3D = Ray3D::new(origin, dir);
            counter.add_shadow(1);
            if !scene.trace_any_hit(&ao_ray, RT_RAY_T_MIN, radius) {
                unoccluded += 1;
            }
        }
        let ao: f32 = ((unoccluded as f32) / (n_rays as f32)).clamp(0.0, 1.0);
        let mat: RtMaterial = scene.material(hit.get_material_id());
        RtSampleOutput::new(
            Vec3::splat(ao),
            mat.get_albedo(),
            normal,
            hit.get_distance(),
            true,
        )
    }
}

/// Default configuration for `HybridPreviewIntegrator`.
impl Default for HybridPreviewIntegrator {
    /// Creates a fast 1-spp interactive hybrid preview integrator.
    ///
    /// # Returns
    ///
    /// - `Self` - Default hybrid preview integrator.
    fn default() -> Self {
        Self {
            ambient_scale: 0.16,
            shadow_enabled: true,
            firefly_clamp: RT_DEFAULT_FIREFLY_CLAMP,
        }
    }
}

/// Fast 1-spp G-buffer and direct-lighting preview tracing for `HybridPreviewIntegrator`.
impl HybridPreviewIntegrator {
    /// Traces a single primary ray with fast direct lighting and emits full G-buffers for interactive orbit.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Hybrid preview integrator configuration.
    /// - `&RaytraceScene` - Scene to intersect.
    /// - `&Ray3D` - Primary camera ray.
    /// - `&mut RtRng` - Deterministic RNG.
    /// - `&mut RtRayCounter` - Telemetry ray counter.
    ///
    /// # Returns
    ///
    /// - `RtSampleOutput` - Fast 1-spp radiance plus primary albedo, world normal, and linear depth.
    #[must_use]
    pub fn trace_ray(
        &self,
        scene: &RaytraceScene,
        ray: &Ray3D,
        rng: &mut RtRng,
        counter: &mut RtRayCounter,
    ) -> RtSampleOutput {
        counter.add_primary(1);
        let geom_hit: Option<RtHit> = scene.trace_closest(ray, RT_RAY_T_MIN, RT_RAY_T_MAX);
        let max_t: f32 = geom_hit.map_or(RT_RAY_T_MAX, |h: RtHit| h.get_distance());
        if let Some((_, light_t, light_rad, _)) =
            scene.intersect_area_lights(ray, RT_RAY_T_MIN, max_t)
        {
            let clean: Vec3 = sanitize_radiance(light_rad, self.get_firefly_clamp());
            return RtSampleOutput::new(
                clean,
                Vec3::splat(1.0),
                ray.get_direction().scale(-1.0),
                light_t,
                true,
            );
        }
        let hit: RtHit = match geom_hit {
            Some(h) => h,
            None => {
                let sky: Vec3 = sanitize_radiance(
                    scene.evaluate_environment(ray.get_direction()),
                    self.get_firefly_clamp(),
                );
                return RtSampleOutput::new(sky, sky, Vec3::zero(), RT_SKY_DEPTH, false);
            }
        };
        let mat: RtMaterial = scene.material(hit.get_material_id());
        let normal: Vec3 = hit.get_shading_normal();
        let geom_n: Vec3 = hit.get_geometric_normal();
        let wo: Vec3 = ray.get_direction().scale(-1.0);
        let mut radiance: Vec3 = mat.get_emission();
        let env_hemi: Vec3 = scene.evaluate_environment(normal);
        radiance = radiance.add(
            mat.get_albedo()
                .mul(env_hemi)
                .scale(self.get_ambient_scale()),
        );
        if mat.get_kind() == RtMaterialKind::Metal || mat.get_kind() == RtMaterialKind::Dielectric {
            let refl_dir: Vec3 = ray.get_direction().reflect(normal).normalize();
            let env_spec: Vec3 = scene.evaluate_environment(refl_dir);
            let f: Vec3 = fresnel_schlick(wo.dot(normal).clamp(0.0, 1.0), mat.get_albedo());
            radiance = radiance.add(env_spec.mul(f));
        } else {
            for light in scene.get_lights() {
                let sample: RtLightSample =
                    light.sample_light(hit.get_point(), rng.next_f32_pair());
                let pdf: f32 = sample.get_pdf();
                let wi: Vec3 = sample.get_direction();
                let n_dot_l: f32 = normal.dot(wi);
                if pdf <= RT_MIN_PDF || n_dot_l <= RT_MIN_PDF {
                    continue;
                }
                if self.get_shadow_enabled() {
                    let shadow_origin: Vec3 = offset_ray_origin(hit.get_point(), geom_n, wi);
                    let shadow_max: f32 =
                        (sample.get_distance() - RT_SURFACE_BIAS * 2.0).max(RT_RAY_T_MIN);
                    let shadow_ray: Ray3D = Ray3D::new(shadow_origin, wi);
                    counter.add_shadow(1);
                    if scene.trace_any_hit(&shadow_ray, RT_RAY_T_MIN, shadow_max) {
                        continue;
                    }
                }
                let (brdf, _): (Vec3, f32) = eval_material_bsdf_and_pdf(&mat, normal, wo, wi);
                radiance = radiance.add(brdf.mul(sample.get_radiance()).scale(n_dot_l / pdf));
            }
        }
        RtSampleOutput::new(
            sanitize_radiance(radiance, self.get_firefly_clamp()),
            mat.get_albedo(),
            normal,
            hit.get_distance(),
            true,
        )
    }
}