euv-core 0.48.1

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
use super::*;

/// Vector arithmetic, normalization, dot/cross products, and reflection helpers for `Vec3`.
impl Vec3 {
    /// Zero vector `(0, 0, 0)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Zero vector.
    #[must_use]
    pub const fn zero() -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }
    }

    /// Uniform vector `(v, v, v)`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Scalar value replicated across all axes.
    ///
    /// # Returns
    ///
    /// - `Self` - Splat vector.
    #[must_use]
    pub const fn splat(v: f32) -> Self {
        Self { x: v, y: v, z: v }
    }

    /// Scales `self` by scalar `s`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source vector.
    /// - `f32` - Scalar multiplier.
    ///
    /// # Returns
    ///
    /// - `Self` - Scaled vector.
    #[inline(always)]
    #[must_use]
    pub fn scale(self, s: f32) -> Self {
        Self {
            x: self.get_x() * s,
            y: self.get_y() * s,
            z: self.get_z() * s,
        }
    }

    /// Computes the dot product `self · rhs`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `f32` - Scalar dot product.
    #[inline(always)]
    #[must_use]
    pub fn dot(self, rhs: Self) -> f32 {
        self.get_x().mul_add(
            rhs.get_x(),
            self.get_y()
                .mul_add(rhs.get_y(), self.get_z() * rhs.get_z()),
        )
    }

    /// Computes the 3D cross product `self × rhs`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Orthogonal cross product vector.
    #[inline(always)]
    #[must_use]
    pub fn cross(self, rhs: Self) -> Self {
        Self {
            x: self.get_y() * rhs.get_z() - self.get_z() * rhs.get_y(),
            y: self.get_z() * rhs.get_x() - self.get_x() * rhs.get_z(),
            z: self.get_x() * rhs.get_y() - self.get_y() * rhs.get_x(),
        }
    }

    /// Computes squared Euclidean length.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source vector.
    ///
    /// # Returns
    ///
    /// - `f32` - Squared magnitude.
    #[inline(always)]
    #[must_use]
    pub fn length_sq(self) -> f32 {
        self.dot(self)
    }

    /// Computes Euclidean length.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source vector.
    ///
    /// # Returns
    ///
    /// - `f32` - Magnitude.
    #[inline(always)]
    #[must_use]
    pub fn length(self) -> f32 {
        self.length_sq().sqrt()
    }

    /// Returns a unit-length vector pointing along `self`, or `(0, 1, 0)` if degenerate.
    ///
    /// # Arguments
    ///
    /// - `Self` - Source vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized unit vector.
    #[inline(always)]
    #[must_use]
    pub fn normalize(self) -> Self {
        let len: f32 = self.length();
        if len > 1e-6 {
            self.scale(1.0 / len)
        } else {
            Self::new(0.0, 1.0, 0.0)
        }
    }

    /// Linearly interpolates between `self` and `other` by `t`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Start vector.
    /// - `Self` - End vector.
    /// - `f32` - Interpolation factor.
    ///
    /// # Returns
    ///
    /// - `Self` - Interpolated vector.
    #[inline(always)]
    #[must_use]
    pub fn lerp(self, other: Self, t: f32) -> Self {
        Self {
            x: (other.get_x() - self.get_x()).mul_add(t, self.get_x()),
            y: (other.get_y() - self.get_y()).mul_add(t, self.get_y()),
            z: (other.get_z() - self.get_z()).mul_add(t, self.get_z()),
        }
    }

    /// Reflects incident vector `self` across unit surface normal `normal`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Incident vector.
    /// - `Self` - Unit surface normal.
    ///
    /// # Returns
    ///
    /// - `Self` - Reflected direction vector.
    #[inline(always)]
    #[must_use]
    pub fn reflect(self, normal: Self) -> Self {
        self.sub(normal.scale(2.0 * self.dot(normal)))
    }

    /// Returns component-wise minimum of `self` and `rhs`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Component-wise minimum.
    #[must_use]
    pub fn min(self, rhs: Self) -> Self {
        Self {
            x: self.get_x().min(rhs.get_x()),
            y: self.get_y().min(rhs.get_y()),
            z: self.get_z().min(rhs.get_z()),
        }
    }

    /// Returns component-wise maximum of `self` and `rhs`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Component-wise maximum.
    #[must_use]
    pub fn max(self, rhs: Self) -> Self {
        Self {
            x: self.get_x().max(rhs.get_x()),
            y: self.get_y().max(rhs.get_y()),
            z: self.get_z().max(rhs.get_z()),
        }
    }

    /// Converts an sRGB `Color` into linear RGB `Vec3` radiance in `[0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `Color` - Source RGBA color.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized linear RGB vector.
    #[must_use]
    pub fn from_color(c: Color) -> Self {
        Self {
            x: (c.get_r() as f32) / 255.0,
            y: (c.get_g() as f32) / 255.0,
            z: (c.get_b() as f32) / 255.0,
        }
    }

    /// Maps a single HDR channel through the ACES filmic tone curve into sRGB byte space.
    ///
    /// # Arguments
    ///
    /// - `f32` - Linear HDR scalar.
    ///
    /// # Returns
    ///
    /// - `u8` - Gamma-encoded sRGB byte.
    #[inline(always)]
    #[must_use]
    fn aces_channel(v: f32) -> u8 {
        let x: f32 = v.max(0.0);
        let num: f32 = x * x.mul_add(2.51, 0.03);
        let den: f32 = x.mul_add(x.mul_add(2.43, 0.59), 0.14);
        let mapped: f32 = num / den;
        let idx: usize = mapped.clamp(0.0, 1.0).mul_add(1024.0, 0.5) as usize;
        LINEAR_TO_SRGB_LUT[idx.min(1024)]
    }

    /// Applies ACES filmic tone mapping and converts linear radiance to RGBA8 `[r, g, b, 255]`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Linear HDR RGB radiance.
    ///
    /// # Returns
    ///
    /// - `[u8; 4]` - Tone-mapped RGBA8 pixel bytes.
    #[inline(always)]
    #[must_use]
    pub fn to_aces_rgba8(self) -> [u8; 4] {
        [
            Self::aces_channel(self.get_x()),
            Self::aces_channel(self.get_y()),
            Self::aces_channel(self.get_z()),
            255,
        ]
    }

    /// Maps four HDR scalar values through the ACES filmic tone curve into 10-bit LUT indices `[0..=1024]`.
    ///
    /// # Arguments
    ///
    /// - `[f32; 4]` - Four linear HDR channel scalars.
    ///
    /// # Returns
    ///
    /// - `[u32; 4]` - Clamped LUT indices into `LINEAR_TO_SRGB_LUT`.
    #[inline(always)]
    #[must_use]
    fn aces_indices_4x(vals: [f32; 4]) -> [u32; 4] {
        #[cfg(target_arch = "aarch64")]
        {
            let mut out: [u32; 4] = [0; 4];
            // SAFETY: `vals` and `out` are valid 16-byte stack arrays; NEON is mandatory on `aarch64`.
            unsafe {
                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
                let x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
                    core::arch::aarch64::vld1q_f32(vals.as_ptr()),
                    zero,
                );
                let num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
                    x,
                    core::arch::aarch64::vfmaq_f32(
                        core::arch::aarch64::vdupq_n_f32(0.03),
                        x,
                        core::arch::aarch64::vdupq_n_f32(2.51),
                    ),
                );
                let den_inner: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
                    core::arch::aarch64::vdupq_n_f32(0.59),
                    x,
                    core::arch::aarch64::vdupq_n_f32(2.43),
                );
                let den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
                    core::arch::aarch64::vdupq_n_f32(0.14),
                    x,
                    den_inner,
                );
                let den_est: core::arch::aarch64::float32x4_t =
                    core::arch::aarch64::vrecpeq_f32(den);
                let inv_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
                    den_est,
                    core::arch::aarch64::vrecpsq_f32(den, den_est),
                );
                let mapped: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
                    core::arch::aarch64::vmaxq_f32(
                        core::arch::aarch64::vmulq_f32(num, inv_den),
                        zero,
                    ),
                    one,
                );
                let scaled: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
                    core::arch::aarch64::vmulq_f32(
                        mapped,
                        core::arch::aarch64::vdupq_n_f32(1024.0),
                    ),
                    core::arch::aarch64::vdupq_n_f32(0.5),
                );
                let idx_u32: core::arch::aarch64::uint32x4_t =
                    core::arch::aarch64::vcvtq_u32_f32(scaled);
                core::arch::aarch64::vst1q_u32(out.as_mut_ptr(), idx_u32);
            }
            [
                out[0].min(1024),
                out[1].min(1024),
                out[2].min(1024),
                out[3].min(1024),
            ]
        }
        #[cfg(target_arch = "x86_64")]
        {
            let mut out: [i32; 4] = [0; 4];
            // SAFETY: `vals` and `out` are valid 16-byte stack arrays; SSE2 is mandatory on `x86_64`.
            unsafe {
                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(0.0);
                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
                let x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
                    core::arch::x86_64::_mm_loadu_ps(vals.as_ptr()),
                    zero,
                );
                let num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
                    x,
                    core::arch::x86_64::_mm_add_ps(
                        core::arch::x86_64::_mm_mul_ps(x, core::arch::x86_64::_mm_set1_ps(2.51)),
                        core::arch::x86_64::_mm_set1_ps(0.03),
                    ),
                );
                let den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
                    core::arch::x86_64::_mm_mul_ps(
                        x,
                        core::arch::x86_64::_mm_add_ps(
                            core::arch::x86_64::_mm_mul_ps(
                                x,
                                core::arch::x86_64::_mm_set1_ps(2.43),
                            ),
                            core::arch::x86_64::_mm_set1_ps(0.59),
                        ),
                    ),
                    core::arch::x86_64::_mm_set1_ps(0.14),
                );
                let mapped: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
                    core::arch::x86_64::_mm_max_ps(core::arch::x86_64::_mm_div_ps(num, den), zero),
                    one,
                );
                let scaled: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
                    core::arch::x86_64::_mm_mul_ps(mapped, core::arch::x86_64::_mm_set1_ps(1024.0)),
                    core::arch::x86_64::_mm_set1_ps(0.5),
                );
                core::arch::x86_64::_mm_storeu_si128(
                    out.as_mut_ptr().cast::<core::arch::x86_64::__m128i>(),
                    core::arch::x86_64::_mm_cvttps_epi32(scaled),
                );
            }
            [
                (out[0].clamp(0, 1024)) as u32,
                (out[1].clamp(0, 1024)) as u32,
                (out[2].clamp(0, 1024)) as u32,
                (out[3].clamp(0, 1024)) as u32,
            ]
        }
        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
        {
            let mut out: [u32; 4] = [0; 4];
            // SAFETY: `vals` and `out` are valid 16-byte stack arrays; `simd128` is enabled on `wasm32`.
            unsafe {
                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
                let x: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
                    core::arch::wasm32::v128_load(vals.as_ptr().cast()),
                    zero,
                );
                let num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
                    x,
                    core::arch::wasm32::f32x4_add(
                        core::arch::wasm32::f32x4_mul(x, core::arch::wasm32::f32x4_splat(2.51)),
                        core::arch::wasm32::f32x4_splat(0.03),
                    ),
                );
                let den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
                    core::arch::wasm32::f32x4_mul(
                        x,
                        core::arch::wasm32::f32x4_add(
                            core::arch::wasm32::f32x4_mul(x, core::arch::wasm32::f32x4_splat(2.43)),
                            core::arch::wasm32::f32x4_splat(0.59),
                        ),
                    ),
                    core::arch::wasm32::f32x4_splat(0.14),
                );
                let mapped: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
                    core::arch::wasm32::f32x4_pmax(core::arch::wasm32::f32x4_div(num, den), zero),
                    one,
                );
                let scaled: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
                    core::arch::wasm32::f32x4_mul(mapped, core::arch::wasm32::f32x4_splat(1024.0)),
                    core::arch::wasm32::f32x4_splat(0.5),
                );
                core::arch::wasm32::v128_store(
                    out.as_mut_ptr().cast(),
                    core::arch::wasm32::u32x4_trunc_sat_f32x4(scaled),
                );
            }
            [
                out[0].min(1024),
                out[1].min(1024),
                out[2].min(1024),
                out[3].min(1024),
            ]
        }
        #[cfg(not(target_arch = "aarch64"))]
        #[cfg(not(target_arch = "x86_64"))]
        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
        {
            let mut out: [u32; 4] = [0; 4];
            for i in 0..4 {
                let x: f32 = vals[i].max(0.0);
                let num: f32 = x * x.mul_add(2.51, 0.03);
                let den: f32 = x.mul_add(x.mul_add(2.43, 0.59), 0.14);
                let idx: u32 = ((num / den).clamp(0.0, 1.0).mul_add(1024.0, 0.5)) as u32;
                out[i] = idx.min(1024);
            }
            out
        }
    }

    /// Vectorized 4-pixel ACES filmic tone mapper returning RGBA8 pixels and Rec.601 luma bytes.
    ///
    /// # Arguments
    ///
    /// - `[f32; 4]` - Four linear HDR red channel values.
    /// - `[f32; 4]` - Four linear HDR green channel values.
    /// - `[f32; 4]` - Four linear HDR blue channel values.
    ///
    /// # Returns
    ///
    /// - `([[u8; 4]; 4], [u8; 4])` - Tone-mapped RGBA8 pixels and corresponding Rec.601 luma values.
    #[inline(always)]
    #[must_use]
    pub fn aces_rgba8_luma_4x(r: [f32; 4], g: [f32; 4], b: [f32; 4]) -> ([[u8; 4]; 4], [u8; 4]) {
        let ir: [u32; 4] = Self::aces_indices_4x(r);
        let ig: [u32; 4] = Self::aces_indices_4x(g);
        let ib: [u32; 4] = Self::aces_indices_4x(b);
        let mut rgba: [[u8; 4]; 4] = [[0, 0, 0, 255]; 4];
        let mut luma: [u8; 4] = [0; 4];
        for i in 0..4 {
            let rv: u8 = LINEAR_TO_SRGB_LUT[ir[i] as usize];
            let gv: u8 = LINEAR_TO_SRGB_LUT[ig[i] as usize];
            let bv: u8 = LINEAR_TO_SRGB_LUT[ib[i] as usize];
            rgba[i] = [rv, gv, bv, 255];
            luma[i] = (((rv as u32) * 77 + (gv as u32) * 150 + (bv as u32) * 29) >> 8) as u8;
        }
        (rgba, luma)
    }
}

/// Component-wise vector addition for `Vec3`.
impl Add for Vec3 {
    type Output = Self;

    /// Adds two vectors component-wise.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Component-wise sum.
    #[inline(always)]
    fn add(self, rhs: Self) -> Self {
        Self {
            x: self.get_x() + rhs.get_x(),
            y: self.get_y() + rhs.get_y(),
            z: self.get_z() + rhs.get_z(),
        }
    }
}

/// Component-wise vector subtraction for `Vec3`.
impl Sub for Vec3 {
    type Output = Self;

    /// Subtracts `rhs` from `self`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Component-wise difference.
    #[inline(always)]
    fn sub(self, rhs: Self) -> Self {
        Self {
            x: self.get_x() - rhs.get_x(),
            y: self.get_y() - rhs.get_y(),
            z: self.get_z() - rhs.get_z(),
        }
    }
}

/// Component-wise Hadamard vector multiplication for `Vec3`.
impl Mul for Vec3 {
    type Output = Self;

    /// Multiplies two vectors component-wise.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left vector.
    /// - `Self` - Right vector.
    ///
    /// # Returns
    ///
    /// - `Self` - Component-wise product.
    #[inline(always)]
    fn mul(self, rhs: Self) -> Self {
        Self {
            x: self.get_x() * rhs.get_x(),
            y: self.get_y() * rhs.get_y(),
            z: self.get_z() * rhs.get_z(),
        }
    }
}

/// Matrix multiplication `self * rhs` for `Mat4`.
impl Mul for Mat4 {
    type Output = Self;

    /// Multiplies `self * rhs`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Left matrix.
    /// - `Self` - Right matrix.
    ///
    /// # Returns
    ///
    /// - `Self` - Product matrix.
    fn mul(self, rhs: Self) -> Self {
        let a: [f32; 16] = self.get_m();
        let b: [f32; 16] = rhs.get_m();
        let mut out: [f32; 16] = [0.0; 16];
        for col in 0..4 {
            for row in 0..4 {
                out[col * 4 + row] = a[row] * b[col * 4]
                    + a[4 + row] * b[col * 4 + 1]
                    + a[8 + row] * b[col * 4 + 2]
                    + a[12 + row] * b[col * 4 + 3];
            }
        }
        Self { m: out }
    }
}

/// Matrix constructors, projection, and point projection for `Mat4`.
impl Mat4 {
    /// Identity 4x4 matrix.
    ///
    /// # Returns
    ///
    /// - `Self` - Identity matrix.
    #[must_use]
    pub const fn identity() -> Self {
        Self {
            m: [
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            ],
        }
    }

    /// Builds a right-handed perspective projection matrix.
    ///
    /// # Arguments
    ///
    /// - `f32` - Vertical FOV in radians.
    /// - `f32` - Viewport aspect ratio `width / height`.
    /// - `f32` - Near plane distance.
    /// - `f32` - Far plane distance.
    ///
    /// # Returns
    ///
    /// - `Self` - Perspective projection matrix.
    #[must_use]
    pub fn perspective(fov_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
        let f: f32 = 1.0 / (fov_rad * 0.5).tan().max(1e-4);
        let nf: f32 = 1.0 / (near - far);
        Self {
            m: [
                f / aspect.max(0.01),
                0.0,
                0.0,
                0.0,
                0.0,
                f,
                0.0,
                0.0,
                0.0,
                0.0,
                (far + near) * nf,
                -1.0,
                0.0,
                0.0,
                2.0 * far * near * nf,
                0.0,
            ],
        }
    }

    /// Builds a right-handed look-at view matrix.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Camera eye position.
    /// - `Vec3` - Target look-at position.
    /// - `Vec3` - World up direction.
    ///
    /// # Returns
    ///
    /// - `Self` - View transformation matrix.
    #[must_use]
    pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
        let f: Vec3 = target.sub(eye).normalize();
        let s: Vec3 = f.cross(up).normalize();
        let u: Vec3 = s.cross(f);
        Self {
            m: [
                s.get_x(),
                u.get_x(),
                -f.get_x(),
                0.0,
                s.get_y(),
                u.get_y(),
                -f.get_y(),
                0.0,
                s.get_z(),
                u.get_z(),
                -f.get_z(),
                0.0,
                -s.dot(eye),
                -u.dot(eye),
                f.dot(eye),
                1.0,
            ],
        }
    }

    /// Builds a TRS model matrix (`translate * rotate_y * scale`).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World translation.
    /// - `f32` - Y-axis yaw rotation in radians.
    /// - `Vec3` - Non-uniform scale.
    ///
    /// # Returns
    ///
    /// - `Self` - Composed model transform matrix.
    #[must_use]
    pub fn from_trs(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
        let c: f32 = yaw_rad.cos();
        let s: f32 = yaw_rad.sin();
        Self {
            m: [
                c * scale.get_x(),
                0.0,
                -s * scale.get_x(),
                0.0,
                0.0,
                scale.get_y(),
                0.0,
                0.0,
                s * scale.get_z(),
                0.0,
                c * scale.get_z(),
                0.0,
                position.get_x(),
                position.get_y(),
                position.get_z(),
                1.0,
            ],
        }
    }

    /// Builds a full 3D Euler TRS model matrix (`translate * rotate_y(yaw) * rotate_x(pitch) * rotate_z(roll) * scale`).
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World translation.
    /// - `f32` - Y-axis yaw rotation in radians.
    /// - `f32` - X-axis pitch rotation in radians.
    /// - `f32` - Z-axis roll rotation in radians.
    /// - `Vec3` - Non-uniform scale.
    ///
    /// # Returns
    ///
    /// - `Self` - Composed 3D model transform matrix.
    #[must_use]
    pub fn from_trs_euler(
        position: Vec3,
        yaw_rad: f32,
        pitch_rad: f32,
        roll_rad: f32,
        scale: Vec3,
    ) -> Self {
        if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
            return Self::from_trs(position, yaw_rad, scale);
        }
        let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
        let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
        let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
        let r00: f32 = cy * cr + sy * sp * sr;
        let r10: f32 = cp * sr;
        let r20: f32 = -sy * cr + cy * sp * sr;
        let r01: f32 = -cy * sr + sy * sp * cr;
        let r11: f32 = cp * cr;
        let r21: f32 = sy * sr + cy * sp * cr;
        let r02: f32 = sy * cp;
        let r12: f32 = -sp;
        let r22: f32 = cy * cp;
        let sx: f32 = scale.get_x();
        let sy_sc: f32 = scale.get_y();
        let sz: f32 = scale.get_z();
        Self {
            m: [
                r00 * sx,
                r10 * sx,
                r20 * sx,
                0.0,
                r01 * sy_sc,
                r11 * sy_sc,
                r21 * sy_sc,
                0.0,
                r02 * sz,
                r12 * sz,
                r22 * sz,
                0.0,
                position.get_x(),
                position.get_y(),
                position.get_z(),
                1.0,
            ],
        }
    }

    /// Transforms a 3D point returning homogeneous clip coordinates `(x, y, z, w)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Transformation matrix.
    /// - `Vec3` - Input 3D position.
    ///
    /// # Returns
    ///
    /// - `[f32; 4]` - Homogeneous clip-space coordinates.
    #[inline(always)]
    #[must_use]
    pub fn mul_point4(&self, p: Vec3) -> [f32; 4] {
        let m: [f32; 16] = self.get_m();
        let px: f32 = p.get_x();
        let py: f32 = p.get_y();
        let pz: f32 = p.get_z();
        [
            px.mul_add(m[0], py.mul_add(m[4], pz.mul_add(m[8], m[12]))),
            px.mul_add(m[1], py.mul_add(m[5], pz.mul_add(m[9], m[13]))),
            px.mul_add(m[2], py.mul_add(m[6], pz.mul_add(m[10], m[14]))),
            px.mul_add(m[3], py.mul_add(m[7], pz.mul_add(m[11], m[15]))),
        ]
    }

    /// Transforms a 3D point by the upper 3x4 affine portion of `self`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Affine transformation matrix.
    /// - `Vec3` - Input 3D position.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Transformed 3D position.
    #[inline(always)]
    #[must_use]
    pub fn mul_point3(&self, p: Vec3) -> Vec3 {
        let m: [f32; 16] = self.get_m();
        let px: f32 = p.get_x();
        let py: f32 = p.get_y();
        let pz: f32 = p.get_z();
        Vec3::new(
            px.mul_add(m[0], py.mul_add(m[4], pz.mul_add(m[8], m[12]))),
            px.mul_add(m[1], py.mul_add(m[5], pz.mul_add(m[9], m[13]))),
            px.mul_add(m[2], py.mul_add(m[6], pz.mul_add(m[10], m[14]))),
        )
    }

    /// Transforms a 3D direction vector by the upper-left 3x3 linear portion of `self` (no translation).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Transformation matrix.
    /// - `Vec3` - Input 3D vector.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Linearly transformed 3D vector.
    #[inline(always)]
    #[must_use]
    pub fn mul_vec3(&self, v: Vec3) -> Vec3 {
        let m: [f32; 16] = self.get_m();
        let vx: f32 = v.get_x();
        let vy: f32 = v.get_y();
        let vz: f32 = v.get_z();
        Vec3::new(
            vx.mul_add(m[0], vy.mul_add(m[4], vz * m[8])),
            vx.mul_add(m[1], vy.mul_add(m[5], vz * m[9])),
            vx.mul_add(m[2], vy.mul_add(m[6], vz * m[10])),
        )
    }

    /// Transforms a local `Aabb3D` into an enclosing world-space `Aabb3D` via Arvo's 18-multiply method (zero corner loop, zero trigonometry).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Affine model transformation matrix.
    /// - `Aabb3D` - Local-space bounding box.
    ///
    /// # Returns
    ///
    /// - `Aabb3D` - Tight world-space enclosing AABB.
    #[inline(always)]
    #[must_use]
    pub fn transform_aabb(&self, local: Aabb3D) -> Aabb3D {
        let m: [f32; 16] = self.get_m();
        let lmin: Vec3 = local.get_min();
        let lmax: Vec3 = local.get_max();
        let lx0: f32 = lmin.get_x();
        let ly0: f32 = lmin.get_y();
        let lz0: f32 = lmin.get_z();
        let lx1: f32 = lmax.get_x();
        let ly1: f32 = lmax.get_y();
        let lz1: f32 = lmax.get_z();
        let ax0: f32 = m[0] * lx0;
        let ax1: f32 = m[0] * lx1;
        let ay0: f32 = m[4] * ly0;
        let ay1: f32 = m[4] * ly1;
        let az0: f32 = m[8] * lz0;
        let az1: f32 = m[8] * lz1;
        let out_min_x: f32 = m[12] + ax0.min(ax1) + ay0.min(ay1) + az0.min(az1);
        let out_max_x: f32 = m[12] + ax0.max(ax1) + ay0.max(ay1) + az0.max(az1);
        let bx0: f32 = m[1] * lx0;
        let bx1: f32 = m[1] * lx1;
        let by0: f32 = m[5] * ly0;
        let by1: f32 = m[5] * ly1;
        let bz0: f32 = m[9] * lz0;
        let bz1: f32 = m[9] * lz1;
        let out_min_y: f32 = m[13] + bx0.min(bx1) + by0.min(by1) + bz0.min(bz1);
        let out_max_y: f32 = m[13] + bx0.max(bx1) + by0.max(by1) + bz0.max(bz1);
        let cx0: f32 = m[2] * lx0;
        let cx1: f32 = m[2] * lx1;
        let cy0: f32 = m[6] * ly0;
        let cy1: f32 = m[6] * ly1;
        let cz0: f32 = m[10] * lz0;
        let cz1: f32 = m[10] * lz1;
        let out_min_z: f32 = m[14] + cx0.min(cx1) + cy0.min(cy1) + cz0.min(cz1);
        let out_max_z: f32 = m[14] + cx0.max(cx1) + cy0.max(cy1) + cz0.max(cz1);
        Aabb3D::new(
            Vec3::new(out_min_x, out_min_y, out_min_z),
            Vec3::new(out_max_x, out_max_y, out_max_z),
        )
    }

    /// Computes the exact analytical inverse of a TRS Euler matrix (`S^-1 * R^T * T^-1`) for object-space raytracing.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World translation.
    /// - `f32` - Y-axis yaw rotation in radians.
    /// - `f32` - X-axis pitch rotation in radians.
    /// - `f32` - Z-axis roll rotation in radians.
    /// - `Vec3` - Non-uniform scale.
    ///
    /// # Returns
    ///
    /// - `Self` - Exact inverse model matrix mapping world space back to local object space.
    #[must_use]
    pub fn inverse_trs_euler(
        position: Vec3,
        yaw_rad: f32,
        pitch_rad: f32,
        roll_rad: f32,
        scale: Vec3,
    ) -> Self {
        let isx: f32 = if scale.get_x().abs() > 1e-6 {
            1.0 / scale.get_x()
        } else {
            1.0
        };
        let isy: f32 = if scale.get_y().abs() > 1e-6 {
            1.0 / scale.get_y()
        } else {
            1.0
        };
        let isz: f32 = if scale.get_z().abs() > 1e-6 {
            1.0 / scale.get_z()
        } else {
            1.0
        };
        let (r00, r10, r20, r01, r11, r21, r02, r12, r22): (
            f32,
            f32,
            f32,
            f32,
            f32,
            f32,
            f32,
            f32,
            f32,
        ) = if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
            let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
            (cy, 0.0, -sy, 0.0, 1.0, 0.0, sy, 0.0, cy)
        } else {
            let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
            let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
            let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
            (
                cy * cr + sy * sp * sr,
                cp * sr,
                -sy * cr + cy * sp * sr,
                -cy * sr + sy * sp * cr,
                cp * cr,
                sy * sr + cy * sp * cr,
                sy * cp,
                -sp,
                cy * cp,
            )
        };
        let m00: f32 = r00 * isx;
        let m01: f32 = r10 * isx;
        let m02: f32 = r20 * isx;
        let m10: f32 = r01 * isy;
        let m11: f32 = r11 * isy;
        let m12: f32 = r21 * isy;
        let m20: f32 = r02 * isz;
        let m21: f32 = r12 * isz;
        let m22: f32 = r22 * isz;
        let px: f32 = position.get_x();
        let py: f32 = position.get_y();
        let pz: f32 = position.get_z();
        let tx: f32 = -(m00 * px + m01 * py + m02 * pz);
        let ty: f32 = -(m10 * px + m11 * py + m12 * pz);
        let tz: f32 = -(m20 * px + m21 * py + m22 * pz);
        Self {
            m: [
                m00, m10, m20, 0.0, m01, m11, m21, 0.0, m02, m12, m22, 0.0, tx, ty, tz, 1.0,
            ],
        }
    }

    /// Computes the inverse-transpose 3x3 normal transformation basis `[col_x, col_y, col_z]` (`R * S^-1`) once per object.
    ///
    /// # Arguments
    ///
    /// - `f32` - Y-axis yaw rotation in radians.
    /// - `f32` - X-axis pitch rotation in radians.
    /// - `f32` - Z-axis roll rotation in radians.
    /// - `Vec3` - Non-uniform scale.
    ///
    /// # Returns
    ///
    /// - `[Vec3; 3]` - Three column vectors transforming local normals into world space.
    #[must_use]
    pub fn normal_basis_from_euler_scale(
        yaw_rad: f32,
        pitch_rad: f32,
        roll_rad: f32,
        scale: Vec3,
    ) -> [Vec3; 3] {
        let isx: f32 = if scale.get_x().abs() > 1e-6 {
            1.0 / scale.get_x()
        } else {
            1.0
        };
        let isy: f32 = if scale.get_y().abs() > 1e-6 {
            1.0 / scale.get_y()
        } else {
            1.0
        };
        let isz: f32 = if scale.get_z().abs() > 1e-6 {
            1.0 / scale.get_z()
        } else {
            1.0
        };
        if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
            let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
            return [
                Vec3::new(cy * isx, 0.0, -sy * isx),
                Vec3::new(0.0, isy, 0.0),
                Vec3::new(sy * isz, 0.0, cy * isz),
            ];
        }
        let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
        let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
        let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
        [
            Vec3::new(
                (cy * cr + sy * sp * sr) * isx,
                (cp * sr) * isx,
                (-sy * cr + cy * sp * sr) * isx,
            ),
            Vec3::new(
                (-cy * sr + sy * sp * cr) * isy,
                (cp * cr) * isy,
                (sy * sr + cy * sp * cr) * isy,
            ),
            Vec3::new((sy * cp) * isz, (-sp) * isz, (cy * cp) * isz),
        ]
    }

    /// Transforms a local surface normal using a precomputed 3x3 `normal_basis` without trigonometry.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Local-space normal vector.
    /// - `[Vec3; 3]` - Precomputed inverse-transpose 3x3 normal basis `[col_x, col_y, col_z]`.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Normalized world-space surface normal.
    #[inline(always)]
    #[must_use]
    pub fn transform_normal_with_basis(n: Vec3, basis: [Vec3; 3]) -> Vec3 {
        let nx: f32 = n.get_x();
        let ny: f32 = n.get_y();
        let nz: f32 = n.get_z();
        Vec3::new(
            nx.mul_add(
                basis[0].get_x(),
                ny.mul_add(basis[1].get_x(), nz * basis[2].get_x()),
            ),
            nx.mul_add(
                basis[0].get_y(),
                ny.mul_add(basis[1].get_y(), nz * basis[2].get_y()),
            ),
            nx.mul_add(
                basis[0].get_z(),
                ny.mul_add(basis[1].get_z(), nz * basis[2].get_z()),
            ),
        )
        .normalize()
    }
}

/// Bounding-box union, centroid, surface area, and ray-slab intersection for `Aabb3D`.
impl Aabb3D {
    /// Creates an inverted empty AABB ready to accumulate points via `expand_point`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty AABB.
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            min: Vec3::splat(f32::INFINITY),
            max: Vec3::splat(f32::NEG_INFINITY),
        }
    }

    /// Expands this bounding box to include `point`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable AABB.
    /// - `Vec3` - Point to enclose.
    pub fn expand_point(&mut self, point: Vec3) {
        let mn: Vec3 = self.get_min().min(point);
        let mx: Vec3 = self.get_max().max(point);
        self.set_min(mn);
        self.set_max(mx);
    }

    /// Expands this bounding box to include `other`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable AABB.
    /// - `Self` - Other bounding box.
    pub fn expand_box(&mut self, other: Self) {
        let mn: Vec3 = self.get_min().min(other.get_min());
        let mx: Vec3 = self.get_max().max(other.get_max());
        self.set_min(mn);
        self.set_max(mx);
    }

    /// Returns the geometric center of the AABB.
    ///
    /// # Arguments
    ///
    /// - `&Self` - AABB reference.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Box centroid.
    #[must_use]
    pub fn center(&self) -> Vec3 {
        self.get_min().add(self.get_max()).scale(0.5)
    }

    /// Computes bounding-sphere radius enclosing this box.
    ///
    /// # Arguments
    ///
    /// - `&Self` - AABB reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Enclosing radius.
    #[must_use]
    pub fn radius(&self) -> f32 {
        self.get_max().sub(self.get_min()).length() * 0.5
    }

    /// Computes half surface area (`dx*dy + dy*dz + dz*dx`) for Surface Area Heuristic (SAH) BVH splits.
    ///
    /// # Arguments
    ///
    /// - `&Self` - AABB reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Non-negative half surface area.
    #[must_use]
    pub fn surface_area(&self) -> f32 {
        let d: Vec3 = self.get_max().sub(self.get_min());
        let dx: f32 = d.get_x().max(0.0);
        let dy: f32 = d.get_y().max(0.0);
        let dz: f32 = d.get_z().max(0.0);
        dx * dy + dy * dz + dz * dx
    }

    /// Branchless slab Ray-AABB intersection returning entry distance `tmin` or `f32::INFINITY` on miss.
    ///
    /// # Arguments
    ///
    /// - `&Self` - AABB reference.
    /// - `Vec3` - Ray origin.
    /// - `Vec3` - Precomputed safe reciprocal ray direction.
    /// - `f32` - Minimum valid distance.
    /// - `f32` - Maximum valid distance.
    ///
    /// # Returns
    ///
    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` if missed.
    #[must_use]
    pub fn intersect_ray_near(&self, origin: Vec3, inv_dir: Vec3, t_min: f32, t_max: f32) -> f32 {
        let mn: Vec3 = self.get_min();
        let mx: Vec3 = self.get_max();
        let tx1: f32 = (mn.get_x() - origin.get_x()) * inv_dir.get_x();
        let tx2: f32 = (mx.get_x() - origin.get_x()) * inv_dir.get_x();
        let mut tmin: f32 = t_min.max(tx1.min(tx2));
        let mut tmax: f32 = t_max.min(tx1.max(tx2));
        let ty1: f32 = (mn.get_y() - origin.get_y()) * inv_dir.get_y();
        let ty2: f32 = (mx.get_y() - origin.get_y()) * inv_dir.get_y();
        tmin = tmin.max(ty1.min(ty2));
        tmax = tmax.min(ty1.max(ty2));
        let tz1: f32 = (mn.get_z() - origin.get_z()) * inv_dir.get_z();
        let tz2: f32 = (mx.get_z() - origin.get_z()) * inv_dir.get_z();
        tmin = tmin.max(tz1.min(tz2));
        tmax = tmax.min(tz1.max(tz2));
        if tmax >= tmin && tmax >= 0.0 {
            tmin
        } else {
            f32::INFINITY
        }
    }

    /// Branchless slab Ray-AABB intersection returning `true` when `ray` hits within `[t_min, t_max]`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - AABB reference.
    /// - `&Ray3D` - Ray with precomputed inverse direction.
    /// - `f32` - Minimum valid distance.
    /// - `f32` - Maximum valid distance.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the ray intersects this box.
    #[must_use]
    pub fn intersects_ray(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
        self.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), t_min, t_max)
            .is_finite()
    }
}

/// Ray construction with safe reciprocal components for `Ray3D`.
impl Ray3D {
    /// Safe reciprocal scalar preventing division by zero in slab ray-box tests.
    ///
    /// # Arguments
    ///
    /// - `f32` - Component scalar.
    ///
    /// # Returns
    ///
    /// - `f32` - Clamped reciprocal value.
    #[must_use]
    fn safe_inv(v: f32) -> f32 {
        if v.abs() < 1e-7 {
            if v < 0.0 { -1e7 } else { 1e7 }
        } else {
            1.0 / v
        }
    }

    /// Computes safe reciprocal vector for an already-normalized ray direction.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Unit ray direction.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Reciprocal direction safe for slab ray-AABB intersection.
    #[must_use]
    pub fn safe_inv_vec(dir: Vec3) -> Vec3 {
        Vec3::new(
            Self::safe_inv(dir.get_x()),
            Self::safe_inv(dir.get_y()),
            Self::safe_inv(dir.get_z()),
        )
    }

    /// Constructs a normalized `Ray3D` with safe reciprocal direction components.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Ray origin.
    /// - `Vec3` - Ray direction (normalized internally).
    ///
    /// # Returns
    ///
    /// - `Self` - Ready BVH ray.
    #[must_use]
    pub fn new(origin: Vec3, direction: Vec3) -> Self {
        let dir: Vec3 = direction.normalize();
        Self {
            origin,
            direction: dir,
            inv_direction: Vec3::new(
                Self::safe_inv(dir.get_x()),
                Self::safe_inv(dir.get_y()),
                Self::safe_inv(dir.get_z()),
            ),
        }
    }
}

/// Gribb-Hartmann 6-plane frustum extraction and AABB visibility testing for `Frustum3D`.
impl Frustum3D {
    /// Normalizes a 4-component plane equation `(a, b, c, d)`.
    ///
    /// # Arguments
    ///
    /// - `[f32; 4]` - Raw plane coefficients.
    ///
    /// # Returns
    ///
    /// - `[f32; 4]` - Unit-normal plane coefficients.
    #[must_use]
    fn normalize_plane(p: [f32; 4]) -> [f32; 4] {
        let len: f32 = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
        [p[0] / len, p[1] / len, p[2] / len, p[3] / len]
    }

    /// Extracts the 6 normalized view-frustum planes from a column-major view-projection matrix.
    ///
    /// # Arguments
    ///
    /// - `&Mat4` - Combined `projection * view` matrix.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized 6-plane frustum.
    #[must_use]
    pub fn from_view_proj(vp: &Mat4) -> Self {
        let m: [f32; 16] = vp.get_m();
        let r0: [f32; 4] = [m[0], m[4], m[8], m[12]];
        let r1: [f32; 4] = [m[1], m[5], m[9], m[13]];
        let r2: [f32; 4] = [m[2], m[6], m[10], m[14]];
        let r3: [f32; 4] = [m[3], m[7], m[11], m[15]];
        Self {
            planes: [
                Self::normalize_plane([r3[0] + r0[0], r3[1] + r0[1], r3[2] + r0[2], r3[3] + r0[3]]),
                Self::normalize_plane([r3[0] - r0[0], r3[1] - r0[1], r3[2] - r0[2], r3[3] - r0[3]]),
                Self::normalize_plane([r3[0] + r1[0], r3[1] + r1[1], r3[2] + r1[2], r3[3] + r1[3]]),
                Self::normalize_plane([r3[0] - r1[0], r3[1] - r1[1], r3[2] - r1[2], r3[3] - r1[3]]),
                Self::normalize_plane([r3[0] + r2[0], r3[1] + r2[1], r3[2] + r2[2], r3[3] + r2[3]]),
                Self::normalize_plane([r3[0] - r2[0], r3[1] - r2[1], r3[2] - r2[2], r3[3] - r2[3]]),
            ],
        }
    }

    /// Returns `true` when `aabb` is at least partially inside the view frustum.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Frustum reference.
    /// - `&Aabb3D` - World-space AABB to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if potentially visible, `false` if completely culled.
    #[must_use]
    pub fn intersects_aabb(&self, aabb: &Aabb3D) -> bool {
        let mn: Vec3 = aabb.get_min();
        let mx: Vec3 = aabb.get_max();
        for p in self.get_planes().iter() {
            let px: f32 = if p[0] >= 0.0 { mx.get_x() } else { mn.get_x() };
            let py: f32 = if p[1] >= 0.0 { mx.get_y() } else { mn.get_y() };
            let pz: f32 = if p[2] >= 0.0 { mx.get_z() } else { mn.get_z() };
            if p[0] * px + p[1] * py + p[2] * pz + p[3] < 0.0 {
                return false;
            }
        }
        true
    }
}

/// Default 3D camera framing an open-world street boulevard.
impl Default for Camera3D {
    /// Creates a default street-level perspective camera.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `Camera3D`.
    fn default() -> Self {
        Self {
            position: Vec3::new(0.0, 9.5, 28.0),
            yaw: -FRAC_PI_2,
            pitch: -0.22,
            fov_deg: 60.0,
            near: 0.3,
            far: 450.0,
        }
    }
}

/// Orientation, movement, and view-projection helpers for `Camera3D`.
impl Camera3D {
    /// Returns the unit forward look vector derived from `(yaw, pitch)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Camera reference.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Forward unit vector.
    #[must_use]
    pub fn forward(&self) -> Vec3 {
        let yaw: f32 = self.get_yaw();
        let pitch: f32 = self.get_pitch();
        let cp: f32 = pitch.cos();
        Vec3::new(yaw.cos() * cp, pitch.sin(), yaw.sin() * cp).normalize()
    }

    /// Returns the unit right vector orthogonal to `forward()` and world up.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Camera reference.
    ///
    /// # Returns
    ///
    /// - `Vec3` - Right unit vector.
    #[must_use]
    pub fn right(&self) -> Vec3 {
        self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize()
    }

    /// Converts a physical camera focal length and full-frame sensor height in millimeters to vertical FOV degrees.
    ///
    /// # Arguments
    ///
    /// - `f32` - Lens focal length in millimeters (e.g., `24.0`, `35.0`, `50.0`, `85.0`).
    /// - `f32` - Camera sensor height in millimeters (`24.0` for 35mm full-frame).
    ///
    /// # Returns
    ///
    /// - `f32` - Vertical field of view in degrees clamped to `[12.0, 120.0]`.
    #[must_use]
    pub fn focal_length_to_fov_deg(focal_length_mm: f32, sensor_height_mm: f32) -> f32 {
        let f_mm: f32 = focal_length_mm.max(8.0);
        let s_mm: f32 = sensor_height_mm.max(4.0);
        (2.0 * (s_mm / (2.0 * f_mm)).atan().to_degrees()).clamp(12.0, 120.0)
    }

    /// Constructs a physically based 35mm full-frame `Camera3D` using lens focal length in millimeters.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - World-space eye position.
    /// - `f32` - Horizontal yaw angle in radians.
    /// - `f32` - Vertical pitch angle in radians.
    /// - `f32` - Lens focal length in millimeters.
    ///
    /// # Returns
    ///
    /// - `Self` - Physically configured perspective camera.
    #[must_use]
    pub fn from_lens(position: Vec3, yaw: f32, pitch: f32, focal_length_mm: f32) -> Self {
        Self {
            position,
            yaw,
            pitch: pitch.clamp(-1.4, 1.4),
            fov_deg: Self::focal_length_to_fov_deg(focal_length_mm, 24.0),
            near: 0.25,
            far: 480.0,
        }
    }

    /// Computes physical exposure value `EV100` from lens aperture (f-stop), shutter speed (seconds), and ISO.
    ///
    /// # Arguments
    ///
    /// - `f32` - Aperture f-number (e.g., `2.8`, `4.0`, `8.0`).
    /// - `f32` - Shutter exposure time in seconds (e.g., `1.0 / 125.0`).
    /// - `f32` - Sensor ISO sensitivity (e.g., `100.0`).
    ///
    /// # Returns
    ///
    /// - `f32` - Physical exposure value `EV100`.
    #[must_use]
    pub fn ev100(aperture_fstop: f32, shutter_seconds: f32, iso: f32) -> f32 {
        let n: f32 = aperture_fstop.max(0.7);
        let t: f32 = shutter_seconds.max(1e-5);
        let s: f32 = iso.max(25.0);
        ((n * n) / t * (100.0 / s)).log2()
    }

    /// Converts an `EV100` exposure value into a linear HDR scene exposure multiplier.
    ///
    /// # Arguments
    ///
    /// - `f32` - Physical exposure value `EV100`.
    ///
    /// # Returns
    ///
    /// - `f32` - Linear exposure multiplier clamped to `[0.05, 8.0]`.
    #[must_use]
    pub fn exposure_scale_from_ev100(ev100: f32) -> f32 {
        let max_lum: f32 = 1.2 * 2.0_f32.powf(ev100);
        (1.0 / max_lum.max(1e-4)).clamp(0.05, 8.0)
    }

    /// Orients this camera's yaw and pitch to aim directly at `target`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable camera reference.
    /// - `Vec3` - World-space look target.
    pub fn look_at(&mut self, target: Vec3) {
        let dir: Vec3 = target.sub(self.get_position()).normalize();
        self.set_yaw(dir.get_z().atan2(dir.get_x()));
        self.set_pitch(dir.get_y().clamp(-0.98, 0.98).asin());
    }

    /// Linearly interpolates camera position, shortest-arc yaw, pitch, and lens parameters between `self` and `other`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Previous fixed-step 3D camera state.
    /// - `Self` - Current fixed-step 3D camera state.
    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Interpolated 3D camera.
    #[must_use]
    pub fn lerp(self, other: Self, alpha: f32) -> Self {
        let k: f32 = alpha.clamp(0.0, 1.0);
        let diff: f32 = other.get_yaw() - self.get_yaw();
        let raw_yaw_delta: f32 = diff - (diff / TAU).floor() * TAU;
        let shortest_yaw: f32 = if raw_yaw_delta > PI {
            raw_yaw_delta - TAU
        } else {
            raw_yaw_delta
        };
        Self {
            position: self.get_position().lerp(other.get_position(), k),
            yaw: self.get_yaw() + shortest_yaw * k,
            pitch: (self.get_pitch() + (other.get_pitch() - self.get_pitch()) * k).clamp(-1.4, 1.4),
            fov_deg: self.get_fov_deg() + (other.get_fov_deg() - self.get_fov_deg()) * k,
            near: self.get_near() + (other.get_near() - self.get_near()) * k,
            far: self.get_far() + (other.get_far() - self.get_far()) * k,
        }
    }

    /// Computes the combined `projection * view` matrix for viewport `aspect`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Camera reference.
    /// - `f32` - Viewport aspect ratio `width / height`.
    ///
    /// # Returns
    ///
    /// - `Mat4` - View-projection matrix.
    #[must_use]
    pub fn view_projection(&self, aspect: f32) -> Mat4 {
        let pos: Vec3 = self.get_position();
        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), Vec3::new(0.0, 1.0, 0.0));
        let proj: Mat4 = Mat4::perspective(
            self.get_fov_deg().to_radians(),
            aspect.max(0.1),
            self.get_near().max(0.05),
            self.get_far().max(10.0),
        );
        proj.mul(view)
    }
}