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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
use super::*;

/// Default environment dome returning dark background.
impl Default for RtEnvironment {
    /// Returns a black zero-radiance environment dome.
    ///
    /// # Returns
    ///
    /// - `Self` - Black environment.
    fn default() -> Self {
        Self::Black
    }
}

/// Default matte diffuse material constructor for `RtMaterial`.
impl Default for RtMaterial {
    /// Returns a neutral mid-gray Lambertian diffuse material.
    ///
    /// # Returns
    ///
    /// - `Self` - Default diffuse material.
    fn default() -> Self {
        Self::lambert(Vec3::splat(0.75))
    }
}

/// Physical BSDF constructors, Beer-Lambert transmittance, and `euv-core` material converters for `RtMaterial`.
impl RtMaterial {
    /// Creates an ideal Lambertian matte diffuse material.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Linear RGB surface albedo in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Diffuse `RtMaterial`.
    #[must_use]
    pub fn lambert(albedo: Vec3) -> Self {
        Self {
            kind: RtMaterialKind::Diffuse,
            albedo: Vec3::new(
                albedo.get_x().clamp(0.0, 1.0),
                albedo.get_y().clamp(0.0, 1.0),
                albedo.get_z().clamp(0.0, 1.0),
            ),
            metallic: 0.0,
            roughness: 1.0,
            ior: RT_DEFAULT_GLASS_IOR,
            transmission: 0.0,
            absorption: Vec3::zero(),
            clearcoat: 0.0,
            clearcoat_roughness: 0.05,
            emission: Vec3::zero(),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Creates an Oren-Nayar micro-rough diffuse material modeling dusty or plaster surfaces.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Linear RGB diffuse albedo.
    /// - `f32` - Microfacet slope standard deviation `sigma` in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Oren-Nayar diffuse `RtMaterial`.
    #[must_use]
    pub fn oren_nayar(albedo: Vec3, sigma: f32) -> Self {
        let mut mat: Self = Self::lambert(albedo);
        mat.set_oren_nayar_sigma(sigma.clamp(0.0, 1.0));
        mat
    }

    /// Creates a GGX microfacet metallic conductor material.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Linear RGB conductor reflectance `F0`.
    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Metallic conductor `RtMaterial`.
    #[must_use]
    pub fn metal(albedo: Vec3, roughness: f32) -> Self {
        Self {
            kind: RtMaterialKind::Metal,
            albedo: Vec3::new(
                albedo.get_x().clamp(0.0, 1.0),
                albedo.get_y().clamp(0.0, 1.0),
                albedo.get_z().clamp(0.0, 1.0),
            ),
            metallic: 1.0,
            roughness: roughness.clamp(0.0, 1.0),
            ior: RT_DEFAULT_GLASS_IOR,
            transmission: 0.0,
            absorption: Vec3::zero(),
            clearcoat: 0.0,
            clearcoat_roughness: 0.05,
            emission: Vec3::zero(),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Creates a sharp mirror conductor material with zero microfacet roughness.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Linear RGB mirror reflectance tint.
    ///
    /// # Returns
    ///
    /// - `Self` - Ideal mirror `RtMaterial`.
    #[must_use]
    pub fn mirror(albedo: Vec3) -> Self {
        Self::metal(albedo, 0.0)
    }

    /// Creates a refractive dielectric material (glass or water) with Schlick/Snell optics and Beer-Lambert absorption.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Surface transmission/reflection albedo multiplier.
    /// - `f32` - Index of refraction (`> 1.0`, e.g., `1.5` for glass or `1.333` for water).
    /// - `f32` - Surface microfacet roughness (`0.0` for crystal-clear glass).
    /// - `Vec3` - Beer-Lambert volumetric absorption coefficient `sigma_a >= 0` (`1 / meters`).
    ///
    /// # Returns
    ///
    /// - `Self` - Dielectric `RtMaterial`.
    #[must_use]
    pub fn dielectric(albedo: Vec3, ior: f32, roughness: f32, absorption: Vec3) -> Self {
        Self {
            kind: RtMaterialKind::Dielectric,
            albedo: Vec3::new(
                albedo.get_x().clamp(0.0, 1.0),
                albedo.get_y().clamp(0.0, 1.0),
                albedo.get_z().clamp(0.0, 1.0),
            ),
            metallic: 0.0,
            roughness: roughness.clamp(0.0, 1.0),
            ior: ior.clamp(1.001, 3.0),
            transmission: 1.0,
            absorption: Vec3::new(
                absorption.get_x().max(0.0),
                absorption.get_y().max(0.0),
                absorption.get_z().max(0.0),
            ),
            clearcoat: 0.0,
            clearcoat_roughness: 0.04,
            emission: Vec3::zero(),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Creates a crystal-clear lossless dielectric glass material with the given index of refraction.
    ///
    /// # Arguments
    ///
    /// - `f32` - Index of refraction (e.g., `1.5`).
    ///
    /// # Returns
    ///
    /// - `Self` - Clear glass `RtMaterial`.
    #[must_use]
    pub fn glass(ior: f32) -> Self {
        Self::dielectric(Vec3::splat(1.0), ior, 0.0, Vec3::zero())
    }

    /// Creates a clearcoat layered material combining a base diffuse/specular coat with a glossy dielectric varnish.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Base linear RGB albedo.
    /// - `f32` - Base layer roughness in `[0.0, 1.0]`.
    /// - `f32` - Clearcoat weight in `[0.0, 1.0]`.
    /// - `f32` - Clearcoat roughness in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Principled clearcoat `RtMaterial`.
    #[must_use]
    pub fn clearcoat(
        albedo: Vec3,
        roughness: f32,
        clearcoat: f32,
        clearcoat_roughness: f32,
    ) -> Self {
        Self {
            kind: RtMaterialKind::Principled,
            albedo: Vec3::new(
                albedo.get_x().clamp(0.0, 1.0),
                albedo.get_y().clamp(0.0, 1.0),
                albedo.get_z().clamp(0.0, 1.0),
            ),
            metallic: 0.0,
            roughness: roughness.clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
            ior: RT_DEFAULT_GLASS_IOR,
            transmission: 0.0,
            absorption: Vec3::zero(),
            clearcoat: clearcoat.clamp(0.0, 1.0),
            clearcoat_roughness: clearcoat_roughness.clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
            emission: Vec3::zero(),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Creates a pure HDR emissive area light material.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Linear HDR emitted radiance RGB.
    ///
    /// # Returns
    ///
    /// - `Self` - Emissive `RtMaterial`.
    #[must_use]
    pub fn emissive(radiance: Vec3) -> Self {
        Self {
            kind: RtMaterialKind::Emissive,
            albedo: Vec3::zero(),
            metallic: 0.0,
            roughness: 1.0,
            ior: RT_DEFAULT_GLASS_IOR,
            transmission: 0.0,
            absorption: Vec3::zero(),
            clearcoat: 0.0,
            clearcoat_roughness: 0.04,
            emission: Vec3::new(
                radiance.get_x().max(0.0),
                radiance.get_y().max(0.0),
                radiance.get_z().max(0.0),
            ),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Creates a unified Principled BSDF material combining metallic, roughness, IOR, and transmission.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Base linear RGB albedo.
    /// - `f32` - Metallic factor in `[0.0, 1.0]`.
    /// - `f32` - Perceptual roughness in `[0.0, 1.0]`.
    /// - `f32` - Dielectric IOR.
    /// - `f32` - Transmission weight in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Principled `RtMaterial`.
    #[must_use]
    pub fn principled(
        albedo: Vec3,
        metallic: f32,
        roughness: f32,
        ior: f32,
        transmission: f32,
    ) -> Self {
        Self {
            kind: RtMaterialKind::Principled,
            albedo: Vec3::new(
                albedo.get_x().clamp(0.0, 1.0),
                albedo.get_y().clamp(0.0, 1.0),
                albedo.get_z().clamp(0.0, 1.0),
            ),
            metallic: metallic.clamp(0.0, 1.0),
            roughness: roughness.clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
            ior: ior.clamp(1.001, 3.0),
            transmission: transmission.clamp(0.0, 1.0),
            absorption: Vec3::zero(),
            clearcoat: 0.0,
            clearcoat_roughness: 0.05,
            emission: Vec3::zero(),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Converts an `euv-core` `PbrMaterial` into a physically based `RtMaterial`.
    ///
    /// # Arguments
    ///
    /// - `&PbrMaterial` - Source `World3D` PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Converted ray-tracing material.
    #[must_use]
    pub fn from_pbr_material(material: &PbrMaterial) -> Self {
        let emissive: Vec3 = material.get_emissive();
        let has_emissive: bool =
            emissive.get_x() > 1e-4 || emissive.get_y() > 1e-4 || emissive.get_z() > 1e-4;
        let metallic: f32 = material.get_metallic().clamp(0.0, 1.0);
        let roughness: f32 = material.get_roughness().clamp(RT_SCENE_MIN_ROUGHNESS, 1.0);
        let base_color: Vec3 = material.get_base_color();
        let kind: RtMaterialKind = if metallic >= 0.85 {
            RtMaterialKind::Metal
        } else if metallic <= 0.05 && roughness >= 0.75 && !has_emissive {
            RtMaterialKind::Diffuse
        } else {
            RtMaterialKind::Principled
        };
        Self {
            kind,
            albedo: Vec3::new(
                base_color.get_x().clamp(0.0, 1.0),
                base_color.get_y().clamp(0.0, 1.0),
                base_color.get_z().clamp(0.0, 1.0),
            ),
            metallic,
            roughness,
            ior: RT_DEFAULT_GLASS_IOR,
            transmission: 0.0,
            absorption: Vec3::zero(),
            clearcoat: (material.get_reflectivity() * 0.5).clamp(0.0, 1.0),
            clearcoat_roughness: (roughness * 0.5).clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
            emission: Vec3::new(
                emissive.get_x().max(0.0),
                emissive.get_y().max(0.0),
                emissive.get_z().max(0.0),
            ),
            oren_nayar_sigma: 0.0,
        }
    }

    /// Converts an `euv-core` Blender/glTF `PrincipledMaterial3D` into a physically based `RtMaterial`.
    ///
    /// # Arguments
    ///
    /// - `&PrincipledMaterial3D` - Source principled material descriptor.
    ///
    /// # Returns
    ///
    /// - `Self` - Converted ray-tracing material including IOR, transmission, clearcoat, and Beer-Lambert volume absorption.
    #[must_use]
    pub fn from_principled_material(material: &PrincipledMaterial3D) -> Self {
        let bc: [f32; 4] = material.get_base_color_factor();
        let albedo: Vec3 = Vec3::new(
            bc[0].clamp(0.0, 1.0),
            bc[1].clamp(0.0, 1.0),
            bc[2].clamp(0.0, 1.0),
        );
        let ef: [f32; 3] = material.get_emissive_factor();
        let es: f32 = material.get_emissive_strength().max(0.0);
        let emission: Vec3 = Vec3::new(
            (ef[0] * es).max(0.0),
            (ef[1] * es).max(0.0),
            (ef[2] * es).max(0.0),
        );
        let transmission: f32 = material.get_transmission_factor().clamp(0.0, 1.0);
        let att_dist: f32 = material.get_attenuation_distance();
        let att_col: [f32; 3] = material.get_attenuation_color();
        let absorption: Vec3 = if att_dist.is_finite() && att_dist > 1e-4 && transmission > 1e-4 {
            let inv_d: f32 = 1.0 / att_dist;
            Vec3::new(
                (-att_col[0].clamp(1e-4, 1.0).ln()) * inv_d,
                (-att_col[1].clamp(1e-4, 1.0).ln()) * inv_d,
                (-att_col[2].clamp(1e-4, 1.0).ln()) * inv_d,
            )
        } else {
            Vec3::zero()
        };
        let metallic: f32 = material.get_metallic_factor().clamp(0.0, 1.0);
        let roughness: f32 = material
            .get_roughness_factor()
            .clamp(RT_SCENE_MIN_ROUGHNESS, 1.0);
        let kind: RtMaterialKind = if transmission >= 0.9 && metallic < 0.05 {
            RtMaterialKind::Dielectric
        } else if metallic >= 0.95 && transmission < 0.05 {
            RtMaterialKind::Metal
        } else {
            RtMaterialKind::Principled
        };
        Self {
            kind,
            albedo,
            metallic,
            roughness,
            ior: material.get_ior().clamp(1.001, 3.0),
            transmission,
            absorption,
            clearcoat: material.get_clearcoat_factor().clamp(0.0, 1.0),
            clearcoat_roughness: material
                .get_clearcoat_roughness_factor()
                .clamp(RT_SCENE_MIN_ROUGHNESS, 1.0),
            emission,
            oren_nayar_sigma: 0.0,
        }
    }

    /// Evaluates Beer-Lambert volumetric transmittance `exp(-sigma_a * distance)` over an interior ray segment.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Material reference.
    /// - `f32` - Interior travel distance in meters.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Component-wise optical transmittance in `(0.0, 1.0]`.
    #[must_use]
    pub fn beer_lambert_transmittance(&self, distance: f32) -> Vec3 {
        let d: f32 = distance.max(0.0);
        let sigma: Vec3 = self.get_absorption();
        Vec3::new(
            (-sigma.get_x().max(0.0) * d).exp().clamp(0.0, 1.0),
            (-sigma.get_y().max(0.0) * d).exp().clamp(0.0, 1.0),
            (-sigma.get_z().max(0.0) * d).exp().clamp(0.0, 1.0),
        )
    }

    /// Returns `true` when this material emits non-zero HDR radiance.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Material reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether emission exceeds zero.
    #[must_use]
    pub fn is_emissive(&self) -> bool {
        let e: Vec3 = self.get_emission();
        e.get_x() > 0.0 || e.get_y() > 0.0 || e.get_z() > 0.0
    }

    /// Returns `true` when this material acts as a pure Dirac delta mirror or clear dielectric.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Material reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether BSDF scattering is a delta distribution.
    #[must_use]
    pub fn is_delta_specular(&self) -> bool {
        match self.get_kind() {
            RtMaterialKind::Metal => self.get_roughness() <= 0.005,
            RtMaterialKind::Dielectric => self.get_roughness() <= 0.005,
            _ => false,
        }
    }
}

/// Constructors, importance sampling, and direct area-light intersection for `RtLight`.
impl RtLight {
    /// Creates a directional sun/sky light with optional angular radius for physically soft shadows.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Direction pointing from the scene toward the light source.
    /// - `Vec3` - Linear HDR light color.
    /// - `f32` - Radiant irradiance multiplier.
    /// - `f32` - Angular half-angle in radians (`0.0` for razor-sharp sun shadows).
    ///
    /// # Returns
    ///
    /// - `Self` - Directional `RtLight`.
    #[must_use]
    pub fn directional(
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        angular_radius_rad: f32,
    ) -> Self {
        Self {
            kind: RtLightKind::Directional {
                direction: direction.normalize(),
                angular_radius_rad: angular_radius_rad.clamp(0.0, FRAC_PI_3),
            },
            color,
            intensity: intensity.max(0.0),
        }
    }

    /// Creates an omnidirectional spherical point light with inverse-square attenuation.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space light center.
    /// - `Vec3` - Linear HDR light color.
    /// - `f32` - Luminous intensity.
    /// - `f32` - Spherical radius in meters (`0.0` for delta point light).
    ///
    /// # Returns
    ///
    /// - `Self` - Point `RtLight`.
    #[must_use]
    pub fn point(position: Vec3, color: Vec3, intensity: f32, radius: f32) -> Self {
        Self {
            kind: RtLightKind::Point {
                position,
                radius: radius.max(0.0),
            },
            color,
            intensity: intensity.max(0.0),
        }
    }

    /// Creates a focused spotlight with inner/outer cone angles in degrees and optional soft emitter radius.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space emitter origin.
    /// - `Vec3` - Beam forward direction.
    /// - `Vec3` - Linear HDR light color.
    /// - `f32` - Luminous intensity.
    /// - `f32` - Inner full-brightness half-angle in degrees.
    /// - `f32` - Outer cutoff half-angle in degrees.
    /// - `f32` - Emitter radius in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Spotlight `RtLight`.
    #[must_use]
    pub fn spot(
        position: Vec3,
        direction: Vec3,
        color: Vec3,
        intensity: f32,
        inner_deg: f32,
        outer_deg: f32,
        radius: f32,
    ) -> Self {
        let inner_clamped: f32 = inner_deg.clamp(0.5, 89.0);
        let outer_clamped: f32 = outer_deg.clamp(inner_clamped + 0.5, 89.5);
        Self {
            kind: RtLightKind::Spot {
                position,
                direction: direction.normalize(),
                inner_cos: inner_clamped.to_radians().cos(),
                outer_cos: outer_clamped.to_radians().cos(),
                radius: radius.max(0.0),
            },
            color,
            intensity: intensity.max(0.0),
        }
    }

    /// Creates a physically based rectangular area light emitter oriented along `normal`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space rectangle center.
    /// - `Vec3` - Outward emitting surface normal.
    /// - `Vec2` - Emitter `(width, height)` dimensions in meters.
    /// - `Vec3` - Linear HDR emission color.
    /// - `f32` - Emitted radiance multiplier.
    /// - `bool` - Whether both sides of the rectangle emit radiance.
    ///
    /// # Returns
    ///
    /// - `Self` - Rectangular area `RtLight`.
    #[must_use]
    pub fn rect_area(
        position: Vec3,
        normal: Vec3,
        dimensions: Vec2,
        color: Vec3,
        intensity: f32,
        two_sided: bool,
    ) -> Self {
        let n: Vec3 = normal.normalize();
        let (right, up): (Vec3, Vec3) = build_orthonormal_basis(n);
        Self {
            kind: RtLightKind::RectArea {
                position,
                right,
                up,
                normal: n,
                width: dimensions.get_x().max(1e-3),
                height: dimensions.get_y().max(1e-3),
                two_sided,
            },
            color,
            intensity: intensity.max(0.0),
        }
    }

    /// Creates a physically based circular disk area light emitter oriented along `normal`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space disk center.
    /// - `Vec3` - Outward emitting surface normal.
    /// - `f32` - Disk radius in meters.
    /// - `Vec3` - Linear HDR emission color.
    /// - `f32` - Emitted radiance multiplier.
    /// - `bool` - Whether both sides of the disk emit radiance.
    ///
    /// # Returns
    ///
    /// - `Self` - Circular disk area `RtLight`.
    #[must_use]
    pub fn disk_area(
        position: Vec3,
        normal: Vec3,
        radius: f32,
        color: Vec3,
        intensity: f32,
        two_sided: bool,
    ) -> Self {
        let n: Vec3 = normal.normalize();
        let (right, up): (Vec3, Vec3) = build_orthonormal_basis(n);
        Self {
            kind: RtLightKind::DiskArea {
                position,
                right,
                up,
                normal: n,
                radius: radius.max(1e-3),
                two_sided,
            },
            color,
            intensity: intensity.max(0.0),
        }
    }

    /// Importance-samples a direct lighting direction and solid-angle PDF from `hit_point`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Light emitter reference.
    /// - `Vec3` - World-space shaded surface position.
    /// - `[f32; 2]` - Uniform quasi-random or pseudo-random pair in `[0.0, 1.0)^2`.
    ///
    /// # Returns
    ///
    /// - `RtLightSample` - Sampled direction, distance, incident radiance, solid-angle PDF, and delta flag.
    #[must_use]
    pub fn sample_light(&self, hit_point: Vec3, xi: [f32; 2]) -> RtLightSample {
        let power: Vec3 = self.get_color().scale(self.get_intensity());
        match self.get_kind() {
            RtLightKind::Directional {
                direction,
                angular_radius_rad,
            } => {
                let axis: Vec3 = direction.normalize();
                if angular_radius_rad <= 1e-5 {
                    return RtLightSample::new(axis, RT_RAY_T_MAX, power, 1.0, true);
                }
                let cos_max: f32 = angular_radius_rad.cos().clamp(-0.999, 0.999_999);
                let cos_theta: f32 = (1.0 - xi[0]) + xi[0] * cos_max;
                let sin_theta: f32 = (1.0 - cos_theta * cos_theta).max(0.0).sqrt();
                let phi: f32 = TAU * xi[1];
                let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(axis);
                let sampled_dir: Vec3 = tangent
                    .scale(sin_theta * phi.cos())
                    .add(bitangent.scale(sin_theta * phi.sin()))
                    .add(axis.scale(cos_theta))
                    .normalize();
                RtLightSample::new(sampled_dir, RT_RAY_T_MAX, power, 1.0, true)
            }
            RtLightKind::Point { position, radius } => {
                let to_center: Vec3 = position.sub(hit_point);
                let center_dist_sq: f32 = to_center.length_sq().max(1e-4);
                let target: Vec3 = if radius > 1e-5 {
                    let axis: Vec3 = to_center.scale(1.0 / center_dist_sq.sqrt());
                    let (t, b): (Vec3, Vec3) = build_orthonormal_basis(axis);
                    let disk: [f32; 2] = concentric_sample_disk(xi);
                    position
                        .add(t.scale(disk[0] * radius))
                        .add(b.scale(disk[1] * radius))
                } else {
                    position
                };
                let to_sample: Vec3 = target.sub(hit_point);
                let dist_sq: f32 = to_sample.length_sq().max(1e-4);
                let dist: f32 = dist_sq.sqrt();
                let dir: Vec3 = to_sample.scale(1.0 / dist);
                RtLightSample::new(dir, dist, power.scale(1.0 / dist_sq), 1.0, true)
            }
            RtLightKind::Spot {
                position,
                direction,
                inner_cos,
                outer_cos,
                radius,
            } => {
                let to_center: Vec3 = position.sub(hit_point);
                let center_dist_sq: f32 = to_center.length_sq().max(1e-4);
                let target: Vec3 = if radius > 1e-5 {
                    let axis: Vec3 = to_center.scale(1.0 / center_dist_sq.sqrt());
                    let (t, b): (Vec3, Vec3) = build_orthonormal_basis(axis);
                    let disk: [f32; 2] = concentric_sample_disk(xi);
                    position
                        .add(t.scale(disk[0] * radius))
                        .add(b.scale(disk[1] * radius))
                } else {
                    position
                };
                let to_sample: Vec3 = target.sub(hit_point);
                let dist_sq: f32 = to_sample.length_sq().max(1e-4);
                let dist: f32 = dist_sq.sqrt();
                let dir: Vec3 = to_sample.scale(1.0 / dist);
                let cos_angle: f32 = dir.scale(-1.0).dot(direction.normalize());
                let span: f32 = (inner_cos - outer_cos).max(1e-4);
                let t_cone: f32 = ((cos_angle - outer_cos) / span).clamp(0.0, 1.0);
                let falloff: f32 = t_cone * t_cone;
                RtLightSample::new(dir, dist, power.scale(falloff / dist_sq), 1.0, true)
            }
            RtLightKind::RectArea {
                position,
                right,
                up,
                normal,
                width,
                height,
                two_sided,
            } => {
                let u_off: f32 = (xi[0] - 0.5) * width;
                let v_off: f32 = (xi[1] - 0.5) * height;
                let sample_pt: Vec3 = position.add(right.scale(u_off)).add(up.scale(v_off));
                let to_light: Vec3 = sample_pt.sub(hit_point);
                let dist_sq: f32 = to_light.length_sq();
                if dist_sq <= RT_SCENE_EPSILON {
                    return RtLightSample::new(
                        Vec3::new(0.0, 1.0, 0.0),
                        0.0,
                        Vec3::zero(),
                        0.0,
                        false,
                    );
                }
                let dist: f32 = dist_sq.sqrt();
                let dir: Vec3 = to_light.scale(1.0 / dist);
                let raw_cos: f32 = normal.dot(dir.scale(-1.0));
                let cos_light: f32 = if two_sided { raw_cos.abs() } else { raw_cos };
                if cos_light <= RT_SCENE_EPSILON {
                    return RtLightSample::new(dir, dist, Vec3::zero(), 0.0, false);
                }
                let area: f32 = (width * height).max(RT_SCENE_EPSILON);
                let pdf: f32 = dist_sq / (area * cos_light);
                RtLightSample::new(dir, dist, power, pdf, false)
            }
            RtLightKind::DiskArea {
                position,
                right,
                up,
                normal,
                radius,
                two_sided,
            } => {
                let disk: [f32; 2] = concentric_sample_disk(xi);
                let sample_pt: Vec3 = position
                    .add(right.scale(disk[0] * radius))
                    .add(up.scale(disk[1] * radius));
                let to_light: Vec3 = sample_pt.sub(hit_point);
                let dist_sq: f32 = to_light.length_sq();
                if dist_sq <= RT_SCENE_EPSILON {
                    return RtLightSample::new(
                        Vec3::new(0.0, 1.0, 0.0),
                        0.0,
                        Vec3::zero(),
                        0.0,
                        false,
                    );
                }
                let dist: f32 = dist_sq.sqrt();
                let dir: Vec3 = to_light.scale(1.0 / dist);
                let raw_cos: f32 = normal.dot(dir.scale(-1.0));
                let cos_light: f32 = if two_sided { raw_cos.abs() } else { raw_cos };
                if cos_light <= RT_SCENE_EPSILON {
                    return RtLightSample::new(dir, dist, Vec3::zero(), 0.0, false);
                }
                let area: f32 = (PI * radius * radius).max(RT_SCENE_EPSILON);
                let pdf: f32 = dist_sq / (area * cos_light);
                RtLightSample::new(dir, dist, power, pdf, false)
            }
        }
    }

    /// Intersects a ray with an explicit finite area light (`RectArea` or `DiskArea`) returning `(distance, radiance, solid_angle_pdf)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Light emitter reference.
    /// - `&Ray3D` - World-space ray.
    /// - `f32` - Minimum accepted distance.
    /// - `f32` - Maximum accepted distance.
    ///
    /// # Returns
    ///
    /// - `Option<(f32, Vec3, f32)>` - Hit distance, emitted HDR radiance, and solid-angle sampling PDF for MIS.
    #[must_use]
    pub fn intersect_area(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<(f32, Vec3, f32)> {
        let power: Vec3 = self.get_color().scale(self.get_intensity());
        let origin: Vec3 = ray.get_origin();
        let dir: Vec3 = ray.get_direction();
        match self.get_kind() {
            RtLightKind::RectArea {
                position,
                right,
                up,
                normal,
                width,
                height,
                two_sided,
            } => {
                let denom: f32 = normal.dot(dir);
                if denom.abs() < RT_SCENE_EPSILON {
                    return None;
                }
                let cos_light: f32 = if two_sided { -denom.abs() } else { denom };
                let front_cos: f32 = -cos_light;
                if !two_sided && front_cos <= RT_SCENE_EPSILON {
                    return None;
                }
                let dist: f32 = position.sub(origin).dot(normal) / denom;
                if !dist.is_finite() {
                    return None;
                }
                if dist < t_min || dist > t_max {
                    return None;
                }
                let rel: Vec3 = origin.add(dir.scale(dist)).sub(position);
                let u_proj: f32 = rel.dot(right);
                let v_proj: f32 = rel.dot(up);
                if u_proj.abs() > width * 0.5 || v_proj.abs() > height * 0.5 {
                    return None;
                }
                let area: f32 = (width * height).max(RT_SCENE_EPSILON);
                let pdf: f32 = (dist * dist) / (area * denom.abs().max(RT_SCENE_EPSILON));
                Some((dist, power, pdf))
            }
            RtLightKind::DiskArea {
                position,
                normal,
                radius,
                two_sided,
                ..
            } => {
                let denom: f32 = normal.dot(dir);
                if denom.abs() < RT_SCENE_EPSILON {
                    return None;
                }
                if !two_sided && (-denom) <= RT_SCENE_EPSILON {
                    return None;
                }
                let dist: f32 = position.sub(origin).dot(normal) / denom;
                if !dist.is_finite() {
                    return None;
                }
                if dist < t_min || dist > t_max {
                    return None;
                }
                let rel: Vec3 = origin.add(dir.scale(dist)).sub(position);
                if rel.length_sq() > radius * radius {
                    return None;
                }
                let area: f32 = (PI * radius * radius).max(RT_SCENE_EPSILON);
                let pdf: f32 = (dist * dist) / (area * denom.abs().max(RT_SCENE_EPSILON));
                Some((dist, power, pdf))
            }
            _ => None,
        }
    }
}

/// Default pinhole camera positioned on `+Z` looking toward the origin.
impl Default for RtCamera {
    /// Creates a default 16:9 pinhole camera at `(0, 1.5, 5.0)` looking at `(0, 1.0, 0)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `RtCamera`.
    fn default() -> Self {
        Self::look_at(
            Vec3::new(0.0, 1.5, 5.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(0.0, 1.0, 0.0),
            RT_DEFAULT_FOV_DEG,
            16.0 / 9.0,
        )
    }
}

/// Look-at construction, thin-lens depth of field, jittered ray generation, and motion hashing for `RtCamera`.
impl RtCamera {
    /// Constructs a pinhole camera looking from `position` toward `target`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space eye position.
    /// - `Vec3` - World-space look target.
    /// - `Vec3` - World-space up reference vector.
    /// - `f32` - Vertical field of view in degrees.
    /// - `f32` - Viewport aspect ratio (`width / height`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured pinhole `RtCamera`.
    #[must_use]
    pub fn look_at(
        position: Vec3,
        target: Vec3,
        world_up: Vec3,
        fov_y_deg: f32,
        aspect: f32,
    ) -> Self {
        let forward: Vec3 = target.sub(position).normalize();
        let up_ref: Vec3 = if forward.dot(world_up.normalize()).abs() > 0.999 {
            Vec3::new(0.0, 0.0, 1.0)
        } else {
            world_up.normalize()
        };
        let right: Vec3 = forward.cross(up_ref).normalize();
        let up: Vec3 = right.cross(forward).normalize();
        let focal_dist: f32 = target.sub(position).length().max(0.1);
        Self {
            position,
            forward,
            right,
            up,
            fov_y_rad: fov_y_deg.clamp(5.0, 150.0).to_radians(),
            aspect: aspect.max(0.05),
            aperture_radius: 0.0,
            focal_distance: focal_dist,
        }
    }

    /// Configures thin-lens Depth-of-Field optics on this camera.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base camera.
    /// - `f32` - Lens aperture radius in meters (`0.0` = sharp pinhole).
    /// - `f32` - Distance to the sharp focal plane in meters.
    ///
    /// # Returns
    ///
    /// - `Self` - Camera with thin-lens depth-of-field parameters.
    #[must_use]
    pub fn with_thin_lens(mut self, aperture_radius: f32, focal_distance: f32) -> Self {
        self.set_aperture_radius(aperture_radius.max(0.0));
        self.set_focal_distance(focal_distance.max(0.05));
        self
    }

    /// Converts an existing `euv-core` `Camera3D` into a matching `RtCamera`.
    ///
    /// # Arguments
    ///
    /// - `&Camera3D` - Source 3D viewport camera.
    /// - `f32` - Viewport width-to-height aspect ratio.
    ///
    /// # Returns
    ///
    /// - `Self` - Matching ray-tracing camera.
    #[must_use]
    pub fn from_camera3d(camera: &Camera3D, aspect: f32) -> Self {
        let pos: Vec3 = camera.get_position();
        let forward: Vec3 = camera.forward();
        let right: Vec3 = camera.right();
        let up: Vec3 = right.cross(forward).normalize();
        let fov_rad: f32 = Camera3D::effective_vertical_fov_rad(camera.get_fov_deg(), aspect);
        Self {
            position: pos,
            forward,
            right,
            up,
            fov_y_rad: fov_rad,
            aspect: aspect.max(0.05),
            aperture_radius: 0.0,
            focal_distance: 5.0,
        }
    }

    /// Generates a world-space primary ray for pixel `(px, py)` with sub-pixel anti-aliasing jitter and thin-lens aperture sampling.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Camera reference.
    /// - `[u32; 2]` - Integer pixel coordinates `[px, py]`.
    /// - `[u32; 2]` - Viewport resolution `[width, height]`.
    /// - `[f32; 2]` - Sub-pixel offset in `[0.0, 1.0)^2` (e.g., from `r2_subpixel_jitter` or Halton).
    /// - `[f32; 2]` - Uniform lens sample in `[0.0, 1.0)^2` for thin-lens DoF.
    ///
    /// # Returns
    ///
    /// - `Ray3D` - Normalized world-space camera ray.
    #[must_use]
    pub fn generate_ray(
        &self,
        pixel: [u32; 2],
        resolution: [u32; 2],
        pixel_jitter: [f32; 2],
        lens_sample: [f32; 2],
    ) -> Ray3D {
        let w: f32 = resolution[0].max(1) as f32;
        let h: f32 = resolution[1].max(1) as f32;
        let u: f32 = ((pixel[0] as f32) + pixel_jitter[0].clamp(0.0, 1.0)) / w;
        let v: f32 = ((pixel[1] as f32) + pixel_jitter[1].clamp(0.0, 1.0)) / h;
        let half_h: f32 = (self.get_fov_y_rad() * 0.5).tan();
        let half_w: f32 = half_h * self.get_aspect();
        let ndc_x: f32 = (2.0 * u - 1.0) * half_w;
        let ndc_y: f32 = (1.0 - 2.0 * v) * half_h;
        let forward: Vec3 = self.get_forward();
        let right: Vec3 = self.get_right();
        let up: Vec3 = self.get_up();
        let pinhole_dir: Vec3 = forward
            .add(right.scale(ndc_x))
            .add(up.scale(ndc_y))
            .normalize();
        let aperture: f32 = self.get_aperture_radius();
        let origin: Vec3 = self.get_position();
        if aperture <= RT_SCENE_EPSILON {
            return Ray3D::new(origin, pinhole_dir);
        }
        let cos_view: f32 = pinhole_dir.dot(forward).max(1e-4);
        let t_focus: f32 = self.get_focal_distance() / cos_view;
        let focus_point: Vec3 = origin.add(pinhole_dir.scale(t_focus));
        let disk: [f32; 2] = concentric_sample_disk(lens_sample);
        let lens_origin: Vec3 = origin
            .add(right.scale(disk[0] * aperture))
            .add(up.scale(disk[1] * aperture));
        Ray3D::new(lens_origin, focus_point.sub(lens_origin))
    }

    /// Computes a deterministic bit-exact 64-bit fingerprint of camera pose and optics for temporal accumulation reset detection.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Camera reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Stable 64-bit hash changing whenever any camera parameter mutates.
    #[must_use]
    pub fn motion_fingerprint(&self) -> u64 {
        let mut h: u64 = RT_FNV_OFFSET_BASIS;
        h = fnv1a_mix_vec3(h, self.get_position());
        h = fnv1a_mix_vec3(h, self.get_forward());
        h = fnv1a_mix_vec3(h, self.get_right());
        h = fnv1a_mix_vec3(h, self.get_up());
        h = fnv1a_mix_f32(h, self.get_fov_y_rad());
        h = fnv1a_mix_f32(h, self.get_aspect());
        h = fnv1a_mix_f32(h, self.get_aperture_radius());
        fnv1a_mix_f32(h, self.get_focal_distance())
    }
}

/// Default empty ray-tracing scene constructor for `RaytraceScene`.
impl Default for RaytraceScene {
    /// Creates an empty `RaytraceScene` with a default matte material at slot `0`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty scene ready for geometry and lights.
    fn default() -> Self {
        Self::new()
    }
}

/// Geometry management, unified ray queries, environment shading, and `World3D` conversion for `RaytraceScene`.
impl RaytraceScene {
    /// Creates an empty ray-tracing scene with a default neutral diffuse material registered at index `0`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty `RaytraceScene`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            blas_list: Vec::new(),
            tlas: Tlas3D::new(),
            primitives: Vec::new(),
            sdf_tracers: Vec::new(),
            materials: vec![RtMaterial::default()],
            lights: Vec::new(),
            environment: RtEnvironment::Black,
            camera: RtCamera::default(),
            revision: 1,
        }
    }

    /// Increments the scene revision counter so temporal accumulators invalidate stale frames.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    pub fn bump_revision(&mut self) {
        let next: u64 = self.get_revision().wrapping_add(1);
        self.set_revision(next);
    }

    /// Registers a material and returns its `material_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `RtMaterial` - Physical material descriptor.
    ///
    /// # Returns
    ///
    /// - `u32` - Registered material index.
    pub fn add_material(&mut self, material: RtMaterial) -> u32 {
        let id: u32 = self.get_materials().len() as u32;
        self.get_mut_materials().push(material);
        self.bump_revision();
        id
    }

    /// Registers a prebuilt `Blas3D` and returns its `blas_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `Blas3D` - Bottom-level triangle BVH.
    ///
    /// # Returns
    ///
    /// - `u32` - Registered BLAS index.
    pub fn add_blas(&mut self, blas: Blas3D) -> u32 {
        let id: u32 = self.get_blas_list().len() as u32;
        self.get_mut_blas_list().push(blas);
        self.bump_revision();
        id
    }

    /// Builds and registers a `Blas3D` from an existing `Mesh3D` and returns its `blas_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `&Mesh3D` - Source mesh geometry.
    ///
    /// # Returns
    ///
    /// - `u32` - Registered BLAS index.
    pub fn add_mesh(&mut self, mesh: &Mesh3D) -> u32 {
        let blas: Blas3D = Blas3D::from_mesh(mesh);
        self.add_blas(blas)
    }

    /// Adds a transformed mesh instance referencing `blas_id` and returns its stable `instance_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `u32` - Registered BLAS index.
    /// - `Mat4` - Local-to-world affine transform matrix.
    /// - `u32` - Material index.
    ///
    /// # Returns
    ///
    /// - `usize` - Stable TLAS instance identifier.
    pub fn add_instance(&mut self, blas_id: u32, transform: Mat4, material_id: u32) -> usize {
        let local_bounds: AxisAlignedBox3D = self
            .get_blas_list()
            .get(blas_id as usize)
            .map_or(AxisAlignedBox3D::empty(), |blas: &Blas3D| blas.get_bounds());
        let instance: RtInstance = RtInstance::new(blas_id, transform, material_id, local_bounds);
        let id: usize = self.get_mut_tlas().add_instance(instance);
        self.bump_revision();
        id
    }

    /// Updates an existing instance's world transform without rebuilding its underlying `Blas3D`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `usize` - Stable instance identifier.
    /// - `Mat4` - Updated local-to-world affine transform.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the instance existed and was updated.
    pub fn update_instance_transform(&mut self, instance_id: usize, transform: Mat4) -> bool {
        let blas_id_opt: Option<u32> = self
            .get_tlas()
            .get_instances()
            .get(instance_id)
            .map(|inst: &RtInstance| inst.get_blas_id());
        let blas_id: u32 = match blas_id_opt {
            Some(id) => id,
            None => return false,
        };
        let local_bounds: AxisAlignedBox3D = self
            .get_blas_list()
            .get(blas_id as usize)
            .map_or(AxisAlignedBox3D::empty(), |blas: &Blas3D| blas.get_bounds());
        let updated: bool =
            self.get_mut_tlas()
                .update_instance_transform(instance_id, transform, local_bounds);
        if updated {
            self.bump_revision();
        }
        updated
    }

    /// Appends an analytic primitive to the scene and returns its index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `RtPrimitive` - Bound analytic primitive.
    ///
    /// # Returns
    ///
    /// - `usize` - Analytic primitive index.
    pub fn add_primitive(&mut self, primitive: RtPrimitive) -> usize {
        let id: usize = self.get_primitives().len();
        self.get_mut_primitives().push(primitive);
        self.bump_revision();
        id
    }

    /// Appends an implicit SDF sphere-tracer volume to the scene and returns its index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `SdfSphereTracer` - Configured SDF volume.
    ///
    /// # Returns
    ///
    /// - `usize` - SDF volume index.
    pub fn add_sdf_tracer(&mut self, tracer: SdfSphereTracer) -> usize {
        let id: usize = self.get_sdf_tracers().len();
        self.get_mut_sdf_tracers().push(tracer);
        self.bump_revision();
        id
    }

    /// Appends a physical light emitter to the scene and returns its index.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    /// - `RtLight` - Light descriptor.
    ///
    /// # Returns
    ///
    /// - `usize` - Light index.
    pub fn add_light(&mut self, light: RtLight) -> usize {
        let id: usize = self.get_lights().len();
        self.get_mut_lights().push(light);
        self.bump_revision();
        id
    }

    /// Rebuilds the scene TLAS using the binned Surface Area Heuristic.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    pub fn rebuild_tlas(&mut self) {
        self.get_mut_tlas().rebuild();
        self.bump_revision();
    }

    /// Refits the scene TLAS bottom-up in O(N) with zero heap allocation after moving instances.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable scene reference.
    pub fn refit_tlas(&mut self) {
        self.get_mut_tlas().refit();
        self.bump_revision();
    }

    /// Returns the `RtMaterial` registered at `material_id`, falling back to a default diffuse material if out of bounds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene reference.
    /// - `u32` - Material identifier.
    ///
    /// # Returns
    ///
    /// - `RtMaterial` - Resolved material descriptor.
    #[must_use]
    pub fn material(&self, material_id: u32) -> RtMaterial {
        self.get_materials()
            .get(material_id as usize)
            .copied()
            .unwrap_or_default()
    }

    /// Traces a world-space ray against the TLAS, analytic primitives, and SDF volumes returning the globally closest hit.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene reference.
    /// - `&Ray3D` - World-space normalized ray.
    /// - `f32` - Minimum accepted hit distance.
    /// - `f32` - Maximum accepted hit distance.
    ///
    /// # Returns
    ///
    /// - `Option<RtHit>` - Globally closest surface hit if any.
    #[must_use]
    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RtHit> {
        let mut best_t: f32 = t_max;
        let mut best_hit: Option<RtHit> =
            self.get_tlas()
                .trace_closest(self.get_blas_list().as_slice(), ray, t_min, best_t);
        if let Some(hit) = best_hit {
            best_t = hit.get_distance();
        }
        for (idx, prim) in self.get_primitives().iter().enumerate() {
            if let Some(hit) = prim.intersect(ray, t_min, best_t, idx as u32) {
                best_t = hit.get_distance();
                best_hit = Some(hit);
            }
        }
        let prim_offset: u32 = self.get_primitives().len() as u32;
        for (idx, sdf) in self.get_sdf_tracers().iter().enumerate() {
            if let Some(hit) = sdf.trace(ray, t_min, best_t, prim_offset + (idx as u32)) {
                best_t = hit.get_distance();
                best_hit = Some(hit);
            }
        }
        best_hit
    }

    /// Tests whether a world-space ray is occluded by any TLAS mesh, analytic primitive, or SDF volume in `[t_min, t_max]`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene reference.
    /// - `&Ray3D` - World-space shadow or ambient-occlusion ray.
    /// - `f32` - Minimum accepted hit distance.
    /// - `f32` - Maximum accepted hit distance.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when any occluder intersects the ray segment.
    #[must_use]
    pub fn trace_any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
        if self
            .get_tlas()
            .trace_any_hit(self.get_blas_list().as_slice(), ray, t_min, t_max)
        {
            return true;
        }
        for prim in self.get_primitives() {
            if prim.any_hit(ray, t_min, t_max) {
                return true;
            }
        }
        for sdf in self.get_sdf_tracers() {
            if sdf.any_hit(ray, t_min, t_max) {
                return true;
            }
        }
        false
    }

    /// Intersects a ray against all finite area lights in the scene returning `(light_index, distance, radiance, solid_angle_pdf)` of the closest hit.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene reference.
    /// - `&Ray3D` - World-space ray.
    /// - `f32` - Minimum accepted distance.
    /// - `f32` - Maximum accepted distance.
    ///
    /// # Returns
    ///
    /// - `Option<(usize, f32, Vec3, f32)>` - Closest intersected area light metadata if any.
    #[must_use]
    pub fn intersect_area_lights(
        &self,
        ray: &Ray3D,
        t_min: f32,
        t_max: f32,
    ) -> Option<(usize, f32, Vec3, f32)> {
        let mut best_t: f32 = t_max;
        let mut result: Option<(usize, f32, Vec3, f32)> = None;
        for (idx, light) in self.get_lights().iter().enumerate() {
            if let Some((dist, rad, pdf)) = light.intersect_area(ray, t_min, best_t) {
                best_t = dist;
                result = Some((idx, dist, rad, pdf));
            }
        }
        result
    }

    /// Evaluates the background environment radiance along unit world-space direction `direction`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Scene reference.
    /// - `Vec3` - Escaping world-space ray direction.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linear HDR RGB sky or environment radiance.
    #[must_use]
    pub fn evaluate_environment(&self, direction: Vec3) -> Vec3 {
        let dir: Vec3 = direction.normalize();
        match self.get_environment() {
            RtEnvironment::Black => Vec3::zero(),
            RtEnvironment::Solid(color) => Vec3::new(
                color.get_x().max(0.0),
                color.get_y().max(0.0),
                color.get_z().max(0.0),
            ),
            RtEnvironment::GradientSky {
                zenith,
                horizon,
                ground,
                sun_dir,
                sun_color,
                sun_angular_radius_rad,
            } => {
                let y: f32 = dir.get_y();
                let mut sky: Vec3 = if y >= 0.0 {
                    let t: f32 = y.powf(0.55).clamp(0.0, 1.0);
                    horizon.lerp(zenith, t)
                } else {
                    let t: f32 = (-y).powf(0.45).clamp(0.0, 1.0);
                    horizon.lerp(ground, t)
                };
                if sun_angular_radius_rad > 1e-5 {
                    let cos_sun: f32 = dir.dot(sun_dir.normalize());
                    let cos_edge: f32 = sun_angular_radius_rad.cos();
                    if cos_sun >= cos_edge {
                        sky = sky.add(sun_color);
                    }
                }
                Vec3::new(
                    sky.get_x().max(0.0),
                    sky.get_y().max(0.0),
                    sky.get_z().max(0.0),
                )
            }
        }
    }

    /// Bridges an existing `euv-core` `World3D` scene directly into a ready-to-trace `RaytraceScene`.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Source `euv-core` 3D world containing meshes, objects, lights, sky, and camera.
    /// - `f32` - Target viewport width-to-height aspect ratio.
    ///
    /// # Returns
    ///
    /// - `Self` - Populated `RaytraceScene` with built BLAS/TLAS acceleration structures.
    #[must_use]
    pub fn from_world3d(world: &World3D, aspect: f32) -> Self {
        let mut scene: Self = Self::new();
        let mesh_chains: &[MeshLodChain] = world.get_mesh_library().as_slice();
        let mut mesh_to_blas: Vec<Option<u32>> = Vec::with_capacity(mesh_chains.len());
        for chain in mesh_chains {
            if let Some(lod0) = chain.get_levels().first() {
                let blas_id: u32 = scene.add_mesh(lod0);
                mesh_to_blas.push(Some(blas_id));
            } else {
                mesh_to_blas.push(None);
            }
        }
        let principled_table: &[PrincipledMaterial3D] = world.get_principled_materials().as_slice();
        for (obj_idx, obj) in world.get_objects().iter().enumerate() {
            if !world.is_object_visible(obj_idx) {
                continue;
            }
            let mesh_id: usize = obj.get_mesh_id();
            let blas_id_opt: Option<u32> =
                if let Some(deformed) = world.deformed_mesh_for_object(obj_idx) {
                    Some(scene.add_mesh(deformed))
                } else {
                    mesh_to_blas.get(mesh_id).copied().flatten()
                };
            let blas_id: u32 = match blas_id_opt {
                Some(id) => id,
                None => continue,
            };
            let rt_mat: RtMaterial = match obj.try_get_principled_material_id() {
                Some(p_id) => match principled_table.get(p_id as usize) {
                    Some(p_mat) => RtMaterial::from_principled_material(p_mat),
                    None => RtMaterial::from_pbr_material(&obj.get_material()),
                },
                None => RtMaterial::from_pbr_material(&obj.get_material()),
            };
            let mat_id: u32 = scene.add_material(rt_mat);
            let model_mat: Mat4 = obj.get_transform().to_mat4();
            let _: usize = scene.add_instance(blas_id, model_mat, mat_id);
        }
        let sun: DirectionalLight3D = world.get_sun();
        let _: usize = scene.add_light(RtLight::directional(
            sun.get_direction(),
            sun.get_color(),
            2.2,
            0.015,
        ));
        scene.set_environment(RtEnvironment::GradientSky {
            zenith: sun.get_sky_zenith(),
            horizon: sun.get_sky_horizon(),
            ground: sun.get_sky_horizon().scale(0.25),
            sun_dir: sun.get_direction().normalize(),
            sun_color: sun.get_color().scale(6.0),
            sun_angular_radius_rad: 0.02,
        });
        for pt in world.get_point_lights() {
            let _: usize = scene.add_light(RtLight::point(
                pt.get_position(),
                pt.get_color(),
                pt.get_intensity(),
                (pt.get_radius() * 0.05).clamp(0.0, 0.25),
            ));
        }
        for sp in world.get_spot_lights() {
            let inner_deg: f32 = sp.get_inner_cos().clamp(-1.0, 1.0).acos().to_degrees();
            let outer_deg: f32 = sp.get_outer_cos().clamp(-1.0, 1.0).acos().to_degrees();
            let _: usize = scene.add_light(RtLight::spot(
                sp.get_position(),
                sp.get_direction(),
                sp.get_color(),
                sp.get_intensity(),
                inner_deg,
                outer_deg,
                0.05,
            ));
        }
        for area in world.get_area_lights() {
            let light: RtLight = match area.get_shape() {
                AreaLightShape3D::Rectangle => RtLight::rect_area(
                    area.get_position(),
                    area.get_direction(),
                    Vec2::new(area.get_width(), area.get_height()),
                    area.get_color(),
                    area.get_intensity(),
                    area.get_two_sided(),
                ),
                AreaLightShape3D::Disk => RtLight::disk_area(
                    area.get_position(),
                    area.get_direction(),
                    0.5 * area.get_width().max(area.get_height()),
                    area.get_color(),
                    area.get_intensity(),
                    area.get_two_sided(),
                ),
            };
            let _: usize = scene.add_light(light);
        }
        let world_cam: Camera3D = world.get_camera();
        scene.set_camera(RtCamera::from_camera3d(&world_cam, aspect));
        scene.rebuild_tlas();
        scene
    }
}

/// Default empty builder constructor for `RaytraceSceneBuilder`.
impl Default for RaytraceSceneBuilder {
    /// Creates an empty `RaytraceSceneBuilder`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty builder.
    fn default() -> Self {
        Self::new()
    }
}

/// Fluent scene assembly helpers and curated presets (Cornell Box, Glass Gallery, Lit Outdoor) for `RaytraceSceneBuilder`.
impl RaytraceSceneBuilder {
    /// Creates a new fluent `RaytraceSceneBuilder`.
    ///
    /// # Returns
    ///
    /// - `Self` - Builder wrapping an empty `RaytraceScene`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            scene: RaytraceScene::new(),
        }
    }

    /// Configures the camera on the scene under construction.
    ///
    /// # Arguments
    ///
    /// - `Self` - Builder value.
    /// - `RtCamera` - Camera configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated builder.
    #[must_use]
    pub fn with_camera(mut self, camera: RtCamera) -> Self {
        self.get_mut_scene().set_camera(camera);
        self
    }

    /// Configures the background environment dome on the scene under construction.
    ///
    /// # Arguments
    ///
    /// - `Self` - Builder value.
    /// - `RtEnvironment` - Environment dome.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated builder.
    #[must_use]
    pub fn with_environment(mut self, environment: RtEnvironment) -> Self {
        self.get_mut_scene().set_environment(environment);
        self
    }

    /// Adds a light emitter to the scene under construction.
    ///
    /// # Arguments
    ///
    /// - `Self` - Builder value.
    /// - `RtLight` - Physical light emitter.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated builder.
    #[must_use]
    pub fn with_light(mut self, light: RtLight) -> Self {
        let _: usize = self.get_mut_scene().add_light(light);
        self
    }

    /// Finalizes the scene, rebuilding the TLAS and returning the completed `RaytraceScene`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Completed builder.
    ///
    /// # Returns
    ///
    /// - `RaytraceScene` - Ready-to-trace scene.
    #[must_use]
    pub fn build(mut self) -> RaytraceScene {
        self.get_mut_scene().rebuild_tlas();
        let Self { scene } = self;
        scene
    }

    /// 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.
    ///
    /// # Arguments
    ///
    /// - `f32` - Viewport width-to-height aspect ratio.
    ///
    /// # Returns
    ///
    /// - `RaytraceScene` - Ready-to-trace Cornell Box scene.
    #[must_use]
    pub fn cornell_box(aspect: f32) -> RaytraceScene {
        let mut scene: RaytraceScene = RaytraceScene::new();
        let white_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.76, 0.75, 0.72)));
        let red_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.68, 0.12, 0.10)));
        let green_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.14, 0.52, 0.18)));
        let metal_mat: u32 =
            scene.add_material(RtMaterial::metal(Vec3::new(0.95, 0.80, 0.45), 0.14));
        let glass_mat: u32 = scene.add_material(RtMaterial::dielectric(
            Vec3::splat(1.0),
            RT_DEFAULT_GLASS_IOR,
            0.0,
            Vec3::new(0.18, 0.04, 0.08),
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Quad {
                corner: Vec3::new(-2.0, 0.0, -2.0),
                edge_u: Vec3::new(0.0, 0.0, 4.0),
                edge_v: Vec3::new(4.0, 0.0, 0.0),
            },
            white_mat,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Quad {
                corner: Vec3::new(-2.0, 4.0, -2.0),
                edge_u: Vec3::new(4.0, 0.0, 0.0),
                edge_v: Vec3::new(0.0, 0.0, 4.0),
            },
            white_mat,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Quad {
                corner: Vec3::new(-2.0, 0.0, -2.0),
                edge_u: Vec3::new(4.0, 0.0, 0.0),
                edge_v: Vec3::new(0.0, 4.0, 0.0),
            },
            white_mat,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Quad {
                corner: Vec3::new(-2.0, 0.0, -2.0),
                edge_u: Vec3::new(0.0, 4.0, 0.0),
                edge_v: Vec3::new(0.0, 0.0, 4.0),
            },
            red_mat,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Quad {
                corner: Vec3::new(2.0, 0.0, -2.0),
                edge_u: Vec3::new(0.0, 0.0, 4.0),
                edge_v: Vec3::new(0.0, 4.0, 0.0),
            },
            green_mat,
        ));
        let cube_mesh: Mesh3D = Mesh3D::box_mesh(
            RT_CORNELL_BOX_CUBE_NAME,
            1.1,
            1.8,
            1.1,
            true,
            PbrMaterial::default(),
        );
        let cube_blas: u32 = scene.add_mesh(&cube_mesh);
        let cube_xform: Mat4 = Mat4::from_trs(Vec3::new(-0.75, 0.0, -0.65), 0.38, Vec3::splat(1.0));
        let _: usize = scene.add_instance(cube_blas, cube_xform, white_mat);
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Sphere {
                center: Vec3::new(0.85, 0.65, -0.45),
                radius: 0.65,
            },
            metal_mat,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Sphere {
                center: Vec3::new(-0.15, 0.55, 0.72),
                radius: 0.55,
            },
            glass_mat,
        ));
        let _: usize = scene.add_light(RtLight::rect_area(
            Vec3::new(0.0, 3.97, 0.0),
            Vec3::new(0.0, -1.0, 0.0),
            Vec2::new(1.4, 1.4),
            Vec3::new(1.0, 0.94, 0.84),
            16.0,
            false,
        ));
        scene.set_environment(RtEnvironment::Black);
        scene.set_camera(RtCamera::look_at(
            Vec3::new(0.0, 2.0, 5.4),
            Vec3::new(0.0, 1.85, 0.0),
            Vec3::new(0.0, 1.0, 0.0),
            42.0,
            aspect,
        ));
        scene.rebuild_tlas();
        scene
    }

    /// Constructs a reflective and refractive glass gallery showcasing Beer-Lambert absorption, clearcoat, mirror chrome, and SDF CSG geometry.
    ///
    /// # Arguments
    ///
    /// - `f32` - Viewport width-to-height aspect ratio.
    ///
    /// # Returns
    ///
    /// - `RaytraceScene` - Ready-to-trace glass gallery scene.
    #[must_use]
    pub fn glass_gallery(aspect: f32) -> RaytraceScene {
        let mut scene: RaytraceScene = RaytraceScene::new();
        let floor_mat: u32 = scene.add_material(RtMaterial::clearcoat(
            Vec3::new(0.18, 0.20, 0.24),
            0.35,
            0.85,
            0.05,
        ));
        let pedestal_mat: u32 =
            scene.add_material(RtMaterial::oren_nayar(Vec3::new(0.72, 0.70, 0.66), 0.4));
        let chrome_mat: u32 = scene.add_material(RtMaterial::mirror(Vec3::splat(0.96)));
        let emerald_glass: u32 = scene.add_material(RtMaterial::dielectric(
            Vec3::splat(1.0),
            1.52,
            0.0,
            Vec3::new(0.85, 0.12, 0.35),
        ));
        let sapphire_glass: u32 = scene.add_material(RtMaterial::dielectric(
            Vec3::splat(1.0),
            1.45,
            0.03,
            Vec3::new(0.75, 0.30, 0.05),
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Plane {
                point: Vec3::zero(),
                normal: Vec3::new(0.0, 1.0, 0.0),
            },
            floor_mat,
        ));
        let ped_mesh: Mesh3D = Mesh3D::box_mesh(
            RT_GALLERY_PEDESTAL_NAME,
            4.2,
            0.25,
            2.2,
            true,
            PbrMaterial::default(),
        );
        let ped_blas: u32 = scene.add_mesh(&ped_mesh);
        let _: usize = scene.add_instance(ped_blas, Mat4::identity(), pedestal_mat);
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Sphere {
                center: Vec3::new(-1.3, 0.9, 0.0),
                radius: 0.65,
            },
            emerald_glass,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Sphere {
                center: Vec3::new(1.3, 0.9, 0.0),
                radius: 0.65,
            },
            chrome_mat,
        ));
        let mut sdf: SdfSphereTracer = SdfSphereTracer::new(
            sapphire_glass,
            AxisAlignedBox3D::new(Vec3::new(-0.8, 0.2, -0.8), Vec3::new(0.8, 1.8, 0.8)),
        );
        let s_box: u32 = sdf.push_op(RtSdfOp::Box {
            center: Vec3::new(0.0, 0.95, 0.0),
            half_extents: Vec3::splat(0.45),
            rounding: 0.06,
        });
        let s_cut: u32 = sdf.push_op(RtSdfOp::Sphere {
            center: Vec3::new(0.0, 0.95, 0.0),
            radius: 0.56,
        });
        let _: u32 = sdf.push_op(RtSdfOp::SmoothSubtract {
            base: s_box,
            cutout: s_cut,
            smoothness: 0.04,
        });
        let _: usize = scene.add_sdf_tracer(sdf);
        let _: usize = scene.add_light(RtLight::rect_area(
            Vec3::new(-2.4, 3.6, 2.0),
            Vec3::new(0.45, -0.8, -0.38),
            Vec2::new(2.0, 1.2),
            Vec3::new(1.0, 0.96, 0.90),
            9.0,
            false,
        ));
        let _: usize = scene.add_light(RtLight::disk_area(
            Vec3::new(2.8, 3.2, -1.6),
            Vec3::new(-0.6, -0.7, 0.35),
            0.9,
            Vec3::new(0.75, 0.88, 1.0),
            8.0,
            false,
        ));
        scene.set_environment(RtEnvironment::GradientSky {
            zenith: Vec3::new(0.08, 0.12, 0.22),
            horizon: Vec3::new(0.22, 0.26, 0.34),
            ground: Vec3::new(0.05, 0.06, 0.08),
            sun_dir: Vec3::new(0.4, 0.8, 0.4).normalize(),
            sun_color: Vec3::new(2.0, 1.8, 1.6),
            sun_angular_radius_rad: 0.03,
        });
        scene.set_camera(
            RtCamera::look_at(
                Vec3::new(0.0, 1.65, 4.4),
                Vec3::new(0.0, 0.85, 0.0),
                Vec3::new(0.0, 1.0, 0.0),
                40.0,
                aspect,
            )
            .with_thin_lens(0.04, 4.4),
        );
        scene.rebuild_tlas();
        scene
    }

    /// Constructs a sunlit outdoor preset with soft solar shadows, architectural monolith instances, metal and glass spheres, and physical sky dome.
    ///
    /// # Arguments
    ///
    /// - `f32` - Viewport width-to-height aspect ratio.
    ///
    /// # Returns
    ///
    /// - `RaytraceScene` - Ready-to-trace outdoor scene.
    #[must_use]
    pub fn lit_outdoor(aspect: f32) -> RaytraceScene {
        let mut scene: RaytraceScene = RaytraceScene::new();
        let ground_mat: u32 =
            scene.add_material(RtMaterial::oren_nayar(Vec3::new(0.42, 0.46, 0.38), 0.5));
        let stone_mat: u32 = scene.add_material(RtMaterial::lambert(Vec3::new(0.78, 0.74, 0.68)));
        let chrome_mat: u32 =
            scene.add_material(RtMaterial::metal(Vec3::new(0.92, 0.94, 0.96), 0.08));
        let water_glass: u32 = scene.add_material(RtMaterial::dielectric(
            Vec3::splat(1.0),
            RT_DEFAULT_WATER_IOR,
            0.01,
            Vec3::new(0.32, 0.08, 0.04),
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Plane {
                point: Vec3::zero(),
                normal: Vec3::new(0.0, 1.0, 0.0),
            },
            ground_mat,
        ));
        let mono_mesh: Mesh3D = Mesh3D::box_mesh(
            RT_OUTDOOR_MONOLITH_NAME,
            1.2,
            2.8,
            1.2,
            true,
            PbrMaterial::default(),
        );
        let mono_blas: u32 = scene.add_mesh(&mono_mesh);
        let _: usize = scene.add_instance(
            mono_blas,
            Mat4::from_trs(Vec3::new(-1.8, 0.0, -1.4), 0.25, Vec3::splat(1.0)),
            stone_mat,
        );
        let _: usize = scene.add_instance(
            mono_blas,
            Mat4::from_trs(Vec3::new(1.9, 0.0, -2.0), -0.32, Vec3::new(0.8, 0.7, 0.8)),
            stone_mat,
        );
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Sphere {
                center: Vec3::new(-0.35, 0.75, 0.4),
                radius: 0.75,
            },
            chrome_mat,
        ));
        let _: usize = scene.add_primitive(RtPrimitive::new(
            RtPrimitiveShape::Sphere {
                center: Vec3::new(1.05, 0.6, 0.95),
                radius: 0.6,
            },
            water_glass,
        ));
        let sun_dir: Vec3 = Vec3::new(0.55, 0.72, 0.42).normalize();
        let _: usize = scene.add_light(RtLight::directional(
            sun_dir,
            Vec3::new(1.0, 0.94, 0.84),
            3.2,
            0.025,
        ));
        scene.set_environment(RtEnvironment::GradientSky {
            zenith: Vec3::new(0.18, 0.42, 0.88),
            horizon: Vec3::new(0.68, 0.80, 0.96),
            ground: Vec3::new(0.20, 0.22, 0.18),
            sun_dir,
            sun_color: Vec3::new(10.0, 9.0, 7.5),
            sun_angular_radius_rad: 0.025,
        });
        scene.set_camera(RtCamera::look_at(
            Vec3::new(0.2, 1.8, 5.8),
            Vec3::new(0.0, 0.9, -0.3),
            Vec3::new(0.0, 1.0, 0.0),
            44.0,
            aspect,
        ));
        scene.rebuild_tlas();
        scene
    }
}