oxideav-mesh3d 0.0.3

Pure-Rust 3D scene + mesh typed model โ€” Decoder/Encoder traits for STL/OBJ/glTF/FBX/USD format crates
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
//! Scene-graph root, nodes, transforms, ID newtypes, and coordinate
//! metadata.
//!
//! The container is [`Scene3D`]. Every collection it owns
//! ([`Node`], [`Mesh`](crate::Mesh), [`Material`](crate::Material),
//! ...) is addressed by an `IdT(u32)` newtype that indexes into the
//! corresponding `Vec`. This keeps the model arena-friendly โ€” clones
//! are cheap, identity is comparable, and serde round-tripping works
//! without back-references โ€” while still letting decoders bulk-load
//! every mesh first and then point nodes at them.
//!
//! Coordinate convention defaults to **glTF 2.0**: right-handed,
//! Y-up, -Z forward, metres. Format crates that consume Z-up content
//! (STL, OBJ Wavefront) set [`Scene3D::up_axis`] to [`Axis::PosZ`]
//! and leave geometry untouched โ€” the orientation metadata is
//! authoritative, no implicit rotation is applied.

use std::collections::HashMap;

use crate::{
    animation::Animation,
    audio::{AudioEmitter, AudioEmitterId, AudioSource, AudioSourceId},
    camera::Camera,
    light::Light,
    material::Material,
    mesh::Mesh,
    skin::Skeleton,
    skin::Skin,
    texture::Texture,
};

macro_rules! id_newtype {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(pub u32);
    };
}

id_newtype!(
    /// Index into [`Scene3D::nodes`].
    NodeId
);
id_newtype!(
    /// Index into [`Scene3D::meshes`].
    MeshId
);
id_newtype!(
    /// Index into [`Scene3D::materials`].
    MaterialId
);
id_newtype!(
    /// Index into [`Scene3D::textures`].
    TextureId
);
id_newtype!(
    /// Index into [`Scene3D::skeletons`].
    SkeletonId
);
id_newtype!(
    /// Index into [`Scene3D::skins`].
    SkinId
);
id_newtype!(
    /// Index into [`Scene3D::cameras`].
    CameraId
);
id_newtype!(
    /// Index into [`Scene3D::lights`].
    LightId
);

/// Axis-aligned bounding box over a set of 3D points.
///
/// `min` is the componentwise minimum corner, `max` the componentwise
/// maximum corner. Both are inclusive; for an empty point set this
/// type returns [`None`] from its constructors rather than carrying a
/// degenerate `[inf; 3]` / `[-inf; 3]` sentinel.
///
/// Use [`BoundingBox::from_points`] to build one from an iterator of
/// `[f32; 3]`, [`BoundingBox::union`] to merge two boxes, and
/// [`BoundingBox::transform`] to rotate / translate / scale the box
/// by a 4x4 row-major-column-vector matrix (the eight corners are
/// transformed and a new AABB is fitted around them โ€” the rotated
/// box's tight bound).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoundingBox {
    pub min: [f32; 3],
    pub max: [f32; 3],
}

impl BoundingBox {
    /// Bounding box of exactly one point. Both corners coincide.
    pub fn from_point(p: [f32; 3]) -> Self {
        Self { min: p, max: p }
    }

    /// Bounding box over a stream of points. Returns `None` if the
    /// iterator yields zero finite points (NaN coordinates are
    /// skipped on a per-component basis).
    pub fn from_points<I: IntoIterator<Item = [f32; 3]>>(points: I) -> Option<Self> {
        let mut acc: Option<Self> = None;
        for p in points {
            if p[0].is_nan() || p[1].is_nan() || p[2].is_nan() {
                continue;
            }
            acc = Some(match acc {
                None => Self::from_point(p),
                Some(b) => b.expand(p),
            });
        }
        acc
    }

    /// Grow the box to include `p`. Returns a new box; the input is
    /// left unchanged. NaN components are kept as-is on the
    /// existing box (they are not propagated by [`from_points`] either).
    pub fn expand(self, p: [f32; 3]) -> Self {
        Self {
            min: [
                self.min[0].min(p[0]),
                self.min[1].min(p[1]),
                self.min[2].min(p[2]),
            ],
            max: [
                self.max[0].max(p[0]),
                self.max[1].max(p[1]),
                self.max[2].max(p[2]),
            ],
        }
    }

    /// Componentwise union of two boxes โ€” the smallest AABB
    /// containing both.
    pub fn union(self, other: Self) -> Self {
        Self {
            min: [
                self.min[0].min(other.min[0]),
                self.min[1].min(other.min[1]),
                self.min[2].min(other.min[2]),
            ],
            max: [
                self.max[0].max(other.max[0]),
                self.max[1].max(other.max[1]),
                self.max[2].max(other.max[2]),
            ],
        }
    }

    /// Centre of the box (average of `min` and `max`).
    pub fn center(self) -> [f32; 3] {
        [
            0.5 * (self.min[0] + self.max[0]),
            0.5 * (self.min[1] + self.max[1]),
            0.5 * (self.min[2] + self.max[2]),
        ]
    }

    /// Componentwise size of the box (`max - min`).
    pub fn size(self) -> [f32; 3] {
        [
            self.max[0] - self.min[0],
            self.max[1] - self.min[1],
            self.max[2] - self.min[2],
        ]
    }

    /// `true` if every component of `min` is less than or equal to the
    /// corresponding component of `max` (i.e. the box is non-empty
    /// and well-formed).
    pub fn is_valid(self) -> bool {
        self.min[0] <= self.max[0] && self.min[1] <= self.max[1] && self.min[2] <= self.max[2]
    }

    /// Tight AABB around the box transformed by a row-major
    /// column-vector 4x4 matrix (`out = M * v`, same convention as
    /// [`Transform::Matrix`]).
    ///
    /// Returns the AABB of the eight transformed corners. For
    /// non-affine matrices (perspective `w != 1`) the result may not
    /// be physically meaningful โ€” this method is intended for the
    /// scene-graph TRS / matrix chain composing every ancestor node's
    /// local transform.
    pub fn transform(self, m: [[f32; 4]; 4]) -> Self {
        let corners = [
            [self.min[0], self.min[1], self.min[2]],
            [self.max[0], self.min[1], self.min[2]],
            [self.min[0], self.max[1], self.min[2]],
            [self.max[0], self.max[1], self.min[2]],
            [self.min[0], self.min[1], self.max[2]],
            [self.max[0], self.min[1], self.max[2]],
            [self.min[0], self.max[1], self.max[2]],
            [self.max[0], self.max[1], self.max[2]],
        ];
        let xf = corners.map(|c| {
            [
                m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2] + m[0][3],
                m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2] + m[1][3],
                m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2] + m[2][3],
            ]
        });
        Self::from_points(xf).expect("eight corners always yield a finite AABB")
    }

    /// Slab-method ray-AABB intersection โ€” returns the entry / exit
    /// parametric distances along the ray clamped to `[0, t_max]`, or
    /// `None` if the ray misses.
    ///
    /// `t_enter == 0.0` indicates the ray's origin lies inside the
    /// box; `t_exit` is the parameter at which the ray leaves through
    /// the far face. Both values are along the (not-necessarily-unit)
    /// `ray.direction`, so the actual world-space point at the
    /// intersection is `ray.point_at(t)`.
    ///
    /// Delegates to [`crate::ray::intersect_aabb`]; see its docs for
    /// the axis-parallel-ray + NaN / Inf handling.
    pub fn intersect_ray(self, ray: crate::ray::Ray, t_max: f32) -> Option<(f32, f32)> {
        crate::ray::intersect_aabb(ray, self.min, self.max, t_max)
    }
}

/// Coordinate-system principal axis. Stored on [`Scene3D`] so a
/// renderer can apply (or skip) a global rotation when the file
/// convention disagrees with its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Axis {
    PosX,
    NegX,
    PosY,
    NegY,
    PosZ,
    NegZ,
}

/// Linear unit a single coordinate-space-1.0 represents in the file.
/// glTF defaults to metres; CAD/STL files often ship in millimetres
/// or inches. Renderers that mix scenes from different unit systems
/// scale by the ratio of [`Unit::to_metres`] values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unit {
    Metres,
    Centimetres,
    Millimetres,
    Inches,
    Feet,
    Yards,
}

impl Unit {
    /// Multiplier from this unit to metres, e.g. `Inches.to_metres() == 0.0254`.
    pub fn to_metres(self) -> f32 {
        match self {
            Self::Metres => 1.0,
            Self::Centimetres => 0.01,
            Self::Millimetres => 0.001,
            Self::Inches => 0.0254,
            Self::Feet => 0.3048,
            Self::Yards => 0.9144,
        }
    }
}

/// Per-node local-to-parent transform. Decoders can store the raw
/// matrix as-is or decompose into translation/rotation/scale; the
/// [`Transform::to_matrix`] / [`Transform::from_matrix`] helpers
/// convert in either direction within float tolerance.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Transform {
    /// Row-major column-vector 4x4 transform โ€” pre-multiplied
    /// (`out = M * v`). Layout matches glTF's `node.matrix` field.
    Matrix([[f32; 4]; 4]),
    /// Decomposed translation + rotation (xyzw quaternion) + scale.
    /// glTF's TRS form; preferred for animation since each channel is
    /// independent.
    Trs {
        translation: [f32; 3],
        rotation: [f32; 4],
        scale: [f32; 3],
    },
}

impl Transform {
    /// Identity TRS โ€” `(0,0,0)` translation, identity quaternion,
    /// `(1,1,1)` scale.
    pub fn identity() -> Self {
        Self::Trs {
            translation: [0.0; 3],
            rotation: [0.0, 0.0, 0.0, 1.0],
            scale: [1.0, 1.0, 1.0],
        }
    }

    /// Compose this transform into a single 4x4 matrix.
    ///
    /// For `Matrix(m)` this is the identity passthrough; for
    /// `Trs { t, r, s }` the build order is `T * R * S`.
    pub fn to_matrix(&self) -> [[f32; 4]; 4] {
        match *self {
            Self::Matrix(m) => m,
            Self::Trs {
                translation,
                rotation,
                scale,
            } => trs_to_matrix(translation, rotation, scale),
        }
    }

    /// Best-effort decomposition of a 4x4 affine transform into TRS.
    ///
    /// Assumes the input is `T * R * S` with no shear and no negative
    /// scale; under that assumption the recovery is exact within
    /// float epsilon. For matrices with shear the output is the
    /// closest pure TRS (scales are column lengths, rotation is the
    /// orthonormalised basis).
    pub fn from_matrix(m: [[f32; 4]; 4]) -> Self {
        let translation = [m[0][3], m[1][3], m[2][3]];
        let cx = [m[0][0], m[1][0], m[2][0]];
        let cy = [m[0][1], m[1][1], m[2][1]];
        let cz = [m[0][2], m[1][2], m[2][2]];
        let sx = vec3_len(cx);
        let sy = vec3_len(cy);
        let sz = vec3_len(cz);
        // Avoid div-by-zero if a column was zero โ€” fall back to a sentinel
        // axis; this lets the from_matrix(to_matrix(t)) round-trip remain
        // total even for pathological inputs.
        let inv_sx = if sx > f32::EPSILON { 1.0 / sx } else { 1.0 };
        let inv_sy = if sy > f32::EPSILON { 1.0 / sy } else { 1.0 };
        let inv_sz = if sz > f32::EPSILON { 1.0 / sz } else { 1.0 };
        let r00 = cx[0] * inv_sx;
        let r10 = cx[1] * inv_sx;
        let r20 = cx[2] * inv_sx;
        let r01 = cy[0] * inv_sy;
        let r11 = cy[1] * inv_sy;
        let r21 = cy[2] * inv_sy;
        let r02 = cz[0] * inv_sz;
        let r12 = cz[1] * inv_sz;
        let r22 = cz[2] * inv_sz;
        let rotation = rot_matrix_to_quat([[r00, r01, r02], [r10, r11, r12], [r20, r21, r22]]);
        Self::Trs {
            translation,
            rotation,
            scale: [sx, sy, sz],
        }
    }
}

fn vec3_len(v: [f32; 3]) -> f32 {
    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}

/// Row-major column-vector 4x4 matrix multiply `a * b`.
fn mat4_mul(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
    let mut out = [[0.0f32; 4]; 4];
    for (i, row) in out.iter_mut().enumerate() {
        for (j, slot) in row.iter_mut().enumerate() {
            *slot = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j] + a[i][3] * b[3][j];
        }
    }
    out
}

/// Signed determinant of the upper-left 3x3 of a row-major
/// column-vector 4x4 matrix, returned as `f64` for accumulator-safe
/// volume scaling. The translation column does not enter the result.
fn mat3_det_of_world(m: [[f32; 4]; 4]) -> f64 {
    let a = m[0][0] as f64;
    let b = m[0][1] as f64;
    let c = m[0][2] as f64;
    let d = m[1][0] as f64;
    let e = m[1][1] as f64;
    let f = m[1][2] as f64;
    let g = m[2][0] as f64;
    let h = m[2][1] as f64;
    let i = m[2][2] as f64;
    a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
}

fn trs_to_matrix(t: [f32; 3], r: [f32; 4], s: [f32; 3]) -> [[f32; 4]; 4] {
    // Quaternion (x, y, z, w) โ†’ 3x3 rotation matrix (Shoemake).
    let (x, y, z, w) = (r[0], r[1], r[2], r[3]);
    let xx = x * x;
    let yy = y * y;
    let zz = z * z;
    let xy = x * y;
    let xz = x * z;
    let yz = y * z;
    let wx = w * x;
    let wy = w * y;
    let wz = w * z;
    let r00 = 1.0 - 2.0 * (yy + zz);
    let r01 = 2.0 * (xy - wz);
    let r02 = 2.0 * (xz + wy);
    let r10 = 2.0 * (xy + wz);
    let r11 = 1.0 - 2.0 * (xx + zz);
    let r12 = 2.0 * (yz - wx);
    let r20 = 2.0 * (xz - wy);
    let r21 = 2.0 * (yz + wx);
    let r22 = 1.0 - 2.0 * (xx + yy);
    [
        [r00 * s[0], r01 * s[1], r02 * s[2], t[0]],
        [r10 * s[0], r11 * s[1], r12 * s[2], t[1]],
        [r20 * s[0], r21 * s[1], r22 * s[2], t[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]
}

fn rot_matrix_to_quat(m: [[f32; 3]; 3]) -> [f32; 4] {
    // Shepperd's branchless variant โ€” picks the column with the
    // largest diagonal to avoid catastrophic cancellation near
    // 180-degree rotations. Returns (x, y, z, w).
    let trace = m[0][0] + m[1][1] + m[2][2];
    if trace > 0.0 {
        let s = (trace + 1.0).sqrt() * 2.0;
        let w = 0.25 * s;
        let x = (m[2][1] - m[1][2]) / s;
        let y = (m[0][2] - m[2][0]) / s;
        let z = (m[1][0] - m[0][1]) / s;
        [x, y, z, w]
    } else if m[0][0] > m[1][1] && m[0][0] > m[2][2] {
        let s = (1.0 + m[0][0] - m[1][1] - m[2][2]).sqrt() * 2.0;
        let w = (m[2][1] - m[1][2]) / s;
        let x = 0.25 * s;
        let y = (m[0][1] + m[1][0]) / s;
        let z = (m[0][2] + m[2][0]) / s;
        [x, y, z, w]
    } else if m[1][1] > m[2][2] {
        let s = (1.0 + m[1][1] - m[0][0] - m[2][2]).sqrt() * 2.0;
        let w = (m[0][2] - m[2][0]) / s;
        let x = (m[0][1] + m[1][0]) / s;
        let y = 0.25 * s;
        let z = (m[1][2] + m[2][1]) / s;
        [x, y, z, w]
    } else {
        let s = (1.0 + m[2][2] - m[0][0] - m[1][1]).sqrt() * 2.0;
        let w = (m[1][0] - m[0][1]) / s;
        let x = (m[0][2] + m[2][0]) / s;
        let y = (m[1][2] + m[2][1]) / s;
        let z = 0.25 * s;
        [x, y, z, w]
    }
}

/// A single scene-graph node.
///
/// Nodes form a forest rooted at [`Scene3D::roots`]. Each node has at
/// most one parent (enforced by walking children top-down only โ€” the
/// `parent` back-pointer isn't stored; decoders that need it should
/// build a side-table).
#[derive(Clone, Debug)]
pub struct Node {
    pub name: Option<String>,
    pub transform: Transform,
    pub children: Vec<NodeId>,
    pub mesh: Option<MeshId>,
    pub camera: Option<CameraId>,
    pub light: Option<LightId>,
    pub skin: Option<SkinId>,
    /// Optional audio emitter attached to this node. The emitter's
    /// position + orientation come from this node's world transform
    /// when [`AudioEmitter::spatial`](crate::AudioEmitter::spatial)
    /// is `Some`; non-spatial emitters ignore the transform and play
    /// globally.
    pub audio_emitter: Option<AudioEmitterId>,
    pub extras: HashMap<String, serde_json::Value>,
}

impl Node {
    /// Construct an empty node with identity transform.
    pub fn new() -> Self {
        Self {
            name: None,
            transform: Transform::identity(),
            children: Vec::new(),
            mesh: None,
            camera: None,
            light: None,
            skin: None,
            audio_emitter: None,
            extras: HashMap::new(),
        }
    }

    /// Builder-style name setter.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Builder-style transform setter.
    pub fn with_transform(mut self, transform: Transform) -> Self {
        self.transform = transform;
        self
    }

    /// Builder-style mesh attachment.
    pub fn with_mesh(mut self, mesh: MeshId) -> Self {
        self.mesh = Some(mesh);
        self
    }

    /// Builder-style audio-emitter attachment.
    pub fn with_audio_emitter(mut self, emitter: AudioEmitterId) -> Self {
        self.audio_emitter = Some(emitter);
        self
    }
}

impl Default for Node {
    fn default() -> Self {
        Self::new()
    }
}

/// Top-level container for a 3D scene.
///
/// Owns every resource referenced by the scene graph. Add resources
/// with the `add_*` helpers โ€” they push into the corresponding `Vec`
/// and return the freshly-issued ID. Roots are explicit: a node added
/// with [`Scene3D::add_node`] is not automatically a root, so that
/// child nodes added later can be re-parented without re-shuffling.
#[derive(Clone, Debug)]
pub struct Scene3D {
    pub nodes: Vec<Node>,
    pub roots: Vec<NodeId>,
    pub meshes: Vec<Mesh>,
    pub materials: Vec<Material>,
    pub textures: Vec<Texture>,
    pub skeletons: Vec<Skeleton>,
    pub skins: Vec<Skin>,
    pub animations: Vec<Animation>,
    pub cameras: Vec<Camera>,
    pub lights: Vec<Light>,
    /// Audio assets owned by the scene; addressed by [`AudioSourceId`].
    pub audio_sources: Vec<AudioSource>,
    /// In-scene audio-emitter instances; addressed by [`AudioEmitterId`].
    pub audio_emitters: Vec<AudioEmitter>,
    pub up_axis: Axis,
    pub front_axis: Axis,
    pub unit: Unit,
    pub extras: HashMap<String, serde_json::Value>,
}

impl Scene3D {
    /// Empty scene with glTF-default orientation (Y-up, -Z forward,
    /// metres) and no resources.
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            roots: Vec::new(),
            meshes: Vec::new(),
            materials: Vec::new(),
            textures: Vec::new(),
            skeletons: Vec::new(),
            skins: Vec::new(),
            animations: Vec::new(),
            cameras: Vec::new(),
            lights: Vec::new(),
            audio_sources: Vec::new(),
            audio_emitters: Vec::new(),
            up_axis: Axis::PosY,
            front_axis: Axis::NegZ,
            unit: Unit::Metres,
            extras: HashMap::new(),
        }
    }

    /// Push a node and return its id.
    pub fn add_node(&mut self, node: Node) -> NodeId {
        let id = NodeId(self.nodes.len() as u32);
        self.nodes.push(node);
        id
    }

    /// Push a mesh and return its id.
    pub fn add_mesh(&mut self, mesh: Mesh) -> MeshId {
        let id = MeshId(self.meshes.len() as u32);
        self.meshes.push(mesh);
        id
    }

    /// Push a material and return its id.
    pub fn add_material(&mut self, material: Material) -> MaterialId {
        let id = MaterialId(self.materials.len() as u32);
        self.materials.push(material);
        id
    }

    /// Push a texture and return its id.
    pub fn add_texture(&mut self, texture: Texture) -> TextureId {
        let id = TextureId(self.textures.len() as u32);
        self.textures.push(texture);
        id
    }

    /// Push a skeleton and return its id.
    pub fn add_skeleton(&mut self, skeleton: Skeleton) -> SkeletonId {
        let id = SkeletonId(self.skeletons.len() as u32);
        self.skeletons.push(skeleton);
        id
    }

    /// Push a skin and return its id.
    pub fn add_skin(&mut self, skin: Skin) -> SkinId {
        let id = SkinId(self.skins.len() as u32);
        self.skins.push(skin);
        id
    }

    /// Push an animation and return its id (animations are
    /// list-ordered, no separate id type โ€” reference by index).
    pub fn add_animation(&mut self, animation: Animation) -> usize {
        let idx = self.animations.len();
        self.animations.push(animation);
        idx
    }

    /// Push a camera and return its id.
    pub fn add_camera(&mut self, camera: Camera) -> CameraId {
        let id = CameraId(self.cameras.len() as u32);
        self.cameras.push(camera);
        id
    }

    /// Push a light and return its id.
    pub fn add_light(&mut self, light: Light) -> LightId {
        let id = LightId(self.lights.len() as u32);
        self.lights.push(light);
        id
    }

    /// Push an [`AudioSource`] and return its id.
    pub fn add_audio_source(&mut self, source: AudioSource) -> AudioSourceId {
        let id = AudioSourceId(self.audio_sources.len() as u32);
        self.audio_sources.push(source);
        id
    }

    /// Push an [`AudioEmitter`] and return its id.
    pub fn add_audio_emitter(&mut self, emitter: AudioEmitter) -> AudioEmitterId {
        let id = AudioEmitterId(self.audio_emitters.len() as u32);
        self.audio_emitters.push(emitter);
        id
    }

    /// Borrow an audio source by id, if it exists.
    pub fn audio_source(&self, id: AudioSourceId) -> Option<&AudioSource> {
        self.audio_sources.get(id.0 as usize)
    }

    /// Borrow an audio emitter by id, if it exists.
    pub fn audio_emitter(&self, id: AudioEmitterId) -> Option<&AudioEmitter> {
        self.audio_emitters.get(id.0 as usize)
    }

    /// Promote a node to a root of the scene-graph forest.
    pub fn add_root(&mut self, node: NodeId) {
        self.roots.push(node);
    }

    /// Borrow a node by id, if it exists.
    pub fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(id.0 as usize)
    }

    /// Mutably borrow a node by id, if it exists.
    pub fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
        self.nodes.get_mut(id.0 as usize)
    }

    /// Borrow a mesh by id, if it exists.
    pub fn mesh(&self, id: MeshId) -> Option<&Mesh> {
        self.meshes.get(id.0 as usize)
    }

    /// World-space 4x4 transform per scene node, indexed by `NodeId.0`.
    ///
    /// Walks every root in [`Scene3D::roots`] in order, composing each
    /// node's local [`Transform`] (via [`Transform::to_matrix`]) onto
    /// its parent's already-composed world transform. The returned
    /// vector has length `nodes.len()`; each slot holds:
    ///
    /// * `Some([[f32; 4]; 4])` โ€” the row-major column-vector world
    ///   transform of that node, i.e. the matrix that takes a position
    ///   in the node's local frame to world space (`p_world = M *
    ///   p_local`, treating `p_local` as `[x, y, z, 1]แต€`).
    /// * `None` โ€” the node is not reachable from any root in
    ///   [`Scene3D::roots`] (detached). Detached nodes are common
    ///   during incremental scene construction; the caller can detect
    ///   them without a separate reachability pass.
    ///
    /// The walk is depth-first iterative on an explicit stack, matching
    /// [`Scene3D::bounding_box`]'s traversal. Re-entry through a cycle
    /// (a node listed as its own descendant) is guarded against โ€” each
    /// node receives **exactly one** world transform, the first one
    /// encountered on the depth-first walk. Out-of-range `NodeId`
    /// entries in `roots` / `children` are silently skipped.
    ///
    /// A node referenced by two parents (shared-instance pattern) is
    /// visited only once, so `world_node_transforms()[id.0 as usize]`
    /// resolves to a single matrix โ€” the one obtained via the first
    /// parent on the DFS path. Decoders that need per-instance world
    /// transforms (mesh-instancing) should keep an explicit
    /// instance-list side-channel rather than relying on this helper.
    ///
    /// **What this does NOT include:**
    ///
    /// * Skin pose deformation โ€” the static scene-graph transform is
    ///   reported, not the skinned-pose transform at any particular
    ///   animation time. Apply animation channels separately to obtain
    ///   pose-time transforms.
    /// * Camera / projection transforms.
    /// * Up-axis or unit conversion. [`Scene3D::up_axis`] and
    ///   [`Scene3D::unit`] are metadata; the returned matrices live in
    ///   whatever coordinate system the scene stored.
    ///
    /// ## Use cases
    ///
    /// * Transform-aware aggregate metrics (multiply each primitive's
    ///   `surface_area` by `|det(scale_part)|` or its `signed_volume`
    ///   by `sign(det) * |det|` to obtain a transform-folded total โ€”
    ///   the per-component scales fall out of the upper-left 3x3 of
    ///   the world matrix).
    /// * Renderer-side world-matrix prep (one DFS pass at scene load,
    ///   then constant-time lookup per node when issuing draw calls).
    /// * Authoring-tool node inspection ("show me the world position
    ///   of `nodes[7]`" without re-walking the ancestor chain).
    ///
    /// Cost: `O(nodes.len() + total_children)`; allocates one
    /// `Vec<Option<...>>` of length `nodes.len()` plus the DFS stack.
    pub fn world_node_transforms(&self) -> Vec<Option<[[f32; 4]; 4]>> {
        let n_nodes = self.nodes.len();
        let mut out: Vec<Option<[[f32; 4]; 4]>> = vec![None; n_nodes];
        if n_nodes == 0 {
            return out;
        }
        let identity: [[f32; 4]; 4] = [
            [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],
        ];
        // Iterative depth-first walk; stack carries (node_id, ancestor_matrix).
        // Roots are pushed in order so that, after the LIFO pop order,
        // the leftmost root is visited first โ€” matching `bounding_box`'s
        // determinism contract.
        let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
            self.roots.iter().rev().map(|r| (*r, identity)).collect();
        while let Some((nid, parent)) = stack.pop() {
            let idx = nid.0 as usize;
            if idx >= n_nodes || out[idx].is_some() {
                continue;
            }
            let node = &self.nodes[idx];
            let world = mat4_mul(parent, node.transform.to_matrix());
            out[idx] = Some(world);
            // Walk children in reverse so leftmost child is popped first
            // (deterministic ordering for snapshot consumers).
            for child in node.children.iter().rev() {
                stack.push((*child, world));
            }
        }
        out
    }

    /// Axis-aligned bounding box over every mesh referenced by a node
    /// reachable from [`Scene3D::roots`], with each mesh's vertices
    /// projected through its node's full ancestor transform chain.
    ///
    /// Returns `None` when no reachable node carries a mesh, or every
    /// reachable mesh is empty.
    ///
    /// **What this does NOT include:**
    ///
    /// * Skin pose deformation โ€” the rest-pose vertices are used
    ///   verbatim. A bound mesh whose vertices are rigged to a
    ///   skeleton will report the *rest-pose* extent, not the
    ///   skinned-pose extent at any particular animation time.
    /// * Morph targets โ€” only base [`Primitive::positions`](crate::Primitive::positions)
    ///   are folded in.
    /// * Meshes referenced by `nodes` not reachable from any root โ€”
    ///   detached resources are ignored. Use [`Scene3D::meshes`] +
    ///   [`Mesh::bounding_box`](crate::Mesh::bounding_box) directly if
    ///   you need every resource regardless of scene-graph reachability.
    ///
    /// Re-entry through a cycle (a node listed as its own descendant)
    /// is guarded against โ€” each node is visited at most once.
    pub fn bounding_box(&self) -> Option<BoundingBox> {
        let n_nodes = self.nodes.len();
        let n_meshes = self.meshes.len();
        if n_nodes == 0 || n_meshes == 0 {
            return None;
        }
        let mut visited = vec![false; n_nodes];
        let identity: [[f32; 4]; 4] = [
            [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],
        ];
        let mut acc: Option<BoundingBox> = None;
        // Iterative depth-first walk; stack carries (node_id, ancestor_matrix).
        let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
            self.roots.iter().map(|r| (*r, identity)).collect();
        while let Some((nid, parent)) = stack.pop() {
            let idx = nid.0 as usize;
            if idx >= n_nodes || visited[idx] {
                continue;
            }
            visited[idx] = true;
            let node = &self.nodes[idx];
            let world = mat4_mul(parent, node.transform.to_matrix());
            if let Some(m) = node.mesh {
                if let Some(mesh) = self.meshes.get(m.0 as usize) {
                    if let Some(b) = mesh.bounding_box() {
                        let xf = b.transform(world);
                        acc = Some(match acc {
                            None => xf,
                            Some(a) => a.union(xf),
                        });
                    }
                }
            }
            // Walk children in reverse so leftmost child is popped first
            // (deterministic for the deterministic-debug-output use case).
            for child in node.children.iter().rev() {
                stack.push((*child, world));
            }
        }
        acc
    }

    /// Sum of triangles across every mesh primitive.
    ///
    /// Lists / strips / fans contribute as if tessellated:
    /// - `Triangles` โ†’ `vertex_count / 3` (or `index_count / 3`)
    /// - `TriangleStrip` / `TriangleFan` โ†’ `max(0, n - 2)` triangles
    /// - non-triangle topologies contribute 0.
    pub fn triangle_count(&self) -> usize {
        self.meshes
            .iter()
            .flat_map(|m| m.primitives.iter())
            .map(|p| p.triangle_count())
            .sum()
    }

    /// Sum of `positions.len()` across every mesh primitive.
    pub fn vertex_count(&self) -> usize {
        self.meshes
            .iter()
            .flat_map(|m| m.primitives.iter())
            .map(|p| p.positions.len())
            .sum()
    }

    /// Sum of every mesh primitive's [`Primitive::surface_area`] in the
    /// scene's local unit-squared (matching [`Scene3D::unit`]). This
    /// does *not* apply node transforms โ€” primitives instanced by
    /// multiple nodes contribute their unscaled area once per mesh,
    /// not once per node. For a transform-aware total, walk
    /// [`Scene3D::world_node_transforms`] and apply the per-node
    /// scale's determinant per primitive instance.
    pub fn surface_area(&self) -> f64 {
        self.meshes.iter().map(|m| m.surface_area()).sum()
    }

    /// Sum of every mesh primitive's
    /// [`crate::Primitive::signed_volume`] in the scene's local
    /// unit-cubed (matching [`Scene3D::unit`]). This does *not* apply
    /// node transforms โ€” primitives instanced by multiple nodes
    /// contribute their unscaled volume once per mesh, not once per
    /// node. For a transform-aware total, walk
    /// [`Scene3D::world_node_transforms`] and apply the per-node
    /// scale's signed determinant per primitive instance (a negative
    /// scale flips winding and so flips the sign of the enclosed
    /// volume).
    ///
    /// **Only physically meaningful when each contained mesh is a
    /// closed two-manifold surface.** See
    /// [`crate::Primitive::is_closed_manifold`] /
    /// [`crate::Primitive::edge_manifold_report`].
    pub fn signed_volume(&self) -> f64 {
        self.meshes.iter().map(|m| m.signed_volume()).sum()
    }

    /// Unsigned `|signed_volume()|` across the scene. Same
    /// shell-cancellation caveat as [`crate::Mesh::volume`]: this is
    /// `|ฮฃ signed|`, not `ฮฃ |signed|`. For a multi-shell scene where
    /// individual shells may differ in sign, prefer summing each mesh's
    /// [`crate::Mesh::volume`] separately.
    pub fn volume(&self) -> f64 {
        self.signed_volume().abs()
    }

    /// Transform-aware total surface area across every node-instantiated
    /// mesh in the scene, in world units squared (matching
    /// [`Scene3D::unit`]ยฒ when the scene's root has identity transform).
    ///
    /// Whereas [`Scene3D::surface_area`] sums each *mesh resource* once
    /// regardless of how many nodes carry it (the geometric-content
    /// total), `world_surface_area` walks the [`Scene3D::roots`] forest
    /// the same way [`Scene3D::bounding_box`] does, applies each
    /// reachable node's full ancestor-chain world matrix to its
    /// primitive's triangle vertices, and sums the post-transform
    /// triangle areas. A mesh instanced under two nodes therefore
    /// contributes twice (once per instance), and each instance's
    /// contribution reflects the world-space scale (and any
    /// non-uniform skew) on the path to that node.
    ///
    /// # Derivation
    ///
    /// For a triangle `(P_a, P_b, P_c)` mapped through the affine world
    /// matrix `M`, the post-transform edge vectors are
    /// `M_3ยท(P_b - P_a)` and `M_3ยท(P_c - P_a)` (the translation row
    /// cancels in the difference; `M_3` is the upper-left 3x3). The
    /// transformed triangle's area is
    ///
    /// ```text
    /// A_world = |(M_3ยทE1) ร— (M_3ยทE2)| / 2.
    /// ```
    ///
    /// Under a uniform scale `s` the factor collapses to `sยฒ`. Under a
    /// non-uniform diagonal scale `(sx, sy, sz)` the factor depends on
    /// the triangle's facing axis, so per-triangle evaluation โ€” rather
    /// than a single det-based scale โ€” is required for correctness.
    /// The translation column of `M` does not enter the area
    /// computation, so the result is translation-invariant per
    /// triangle (as expected for an intrinsic area metric).
    ///
    /// # Contract
    ///
    /// * Topology handling, degenerate-triangle skipping, NaN-guarding,
    ///   and out-of-range-index skipping all mirror
    ///   [`crate::Primitive::surface_area`]. Non-triangle topologies
    ///   contribute 0.0. Result is finite and non-negative for any
    ///   finite input.
    /// * Mesh resources not reachable from any [`Scene3D::roots`] node
    ///   contribute 0.0 โ€” the count is per-instance over the
    ///   scene-graph, not per-resource. For a resource-level total see
    ///   [`Scene3D::surface_area`].
    /// * Cycles in the scene-graph are guarded the same way as
    ///   [`Scene3D::bounding_box`] / [`Scene3D::world_node_transforms`]:
    ///   each node is visited at most once. A node instanced under two
    ///   parents resolves to one world matrix (the first parent on the
    ///   DFS path); use an explicit instance side-table if your decoder
    ///   needs both.
    /// * Skin pose deformation, morph targets, and unit-axis conversion
    ///   are *not* applied โ€” the static scene-graph transform is the
    ///   only thing folded in. For a pose-time area, apply the
    ///   animation pose before calling.
    /// * Cost `O(reachable_nodes + ฮฃ triangle_count_per_reachable_mesh)`.
    ///   Allocates the DFS stack only; the per-triangle math is in
    ///   `f64` to avoid `f32` drift on dense meshes.
    pub fn world_surface_area(&self) -> f64 {
        let n_nodes = self.nodes.len();
        let n_meshes = self.meshes.len();
        if n_nodes == 0 || n_meshes == 0 {
            return 0.0;
        }
        let mut visited = vec![false; n_nodes];
        let identity: [[f32; 4]; 4] = [
            [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],
        ];
        let mut total = 0.0_f64;
        // Push roots in reverse so the LIFO pop visits the leftmost
        // root first โ€” matching `world_node_transforms`'s documented
        // single-resolution policy (a shared instance reachable from
        // two parents resolves via the first parent on the DFS path).
        let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
            self.roots.iter().rev().map(|r| (*r, identity)).collect();
        while let Some((nid, parent)) = stack.pop() {
            let idx = nid.0 as usize;
            if idx >= n_nodes || visited[idx] {
                continue;
            }
            visited[idx] = true;
            let node = &self.nodes[idx];
            let world = mat4_mul(parent, node.transform.to_matrix());
            if let Some(m) = node.mesh {
                if let Some(mesh) = self.meshes.get(m.0 as usize) {
                    for prim in &mesh.primitives {
                        total += prim.world_surface_area(world);
                    }
                }
            }
            // Walk children in reverse so leftmost child is popped first.
            for child in node.children.iter().rev() {
                stack.push((*child, world));
            }
        }
        total
    }

    /// Transform-aware total signed volume across every
    /// node-instantiated mesh, in world units cubed.
    ///
    /// Whereas [`Scene3D::signed_volume`] sums each *mesh resource* once
    /// in its local frame, `world_signed_volume` walks the
    /// [`Scene3D::roots`] forest, applies each reachable node's
    /// world-space transform to the underlying primitives, and
    /// accumulates the per-instance signed enclosed volume.
    ///
    /// # Derivation
    ///
    /// For a primitive with local signed volume
    /// `V_local = (1/6) ฮฃ P_a ยท (P_b ร— P_c)` and an affine world
    /// transform `M` whose upper-left 3x3 is `M_3` with translation
    /// column `t`, every transformed corner is `M_3ยทP + t`. Expanding
    /// the per-triangle scalar triple product:
    ///
    /// ```text
    /// (M_3ยทP_a + t) ยท ((M_3ยทP_b + t) ร— (M_3ยทP_c + t))
    ///   = det(M_3) ยท (P_a ยท (P_b ร— P_c)) + boundary_terms(t).
    /// ```
    ///
    /// The `boundary_terms(t)` involve only the open-mesh boundary and
    /// vanish for a closed two-manifold (the same origin-cancellation
    /// that makes the local signed volume translation-invariant). For
    /// such a mesh the world signed volume reduces to
    ///
    /// ```text
    /// V_world = det(M_3) ยท V_local.
    /// ```
    ///
    /// `det(M_3)` is the *signed* 3x3 determinant: a uniform scale of
    /// `s` gives `sยณ`; a single-axis mirror (`-1` on one axis) gives
    /// `-1`, correctly flipping the enclosed-volume sign because the
    /// triangle winding flips with the mirror. For an open mesh, the
    /// translation-dependent boundary term means this scaling identity
    /// is only an approximation; the helper still returns the
    /// closed-form `det(M_3) ยท V_local` because that is the
    /// physically-meaningful summand whenever the per-instance mesh is
    /// itself a closed surface (the usual case for which the
    /// volume reduction is defined).
    ///
    /// # Contract
    ///
    /// * Reachability, cycle-guarding, and per-instance accumulation
    ///   match [`Scene3D::world_surface_area`].
    /// * Each node's world matrix is reduced to its upper-left 3x3
    ///   determinant; non-finite determinants (matrix corruption,
    ///   inf/NaN entries) skip the contribution.
    /// * Each mesh resource contributes once per reachable node that
    ///   references it. A two-node instance with mirrored scale
    ///   `[-1, 1, 1]` and an unmirrored sibling cancel each other in
    ///   the signed sum โ€” that is the geometric truth.
    /// * Skin pose, morph targets, and unit-axis conversion are not
    ///   applied.
    /// * Returns `0.0` for an empty scene or one with no
    ///   reachable meshes.
    /// * Result is finite for any finite input; the accumulator is
    ///   `f64`.
    /// * Cost `O(reachable_nodes + ฮฃ triangle_count_per_reachable_mesh)`.
    pub fn world_signed_volume(&self) -> f64 {
        let n_nodes = self.nodes.len();
        let n_meshes = self.meshes.len();
        if n_nodes == 0 || n_meshes == 0 {
            return 0.0;
        }
        let mut visited = vec![false; n_nodes];
        let identity: [[f32; 4]; 4] = [
            [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],
        ];
        let mut total = 0.0_f64;
        // Push roots in reverse so the LIFO pop visits the leftmost
        // root first โ€” matching `world_node_transforms`'s
        // single-resolution policy.
        let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
            self.roots.iter().rev().map(|r| (*r, identity)).collect();
        while let Some((nid, parent)) = stack.pop() {
            let idx = nid.0 as usize;
            if idx >= n_nodes || visited[idx] {
                continue;
            }
            visited[idx] = true;
            let node = &self.nodes[idx];
            let world = mat4_mul(parent, node.transform.to_matrix());
            if let Some(m) = node.mesh {
                if let Some(mesh) = self.meshes.get(m.0 as usize) {
                    let det = mat3_det_of_world(world);
                    if det.is_finite() {
                        let local = mesh.signed_volume();
                        let scaled = det * local;
                        if scaled.is_finite() {
                            total += scaled;
                        }
                    }
                }
            }
            for child in node.children.iter().rev() {
                stack.push((*child, world));
            }
        }
        total
    }

    /// Unsigned `|world_signed_volume()|` across the scene.
    ///
    /// Same shell-cancellation caveat as
    /// [`Scene3D::volume`] / [`crate::Mesh::volume`]: this is
    /// `|ฮฃ signed_world|`, not `ฮฃ |signed_world|`. For a scene where
    /// instances may carry mirrored scales (producing per-instance
    /// negative signed volumes), prefer summing each instance's
    /// `|det(M_3) ยท signed_volume|` separately.
    pub fn world_volume(&self) -> f64 {
        self.world_signed_volume().abs()
    }

    /// Walk every cross-collection reference and report dangling
    /// indices + inconsistent buffer lengths. Returns `Ok(())` when
    /// the scene is internally consistent, or `Err` carrying every
    /// problem found (the walk does not short-circuit, so callers see
    /// the full set in one pass).
    ///
    /// Currently checks:
    ///
    /// * `roots` reference live `nodes`.
    /// * Every `Node::children`, `Node::mesh`, `Node::camera`,
    ///   `Node::light`, `Node::skin`, `Node::audio_emitter` references
    ///   a live entry in the corresponding arena.
    /// * Every primitive's optional attribute buffer (`normals`,
    ///   `tangents`, `uvs[i]`, `colors[i]`, `joints`, `weights`)
    ///   matches `positions.len()`.
    /// * `Primitive::indices` values stay within `positions.len()`.
    /// * `Primitive::material` indices are live.
    /// * Each `MorphTarget` slot length matches the corresponding
    ///   base attribute on the parent `Primitive`.
    /// * `Mesh::weights.len()` matches the morph-target count of
    ///   every contained primitive (or every primitive has zero
    ///   targets and `weights` is empty).
    /// * Every `Skeleton::inverse_bind_matrices` entry has its fourth
    ///   row set to `[0, 0, 0, 1]` (glTF 2.0 ยง5.28.1 affine-IBM
    ///   constraint).
    ///
    /// This is a defensive check for fuzzers and codec authors โ€”
    /// production decoders are expected to produce valid scenes
    /// already; the runtime cost is `O(N)` over every typed buffer.
    pub fn validate(&self) -> std::result::Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();
        let n_nodes = self.nodes.len();
        let n_meshes = self.meshes.len();
        let n_materials = self.materials.len();
        let n_textures = self.textures.len();
        let n_cameras = self.cameras.len();
        let n_lights = self.lights.len();
        let n_skeletons = self.skeletons.len();
        let n_skins = self.skins.len();
        let n_emitters = self.audio_emitters.len();
        let n_audio_sources = self.audio_sources.len();

        for (i, root) in self.roots.iter().enumerate() {
            if (root.0 as usize) >= n_nodes {
                errors.push(ValidationError::DanglingId {
                    location: format!("roots[{i}]"),
                    id: root.0,
                    arena: "nodes",
                });
            }
        }
        for (i, node) in self.nodes.iter().enumerate() {
            for (j, child) in node.children.iter().enumerate() {
                if (child.0 as usize) >= n_nodes {
                    errors.push(ValidationError::DanglingId {
                        location: format!("nodes[{i}].children[{j}]"),
                        id: child.0,
                        arena: "nodes",
                    });
                }
            }
            if let Some(m) = node.mesh {
                if (m.0 as usize) >= n_meshes {
                    errors.push(ValidationError::DanglingId {
                        location: format!("nodes[{i}].mesh"),
                        id: m.0,
                        arena: "meshes",
                    });
                }
            }
            if let Some(c) = node.camera {
                if (c.0 as usize) >= n_cameras {
                    errors.push(ValidationError::DanglingId {
                        location: format!("nodes[{i}].camera"),
                        id: c.0,
                        arena: "cameras",
                    });
                }
            }
            if let Some(l) = node.light {
                if (l.0 as usize) >= n_lights {
                    errors.push(ValidationError::DanglingId {
                        location: format!("nodes[{i}].light"),
                        id: l.0,
                        arena: "lights",
                    });
                }
            }
            if let Some(s) = node.skin {
                if (s.0 as usize) >= n_skins {
                    errors.push(ValidationError::DanglingId {
                        location: format!("nodes[{i}].skin"),
                        id: s.0,
                        arena: "skins",
                    });
                }
            }
            if let Some(e) = node.audio_emitter {
                if (e.0 as usize) >= n_emitters {
                    errors.push(ValidationError::DanglingId {
                        location: format!("nodes[{i}].audio_emitter"),
                        id: e.0,
                        arena: "audio_emitters",
                    });
                }
            }
        }

        for (mi, mesh) in self.meshes.iter().enumerate() {
            let mesh_weights = mesh.weights.len();
            for (pi, prim) in mesh.primitives.iter().enumerate() {
                let n_pos = prim.positions.len();
                let here = |field: &str| format!("meshes[{mi}].primitives[{pi}].{field}");
                if let Some(v) = &prim.normals {
                    if v.len() != n_pos {
                        errors.push(ValidationError::AttributeLengthMismatch {
                            location: here("normals"),
                            expected: n_pos,
                            actual: v.len(),
                        });
                    }
                }
                if let Some(v) = &prim.tangents {
                    if v.len() != n_pos {
                        errors.push(ValidationError::AttributeLengthMismatch {
                            location: here("tangents"),
                            expected: n_pos,
                            actual: v.len(),
                        });
                    }
                }
                for (k, set) in prim.uvs.iter().enumerate() {
                    if set.len() != n_pos {
                        errors.push(ValidationError::AttributeLengthMismatch {
                            location: here(&format!("uvs[{k}]")),
                            expected: n_pos,
                            actual: set.len(),
                        });
                    }
                }
                for (k, set) in prim.colors.iter().enumerate() {
                    if set.len() != n_pos {
                        errors.push(ValidationError::AttributeLengthMismatch {
                            location: here(&format!("colors[{k}]")),
                            expected: n_pos,
                            actual: set.len(),
                        });
                    }
                }
                if let Some(v) = &prim.joints {
                    if v.len() != n_pos {
                        errors.push(ValidationError::AttributeLengthMismatch {
                            location: here("joints"),
                            expected: n_pos,
                            actual: v.len(),
                        });
                    }
                }
                if let Some(v) = &prim.weights {
                    if v.len() != n_pos {
                        errors.push(ValidationError::AttributeLengthMismatch {
                            location: here("weights"),
                            expected: n_pos,
                            actual: v.len(),
                        });
                    }
                }
                if let Some(idx) = &prim.indices {
                    let max_ok = n_pos as u32;
                    let bad = match idx {
                        crate::mesh::Indices::U16(v) => v.iter().any(|i| (*i as u32) >= max_ok),
                        crate::mesh::Indices::U32(v) => v.iter().any(|i| *i >= max_ok),
                    };
                    if bad {
                        errors.push(ValidationError::IndexOutOfRange {
                            location: here("indices"),
                            vertex_count: n_pos,
                        });
                    }
                }
                if let Some(m) = prim.material {
                    if (m.0 as usize) >= n_materials {
                        errors.push(ValidationError::DanglingId {
                            location: here("material"),
                            id: m.0,
                            arena: "materials",
                        });
                    }
                }
                for (ti, tgt) in prim.targets.iter().enumerate() {
                    let tgt_loc = |field: &str| here(&format!("targets[{ti}].{field}"));
                    if let Some(v) = &tgt.position {
                        if v.len() != n_pos {
                            errors.push(ValidationError::AttributeLengthMismatch {
                                location: tgt_loc("position"),
                                expected: n_pos,
                                actual: v.len(),
                            });
                        }
                    }
                    if let Some(v) = &tgt.normal {
                        if v.len() != n_pos {
                            errors.push(ValidationError::AttributeLengthMismatch {
                                location: tgt_loc("normal"),
                                expected: n_pos,
                                actual: v.len(),
                            });
                        }
                    }
                    if let Some(v) = &tgt.tangent {
                        if v.len() != n_pos {
                            errors.push(ValidationError::AttributeLengthMismatch {
                                location: tgt_loc("tangent"),
                                expected: n_pos,
                                actual: v.len(),
                            });
                        }
                    }
                }
                if mesh_weights != 0 && prim.targets.len() != mesh_weights {
                    errors.push(ValidationError::MorphWeightCountMismatch {
                        location: format!("meshes[{mi}].primitives[{pi}].targets"),
                        mesh_weights,
                        primitive_targets: prim.targets.len(),
                    });
                }
            }
        }

        // Materials โ†’ textures.
        for (mi, mat) in self.materials.iter().enumerate() {
            let slot = |field: &str| format!("materials[{mi}].{field}");
            let mut check = |field: &str, t: Option<crate::material::TextureRef>| {
                if let Some(r) = t {
                    if (r.texture.0 as usize) >= n_textures {
                        errors.push(ValidationError::DanglingId {
                            location: slot(field),
                            id: r.texture.0,
                            arena: "textures",
                        });
                    }
                }
            };
            check("base_color_texture", mat.base_color_texture);
            check("metallic_roughness_texture", mat.metallic_roughness_texture);
            check("normal_texture", mat.normal_texture);
            check("occlusion_texture", mat.occlusion_texture);
            check("emissive_texture", mat.emissive_texture);
        }

        // Skeletons โ†’ nodes + inverse-bind-matrix parity.
        for (si, skel) in self.skeletons.iter().enumerate() {
            for (ji, joint) in skel.joints.iter().enumerate() {
                if (joint.0 as usize) >= n_nodes {
                    errors.push(ValidationError::DanglingId {
                        location: format!("skeletons[{si}].joints[{ji}]"),
                        id: joint.0,
                        arena: "nodes",
                    });
                }
            }
            if !skel.inverse_bind_matrices.is_empty()
                && skel.inverse_bind_matrices.len() != skel.joints.len()
            {
                errors.push(ValidationError::SkeletonBindMatrixCountMismatch {
                    location: format!("skeletons[{si}]"),
                    joints: skel.joints.len(),
                    inverse_bind_matrices: skel.inverse_bind_matrices.len(),
                });
            }
            // glTF 2.0 ยง5.28.1: an accessor referenced by
            // `inverseBindMatrices` MUST have its fourth row set to
            // `[0.0, 0.0, 0.0, 1.0]` (the matrix is affine โ€” a pure
            // composition of rotations/translations/scales/shears,
            // never projective). Our matrix is row-major
            // column-vector, so the "fourth row" of the math matrix
            // is the row at index 3.
            for (ji, ibm) in skel.inverse_bind_matrices.iter().enumerate() {
                let last = ibm[3];
                if last[0] != 0.0 || last[1] != 0.0 || last[2] != 0.0 || last[3] != 1.0 {
                    errors.push(ValidationError::SkeletonBindMatrixNotAffine {
                        location: format!("skeletons[{si}].inverse_bind_matrices[{ji}]"),
                        last_row: last,
                    });
                }
            }
        }

        // Skins โ†’ skeletons + optional root node.
        for (si, skin) in self.skins.iter().enumerate() {
            if (skin.skeleton.0 as usize) >= n_skeletons {
                errors.push(ValidationError::DanglingId {
                    location: format!("skins[{si}].skeleton"),
                    id: skin.skeleton.0,
                    arena: "skeletons",
                });
            }
            if let Some(r) = skin.root_node {
                if (r.0 as usize) >= n_nodes {
                    errors.push(ValidationError::DanglingId {
                        location: format!("skins[{si}].root_node"),
                        id: r.0,
                        arena: "nodes",
                    });
                }
            }
        }

        // Audio emitters โ†’ audio sources.
        for (ei, em) in self.audio_emitters.iter().enumerate() {
            if (em.source.0 as usize) >= n_audio_sources {
                errors.push(ValidationError::DanglingId {
                    location: format!("audio_emitters[{ei}].source"),
                    id: em.source.0,
                    arena: "audio_sources",
                });
            }
        }

        // Animations: channel target nodes + sampler parity.
        for (ai, anim) in self.animations.iter().enumerate() {
            for (ci, ch) in anim.channels.iter().enumerate() {
                let loc = |suffix: &str| format!("animations[{ai}].channels[{ci}]{suffix}");
                if (ch.target.node.0 as usize) >= n_nodes {
                    errors.push(ValidationError::DanglingId {
                        location: loc(".target.node"),
                        id: ch.target.node.0,
                        arena: "nodes",
                    });
                }
                let k = ch.sampler.keyframes.len();
                if k == 0 {
                    errors.push(ValidationError::AnimationSamplerEmpty {
                        location: loc(".sampler"),
                    });
                } else {
                    let mut prev = f32::NEG_INFINITY;
                    for (ki, t) in ch.sampler.keyframes.iter().enumerate() {
                        if t.partial_cmp(&prev) != Some(std::cmp::Ordering::Greater) {
                            errors.push(ValidationError::AnimationKeyframesNotStrictlyIncreasing {
                                location: loc(&format!(".sampler.keyframes[{ki}]")),
                                at: *t,
                                previous: prev,
                            });
                            break;
                        }
                        prev = *t;
                    }
                }

                use crate::animation::{AnimationProperty as P, AnimationValues as V};
                let variant_ok = matches!(
                    (ch.target.property, &ch.sampler.values),
                    (P::Translation | P::Scale, V::Vec3(_))
                        | (P::Rotation, V::Quat(_))
                        | (P::MorphWeights, V::Scalar(_))
                );
                if !variant_ok {
                    let expected: &'static str = match ch.target.property {
                        P::Translation | P::Scale => "Vec3",
                        P::Rotation => "Quat",
                        P::MorphWeights => "Scalar",
                    };
                    let actual: &'static str = match ch.sampler.values {
                        V::Vec3(_) => "Vec3",
                        V::Quat(_) => "Quat",
                        V::Scalar(_) => "Scalar",
                    };
                    errors.push(ValidationError::AnimationValueVariantMismatch {
                        location: loc(""),
                        property: match ch.target.property {
                            P::Translation => "Translation",
                            P::Rotation => "Rotation",
                            P::Scale => "Scale",
                            P::MorphWeights => "MorphWeights",
                        },
                        expected_variant: expected,
                        actual_variant: actual,
                    });
                }

                if k != 0 {
                    let v = ch.sampler.values.len();
                    let expected_factor = match ch.sampler.interpolation {
                        crate::animation::Interpolation::CubicSpline => 3,
                        _ => 1,
                    };
                    let ok = match (ch.target.property, &ch.sampler.values) {
                        (P::MorphWeights, V::Scalar(_)) => {
                            let denom = k * expected_factor;
                            denom != 0 && v % denom == 0 && v >= denom
                        }
                        _ => v == k * expected_factor,
                    };
                    if !ok {
                        errors.push(ValidationError::AnimationSamplerLengthMismatch {
                            location: loc(".sampler"),
                            keyframes: k,
                            values: v,
                            interpolation: match ch.sampler.interpolation {
                                crate::animation::Interpolation::Step => "Step",
                                crate::animation::Interpolation::Linear => "Linear",
                                crate::animation::Interpolation::CubicSpline => "CubicSpline",
                            },
                        });
                    }
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// One issue surfaced by [`Scene3D::validate`]. The variants intentionally
/// carry breadcrumb strings (`"meshes[3].primitives[0].normals"`) so a
/// caller can render a usable diagnostic without re-walking the scene.
///
/// `Eq` is not implemented because
/// [`AnimationKeyframesNotStrictlyIncreasing`](Self::AnimationKeyframesNotStrictlyIncreasing)
/// carries `f32` keyframe values; use `PartialEq` or pattern-match on
/// the variant fields when asserting in tests.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ValidationError {
    /// A typed `IdT(u32)` field points outside its arena.
    DanglingId {
        location: String,
        id: u32,
        arena: &'static str,
    },
    /// An optional attribute buffer is present but its length disagrees
    /// with the parent primitive's `positions.len()`.
    AttributeLengthMismatch {
        location: String,
        expected: usize,
        actual: usize,
    },
    /// A primitive's index buffer references a vertex past
    /// `positions.len()`.
    IndexOutOfRange {
        location: String,
        vertex_count: usize,
    },
    /// `Mesh::weights` is non-empty and disagrees with one of the
    /// child primitives' morph-target count.
    MorphWeightCountMismatch {
        location: String,
        mesh_weights: usize,
        primitive_targets: usize,
    },
    /// [`Skeleton::inverse_bind_matrices`](crate::Skeleton::inverse_bind_matrices)
    /// is non-empty and its length disagrees with
    /// [`Skeleton::joints`](crate::Skeleton::joints).
    SkeletonBindMatrixCountMismatch {
        location: String,
        joints: usize,
        inverse_bind_matrices: usize,
    },
    /// One of [`Skeleton::inverse_bind_matrices`](crate::Skeleton::inverse_bind_matrices)
    /// has a non-affine fourth row. The glTF 2.0 spec ยง5.28.1
    /// requires every IBM's last row to be `[0.0, 0.0, 0.0, 1.0]`;
    /// any other value implies a projective component that the
    /// skinning math `(weight_i * joint_world_i * IBM_i * pos)` would
    /// silently corrupt.
    SkeletonBindMatrixNotAffine {
        location: String,
        last_row: [f32; 4],
    },
    /// An animation channel's sampler has zero keyframes; no
    /// keyframe-time table to interpolate against.
    AnimationSamplerEmpty { location: String },
    /// An animation sampler's keyframe times are not strictly
    /// increasing โ€” the renderer would search ambiguously.
    AnimationKeyframesNotStrictlyIncreasing {
        location: String,
        at: f32,
        previous: f32,
    },
    /// An animation sampler's value variant disagrees with the
    /// channel target's property kind (e.g. `Rotation` channel
    /// fed `Vec3` values).
    AnimationValueVariantMismatch {
        location: String,
        property: &'static str,
        expected_variant: &'static str,
        actual_variant: &'static str,
    },
    /// An animation sampler's value count doesn't match the expected
    /// `keyframes.len() * factor` (`factor = 1` for Step/Linear,
    /// `factor = 3` for CubicSpline; MorphWeights additionally
    /// multiplies by per-mesh morph-target count, so we only check
    /// divisibility there).
    AnimationSamplerLengthMismatch {
        location: String,
        keyframes: usize,
        values: usize,
        interpolation: &'static str,
    },
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DanglingId {
                location,
                id,
                arena,
            } => write!(f, "{location}: id {id} is out of bounds for {arena}"),
            Self::AttributeLengthMismatch {
                location,
                expected,
                actual,
            } => write!(
                f,
                "{location}: length {actual} disagrees with positions length {expected}"
            ),
            Self::IndexOutOfRange {
                location,
                vertex_count,
            } => write!(
                f,
                "{location}: index buffer references vertex >= {vertex_count}"
            ),
            Self::MorphWeightCountMismatch {
                location,
                mesh_weights,
                primitive_targets,
            } => write!(
                f,
                "{location}: mesh has {mesh_weights} weights but primitive carries {primitive_targets} morph targets"
            ),
            Self::SkeletonBindMatrixCountMismatch {
                location,
                joints,
                inverse_bind_matrices,
            } => write!(
                f,
                "{location}: skeleton has {joints} joints but {inverse_bind_matrices} inverse-bind matrices"
            ),
            Self::SkeletonBindMatrixNotAffine { location, last_row } => write!(
                f,
                "{location}: inverse-bind matrix last row {last_row:?} is not [0, 0, 0, 1]"
            ),
            Self::AnimationSamplerEmpty { location } => {
                write!(f, "{location}: sampler has no keyframes")
            }
            Self::AnimationKeyframesNotStrictlyIncreasing {
                location,
                at,
                previous,
            } => write!(
                f,
                "{location}: keyframe time {at} is not greater than previous {previous}"
            ),
            Self::AnimationValueVariantMismatch {
                location,
                property,
                expected_variant,
                actual_variant,
            } => write!(
                f,
                "{location}: property {property} expects {expected_variant} values but sampler carries {actual_variant}"
            ),
            Self::AnimationSamplerLengthMismatch {
                location,
                keyframes,
                values,
                interpolation,
            } => write!(
                f,
                "{location}: interpolation {interpolation} with {keyframes} keyframes expects matching values, got {values}"
            ),
        }
    }
}

impl std::error::Error for ValidationError {}

impl Default for Scene3D {
    fn default() -> Self {
        Self::new()
    }
}