animsmith-gltf 0.4.0

glTF/GLB ingestion into the animsmith core model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
//! Read-only raw glTF capability inventory for scale producers.
//!
//! A normalized [`animsmith_core::Document`] cannot prove that a source file
//! lacked data the loader does not model. This module therefore inventories
//! the original glTF JSON and resolved buffers before any scale plan or
//! candidate document exists.

use crate::{
    LoadError, load_source_bytes, resolve_buffers, topology, validate_animations,
    validate_document, validate_glb_framing,
};
use animsmith_core::{Document, LoadedSource, SourceFactsViewV1};
use serde::Serialize;
use serde_json::{Map, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

const GLB_MAGIC: &[u8; 4] = b"glTF";
const GLB_JSON_CHUNK: u32 = 0x4e4f_534a;

/// Whether the captured top-level source is JSON glTF or a binary GLB.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfContainerKind {
    /// A plain JSON `.gltf` document.
    Gltf,
    /// A binary `.glb` container.
    Glb,
}

/// How one source buffer was declared.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfBufferSourceKind {
    /// The GLB BIN chunk.
    BinaryChunk,
    /// A base64 data URI.
    DataUri,
    /// An external relative URI.
    External,
}

/// One source buffer recorded before normalized loading.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfBufferCapability {
    /// Stable source buffer index.
    pub buffer_index: usize,
    /// Source declaration kind.
    pub source_kind: GltfBufferSourceKind,
    /// Declared byte length.
    pub declared_byte_length: u64,
}

/// Whether a node authored decomposed TRS or a matrix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GltfNodeRestKind {
    /// No matrix was declared, so the node uses glTF TRS properties/defaults.
    Trs,
    /// The node declared a local matrix.
    Matrix,
}

/// One source node identity and authored rest representation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfNodeCapability {
    /// Stable source node index.
    pub node_index: usize,
    /// Authored rest representation.
    pub rest_kind: GltfNodeRestKind,
    /// Referenced mesh index, when present.
    pub mesh_index: Option<usize>,
    /// Referenced skin index, when present.
    pub skin_index: Option<usize>,
}

/// One animation channel and its exact accessor identities.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfAnimationChannelCapability {
    /// Stable source animation index.
    pub animation_index: usize,
    /// Channel index inside the animation.
    pub channel_index: usize,
    /// Source target node index.
    pub target_node_index: usize,
    /// glTF target path (`translation`, `rotation`, `scale`, or `weights`).
    pub target_path: String,
    /// glTF interpolation spelling.
    pub interpolation: String,
    /// Input time accessor index.
    pub input_accessor_index: usize,
    /// Output value accessor index.
    pub output_accessor_index: usize,
}

/// One vertex attribute declaration and its source accessor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfAttributeCapability {
    /// glTF attribute semantic such as `POSITION` or `JOINTS_0`.
    pub semantic: String,
    /// Stable source accessor index.
    pub accessor_index: usize,
}

/// One source primitive and every declared attribute semantic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfPrimitiveCapability {
    /// Stable source mesh index.
    pub mesh_index: usize,
    /// Primitive index inside the mesh.
    pub primitive_index: usize,
    /// Raw glTF primitive mode value (default `4`, triangles).
    pub mode: u64,
    /// Attributes in lexical semantic order with exact accessor identities.
    pub attributes: Vec<GltfAttributeCapability>,
    /// Number of declared morph targets.
    pub morph_target_count: usize,
    /// `POSITION` accessor indices from morph targets in target order.
    pub morph_position_accessors: Vec<usize>,
    /// Located morph semantics this scale boundary cannot preserve.
    #[serde(skip)]
    pub unsupported_morph_locations: Vec<String>,
}

/// One raw `EXT_mesh_gpu_instancing` declaration and its accessor identities.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfInstancingCapability {
    /// Stable source node index carrying the instancing payload.
    pub node_index: usize,
    /// Instancing attributes in lexical semantic order.
    pub attributes: Vec<GltfAttributeCapability>,
}

/// One raw accessor layout required by a future exact-source rewrite.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfAccessorCapability {
    /// Stable source accessor index.
    pub accessor_index: usize,
    /// Referenced buffer-view index, when present.
    pub buffer_view_index: Option<usize>,
    /// Byte offset relative to the buffer view.
    pub byte_offset: u64,
    /// Raw glTF component-type value.
    pub component_type: u64,
    /// Raw glTF accessor type such as `VEC3` or `MAT4`.
    pub accessor_type: String,
    /// Declared element count.
    pub count: u64,
    /// Whether normalized integer interpretation was requested.
    pub normalized: bool,
    /// Whether the accessor declares sparse replacement data.
    pub sparse: bool,
}

/// One raw buffer-view layout.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfBufferViewCapability {
    /// Stable source buffer-view index.
    pub buffer_view_index: usize,
    /// Stable source buffer index.
    pub buffer_index: usize,
    /// Byte offset relative to the buffer.
    pub byte_offset: u64,
    /// Declared byte length.
    pub byte_length: u64,
    /// Optional element stride.
    pub byte_stride: Option<u64>,
}

/// Read-side inverse-bind declaration for one source skin.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfSkinCapability {
    /// Stable source skin index.
    pub skin_index: usize,
    /// Number of declared joints.
    pub joint_count: usize,
    /// Declared inverse-bind accessor index, when present.
    pub inverse_bind_accessor_index: Option<usize>,
    /// Declared inverse-bind accessor count, when readable from raw JSON.
    pub inverse_bind_count: Option<u64>,
}

/// Deterministic facts captured from the original glTF/GLB source.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GltfCapabilityManifest {
    /// Top-level container kind.
    pub container: GltfContainerKind,
    /// Source buffers in source order.
    pub buffers: Vec<GltfBufferCapability>,
    /// Source buffer views in source order.
    pub buffer_views: Vec<GltfBufferViewCapability>,
    /// Source accessors in source order.
    pub accessors: Vec<GltfAccessorCapability>,
    /// Source nodes in source order.
    pub nodes: Vec<GltfNodeCapability>,
    /// Animation channels in animation/channel order.
    pub animation_channels: Vec<GltfAnimationChannelCapability>,
    /// Mesh primitives in mesh/primitive order.
    pub primitives: Vec<GltfPrimitiveCapability>,
    /// Static and animated morph-weight locations in lexical order.
    pub morph_weight_locations: Vec<String>,
    /// GPU-instancing declarations in source node order.
    pub instancing: Vec<GltfInstancingCapability>,
    /// Source skins in source order.
    pub skins: Vec<GltfSkinCapability>,
    /// Number of declared cameras.
    pub camera_count: usize,
    /// Declared extension names in lexical order.
    pub extensions: Vec<String>,
    /// JSON pointers of extension payloads in lexical order.
    pub extension_locations: Vec<String>,
    /// JSON pointers of external buffer/image declarations in lexical order.
    pub external_resource_locations: Vec<String>,
    /// JSON pointers of every non-null `extras` value in lexical order.
    pub extras_locations: Vec<String>,
    /// JSON pointers of unknown members in lexical order.
    pub unknown_member_locations: Vec<String>,
}

/// Stable machine identity for one fail-closed capability violation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum GltfCapabilityViolationKind {
    /// A source buffer or image uses an external URI.
    ExternalResource,
    /// A morph target is present.
    MorphTarget,
    /// Static or animated morph weights are present.
    MorphWeights,
    /// A camera definition or reference is present.
    Camera,
    /// A punctual-light declaration or payload is present.
    Light,
    /// An `EXT_mesh_gpu_instancing` declaration or payload is present.
    Instancing,
    /// An extension declaration is not covered by a registered handler.
    ExtensionDeclaration,
    /// An extension payload is not covered by a registered handler.
    ExtensionPayload,
    /// Non-null application-specific extras are present.
    Extras,
    /// A JSON member outside the glTF 2.0 schema was ignored by the typed parser.
    UnknownJsonMember,
    /// A primitive mode other than triangle lists is present.
    NonTrianglePrimitive,
    /// A vertex attribute is outside the normalized writer subset.
    UnsupportedVertexAttribute,
    /// A secondary `JOINTS_n` or `WEIGHTS_n` set is present.
    SecondarySkinInfluences,
    /// A skin omitted its inverse-bind accessor.
    MissingInverseBinds,
    /// A skin declared an empty inverse-bind accessor.
    EmptyInverseBindAccessor,
    /// A skin's inverse-bind count does not equal its joint count.
    InverseBindCountMismatch,
    /// A declared inverse-bind accessor is not a dense f32 MAT4 source.
    UnreadableInverseBinds,
    /// A used accessor cannot be safely bounded, or a rewrite accessor is not dense f32.
    UnsafeAccessorLayout,
    /// One accessor is shared between scale-bearing and dimensionless semantics.
    ConflictingAccessorUse,
    /// A scale-bearing accessor overlaps another owned byte range in a source
    /// buffer. The other range is an accessor, or an `image` payload reported
    /// alongside it as [`GltfCapabilityViolationKind::ImagePayloadOverlap`].
    OverlappingAccessorRanges,
    /// A node declares `matrix` alongside `translation`, `rotation` or
    /// `scale`, which glTF 2.0 §3.5 forbids.
    ConflictingNodeTransform,
    /// A node `matrix` is not TRS-decomposable: its last row is not
    /// `(0, 0, 0, 1)`.
    NonAffineNodeMatrix,
    /// An animation targets a node that authored its rest transform as a
    /// `matrix`. glTF animation channels replace TRS properties, so there is
    /// no raw TRS property this operation can reparameterize safely.
    AnimatedMatrixNode,
    /// An `image` reads a buffer view overlapping a scale-bearing accessor.
    ImagePayloadOverlap,
}

/// One deterministic, source-indexed preflight rejection.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct GltfCapabilityViolation {
    /// JSON pointer or stable source identity for the rejected domain.
    pub location: String,
    /// Stable violation kind.
    pub kind: GltfCapabilityViolationKind,
}

/// A captured, immutable source that passed the common scale preflight.
///
/// This type deliberately has no mutation or write method. Scale operations
/// consume its manifest and captured bytes without reopening the input.
#[derive(Debug)]
pub struct GltfScaleSource {
    loaded_source: LoadedSource,
    #[cfg(test)]
    document_override: Option<Document>,
    manifest: GltfCapabilityManifest,
    source_bytes: Vec<u8>,
    raw_json: Value,
    resolved_buffers: Vec<Vec<u8>>,
}

impl GltfScaleSource {
    /// The normalized read-only document built from the captured bytes.
    pub fn document(&self) -> &Document {
        #[cfg(test)]
        if let Some(document) = self.document_override.as_ref() {
            return document;
        }
        self.loaded_source.document()
    }

    /// Importer-sensitive raw source facts bound to the normalized document.
    pub fn source_facts(&self) -> SourceFactsViewV1<'_> {
        self.loaded_source.source_facts()
    }

    /// The deterministic raw capability manifest.
    pub fn manifest(&self) -> &GltfCapabilityManifest {
        &self.manifest
    }

    /// The exact captured top-level input bytes.
    pub fn source_bytes(&self) -> &[u8] {
        &self.source_bytes
    }

    /// The original top-level JSON tree.
    pub fn raw_json(&self) -> &Value {
        &self.raw_json
    }

    /// Resolved source buffers in buffer-index order.
    pub fn resolved_buffers(&self) -> &[Vec<u8>] {
        &self.resolved_buffers
    }
}

/// Failure to load or safely preflight a captured scale source.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GltfScalePreflightError {
    /// The source was malformed or unreadable.
    #[error(transparent)]
    Load(#[from] LoadError),
    /// The source was parseable but contains unsupported raw domains.
    #[error("glTF scale preflight rejected {count} unsupported source domain(s)")]
    Unsupported {
        /// Complete inventory gathered before rejection.
        manifest: Box<GltfCapabilityManifest>,
        /// Deterministically ordered typed violations.
        violations: Vec<GltfCapabilityViolation>,
        /// Number of violations, repeated for stable error rendering.
        count: usize,
    },
}

/// Read and preflight a glTF/GLB file without creating a candidate or output.
///
/// # Errors
///
/// Returns [`GltfScalePreflightError::Load`] for unreadable or malformed input
/// and [`GltfScalePreflightError::Unsupported`] for a parseable source whose
/// complete raw domain is not covered by the initial scale boundary.
pub fn preflight_scale_source(path: &Path) -> Result<GltfScaleSource, GltfScalePreflightError> {
    let bytes = std::fs::read(path).map_err(|source| LoadError::Io {
        path: path.display().to_string(),
        source,
    })?;
    preflight_scale_source_bytes(path, &bytes)
}

/// Preflight captured glTF/GLB bytes without creating a candidate or output.
///
/// `path` is used only for source provenance and resolving resources. The
/// initial accepted subset rejects external resources before resolving them,
/// so a successful value is fully captured in memory.
///
/// # Errors
///
/// Returns [`GltfScalePreflightError::Load`] for malformed input and
/// [`GltfScalePreflightError::Unsupported`] for unsupported raw domains.
pub fn preflight_scale_source_bytes(
    path: &Path,
    bytes: &[u8],
) -> Result<GltfScaleSource, GltfScalePreflightError> {
    capture_scale_source(path, bytes, GatePolicy::Enforce)
}

/// Whether a captured source must clear the preflight's violation gate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GatePolicy {
    /// A source with any violation is refused. The only policy in a
    /// non-test build.
    Enforce,
    /// Violations are inventoried and then ignored, so a
    /// [`GltfScaleSource`] is built for a source the gate would refuse.
    ///
    /// Every operation below the gate keeps its own guard for the source
    /// facts the gate decides — [`crate::scale::rewrite_linear_units`]
    /// re-checks out-of-contract node transforms and image payloads aliasing
    /// a converted accessor. Those guards are what must hold if the gate is
    /// ever relaxed, which is exactly the property no test can observe while
    /// the gate refuses every source that would reach them: deleting the
    /// guard's call site leaves the public API's behaviour unchanged. This
    /// policy is the synthetic relaxation those tests need, and it exists
    /// only under `cfg(test)` so no release path can select it.
    #[cfg(test)]
    Bypass,
}

/// Capture a scale source, applying `policy` to the preflight's violations.
fn capture_scale_source(
    path: &Path,
    bytes: &[u8],
    policy: GatePolicy,
) -> Result<GltfScaleSource, GltfScalePreflightError> {
    validate_glb_framing(bytes)?;
    let (container, json_bytes) = raw_json_bytes(bytes)?;
    let raw_json: Value = serde_json::from_slice(json_bytes)
        .map_err(|error| LoadError::Malformed(format!("invalid top-level JSON: {error}")))?;
    if !raw_json.is_object() {
        return Err(LoadError::Malformed("top-level glTF JSON is not an object".into()).into());
    }
    let gltf = gltf::Gltf::from_slice_without_validation(bytes).map_err(LoadError::Gltf)?;

    let mut violations = Vec::new();
    let manifest = inventory(&raw_json, container, &mut violations);
    let accessor_uses = inspect_accessor_uses(&raw_json, &mut violations);
    match validate_document(&gltf.document) {
        Ok(()) => {}
        Err(error) => return Err(LoadError::Gltf(error).into()),
    }
    validate_animations(&gltf.document)?;
    topology(&gltf.document)?;

    let can_resolve_buffers = !manifest
        .buffers
        .iter()
        .any(|buffer| buffer.source_kind == GltfBufferSourceKind::External);
    let resolved_buffers = if can_resolve_buffers {
        resolve_buffers(&gltf, path.parent())?
    } else {
        Vec::new()
    };
    if can_resolve_buffers {
        inspect_accessor_layouts(
            &raw_json,
            &resolved_buffers,
            &accessor_uses,
            &mut violations,
        );
    }
    violations.sort();
    violations.dedup();
    let refuse = match policy {
        GatePolicy::Enforce => !violations.is_empty(),
        #[cfg(test)]
        GatePolicy::Bypass => false,
    };
    if refuse {
        let count = violations.len();
        return Err(GltfScalePreflightError::Unsupported {
            manifest: Box::new(manifest),
            violations,
            count,
        });
    }

    let loaded_source = load_source_bytes(path, bytes)?;
    Ok(GltfScaleSource {
        loaded_source,
        #[cfg(test)]
        document_override: None,
        manifest,
        source_bytes: bytes.to_vec(),
        raw_json,
        resolved_buffers,
    })
}

/// Capture a [`GltfScaleSource`] from bytes the preflight gate would refuse.
///
/// See [`GatePolicy::Bypass`] for why this exists. It is not a public API and
/// not reachable from an integration test: the gate is the only way to build a
/// [`GltfScaleSource`] outside this crate, and that stays true.
///
/// # Errors
///
/// Returns [`GltfScalePreflightError::Load`] for input that is malformed
/// rather than merely out of contract. `Unsupported` is never returned.
#[cfg(test)]
pub(crate) fn scale_source_past_the_gate(
    path: &Path,
    bytes: &[u8],
) -> Result<GltfScaleSource, GltfScalePreflightError> {
    capture_scale_source(path, bytes, GatePolicy::Bypass)
}

/// A captured source with its normalized document replaced.
///
/// The sibling of [`scale_source_past_the_gate`], for the one relaxation that
/// gate bypass cannot supply. A captured source's raw child arrays,
/// `SourceNodeAsset::parent_source_node_index` and `Skeleton::parent` all come
/// from a single `topology()` pass over a single parsed document, so no glTF
/// byte sequence makes them contradict each other — which is what issue #309
/// records, and what leaves
/// [`crate::scale::rest_bind`]'s hierarchy cross-check with no reachable
/// input. Handing the rewriter a source whose document says one thing and
/// whose bytes say another is the only way to falsify that check's *wiring*
/// rather than only its classification.
///
/// The document is the sole field replaced: the bytes, the raw JSON, the
/// manifest and the resolved buffers stay the captured ones, so the rewriter
/// still reads a real source and only the normalized projection disagrees.
/// It is not a public API and not reachable from an integration test.
#[cfg(test)]
pub(crate) fn scale_source_with_document(
    mut source: GltfScaleSource,
    document: Document,
) -> GltfScaleSource {
    source.document_override = Some(document);
    source
}

/// Split a captured container into its kind and its top-level JSON bytes.
///
/// Shared with [`crate::scale`], whose artifact proof must re-read the
/// emitted container through exactly the same framing the preflight used.
pub(crate) fn raw_json_bytes(bytes: &[u8]) -> Result<(GltfContainerKind, &[u8]), LoadError> {
    if !bytes.starts_with(GLB_MAGIC) {
        return Ok((GltfContainerKind::Gltf, bytes));
    }
    let chunk_length = bytes
        .get(12..16)
        .and_then(|slice| slice.try_into().ok())
        .map(u32::from_le_bytes)
        .ok_or_else(|| LoadError::Buffer("malformed GLB JSON chunk header".into()))?
        as usize;
    let chunk_type = bytes
        .get(16..20)
        .and_then(|slice| slice.try_into().ok())
        .map(u32::from_le_bytes)
        .ok_or_else(|| LoadError::Buffer("malformed GLB JSON chunk header".into()))?;
    if chunk_type != GLB_JSON_CHUNK {
        return Err(LoadError::Buffer(
            "GLB first chunk is not a JSON chunk".into(),
        ));
    }
    let end = 20usize
        .checked_add(chunk_length)
        .ok_or_else(|| LoadError::Buffer("GLB JSON chunk range overflow".into()))?;
    let json = bytes
        .get(20..end)
        .ok_or_else(|| LoadError::Buffer("malformed GLB JSON chunk length".into()))?;
    Ok((GltfContainerKind::Glb, json))
}

fn violation(
    violations: &mut Vec<GltfCapabilityViolation>,
    kind: GltfCapabilityViolationKind,
    location: impl Into<String>,
) {
    violations.push(GltfCapabilityViolation {
        kind,
        location: location.into(),
    });
}

fn as_index(value: Option<&Value>) -> Option<usize> {
    value?.as_u64()?.try_into().ok()
}

fn inventory(
    root: &Value,
    container: GltfContainerKind,
    violations: &mut Vec<GltfCapabilityViolation>,
) -> GltfCapabilityManifest {
    let Some(object) = root.as_object() else {
        return GltfCapabilityManifest {
            container,
            buffers: Vec::new(),
            buffer_views: Vec::new(),
            accessors: Vec::new(),
            nodes: Vec::new(),
            animation_channels: Vec::new(),
            primitives: Vec::new(),
            morph_weight_locations: Vec::new(),
            instancing: Vec::new(),
            skins: Vec::new(),
            camera_count: 0,
            extensions: Vec::new(),
            extension_locations: Vec::new(),
            external_resource_locations: Vec::new(),
            extras_locations: Vec::new(),
            unknown_member_locations: Vec::new(),
        };
    };
    let mut manifest = GltfCapabilityManifest {
        container,
        buffers: Vec::new(),
        buffer_views: Vec::new(),
        accessors: Vec::new(),
        nodes: Vec::new(),
        animation_channels: Vec::new(),
        primitives: Vec::new(),
        morph_weight_locations: Vec::new(),
        instancing: Vec::new(),
        skins: Vec::new(),
        camera_count: object
            .get("cameras")
            .and_then(Value::as_array)
            .map_or(0, Vec::len),
        extensions: Vec::new(),
        extension_locations: Vec::new(),
        external_resource_locations: Vec::new(),
        extras_locations: Vec::new(),
        unknown_member_locations: Vec::new(),
    };

    inspect_schema_members(root, "", &mut manifest, violations);
    inventory_extensions(object, &mut manifest, violations);
    inventory_buffers(object, container, &mut manifest, violations);
    inventory_buffer_views_and_accessors(object, &mut manifest);
    inventory_nodes(object, &mut manifest, violations);
    inventory_animations(object, &mut manifest, violations);
    inventory_meshes(object, &mut manifest, violations);
    inventory_skins(object, &mut manifest, violations);

    if manifest.camera_count > 0 {
        violation(violations, GltfCapabilityViolationKind::Camera, "/cameras");
    }
    manifest.extensions.sort();
    manifest.extensions.dedup();
    manifest.extension_locations.sort();
    manifest.extension_locations.dedup();
    manifest.external_resource_locations.sort();
    manifest.external_resource_locations.dedup();
    manifest.extras_locations.sort();
    manifest.extras_locations.dedup();
    manifest.unknown_member_locations.sort();
    manifest.unknown_member_locations.dedup();
    manifest.morph_weight_locations.sort();
    manifest.morph_weight_locations.dedup();
    manifest
}

fn inventory_extensions(
    root: &Map<String, Value>,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    for key in ["extensionsUsed", "extensionsRequired"] {
        let Some(values) = root.get(key).and_then(Value::as_array) else {
            continue;
        };
        for (index, value) in values.iter().enumerate() {
            let Some(name) = value.as_str() else { continue };
            manifest.extensions.push(name.to_owned());
            let kind = match name {
                "KHR_lights_punctual" => GltfCapabilityViolationKind::Light,
                "EXT_mesh_gpu_instancing" => GltfCapabilityViolationKind::Instancing,
                _ => GltfCapabilityViolationKind::ExtensionDeclaration,
            };
            violation(violations, kind, format!("/{key}/{index}"));
        }
    }
}

fn inventory_buffers(
    root: &Map<String, Value>,
    container: GltfContainerKind,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    let Some(buffers) = root.get("buffers").and_then(Value::as_array) else {
        return;
    };
    for (buffer_index, buffer) in buffers.iter().enumerate() {
        let Some(buffer) = buffer.as_object() else {
            continue;
        };
        let uri = buffer.get("uri").and_then(Value::as_str);
        let source_kind = match uri {
            Some(uri) if uri.starts_with("data:") => GltfBufferSourceKind::DataUri,
            Some(_) => GltfBufferSourceKind::External,
            None if container == GltfContainerKind::Glb => GltfBufferSourceKind::BinaryChunk,
            None => GltfBufferSourceKind::External,
        };
        if source_kind == GltfBufferSourceKind::External {
            manifest
                .external_resource_locations
                .push(format!("/buffers/{buffer_index}/uri"));
            violation(
                violations,
                GltfCapabilityViolationKind::ExternalResource,
                format!("/buffers/{buffer_index}/uri"),
            );
        }
        manifest.buffers.push(GltfBufferCapability {
            buffer_index,
            source_kind,
            declared_byte_length: buffer
                .get("byteLength")
                .and_then(Value::as_u64)
                .unwrap_or(0),
        });
    }
    if let Some(images) = root.get("images").and_then(Value::as_array) {
        for (image_index, image) in images.iter().enumerate() {
            if image
                .get("uri")
                .and_then(Value::as_str)
                .is_some_and(|uri| !uri.starts_with("data:"))
            {
                manifest
                    .external_resource_locations
                    .push(format!("/images/{image_index}/uri"));
                violation(
                    violations,
                    GltfCapabilityViolationKind::ExternalResource,
                    format!("/images/{image_index}/uri"),
                );
            }
        }
    }
}

fn inventory_buffer_views_and_accessors(
    root: &Map<String, Value>,
    manifest: &mut GltfCapabilityManifest,
) {
    if let Some(buffer_views) = root.get("bufferViews").and_then(Value::as_array) {
        for (buffer_view_index, view) in buffer_views.iter().enumerate() {
            let Some(view) = view.as_object() else {
                continue;
            };
            manifest.buffer_views.push(GltfBufferViewCapability {
                buffer_view_index,
                buffer_index: as_index(view.get("buffer")).unwrap_or(usize::MAX),
                byte_offset: view.get("byteOffset").and_then(Value::as_u64).unwrap_or(0),
                byte_length: view.get("byteLength").and_then(Value::as_u64).unwrap_or(0),
                byte_stride: view.get("byteStride").and_then(Value::as_u64),
            });
        }
    }
    if let Some(accessors) = root.get("accessors").and_then(Value::as_array) {
        for (accessor_index, accessor) in accessors.iter().enumerate() {
            let Some(accessor) = accessor.as_object() else {
                continue;
            };
            manifest.accessors.push(GltfAccessorCapability {
                accessor_index,
                buffer_view_index: as_index(accessor.get("bufferView")),
                byte_offset: accessor
                    .get("byteOffset")
                    .and_then(Value::as_u64)
                    .unwrap_or(0),
                component_type: accessor
                    .get("componentType")
                    .and_then(Value::as_u64)
                    .unwrap_or(0),
                accessor_type: accessor
                    .get("type")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_owned(),
                count: accessor.get("count").and_then(Value::as_u64).unwrap_or(0),
                normalized: accessor
                    .get("normalized")
                    .and_then(Value::as_bool)
                    .unwrap_or(false),
                sparse: accessor.contains_key("sparse"),
            });
        }
    }
}

/// The last row of a column-major glTF node `matrix`, and the only values
/// glTF 2.0 permits there.
///
/// Shared with [`crate::scale`], whose rewriter keeps its own guard as
/// defence in depth: re-deriving the row there would let two definitions of
/// "affine" drift apart, which is exactly how this workspace's two affine
/// classifiers once came to disagree.
pub(crate) const AFFINE_LAST_ROW: [(usize, f64); 4] = [(3, 0.0), (7, 0.0), (11, 0.0), (15, 1.0)];

/// One way a source node's transform is outside the glTF 2.0 contract.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum NodeTransformFault {
    /// A TRS member is declared alongside `matrix`.
    TrsBesideMatrix {
        /// Stable source node index.
        node_index: usize,
        /// The offending member's glTF spelling.
        member: &'static str,
    },
    /// A last-row `matrix` entry is a number other than the affine one.
    ProjectiveMatrixEntry {
        /// Stable source node index.
        node_index: usize,
        /// Component index inside the column-major `matrix`.
        component: usize,
        /// The authored value.
        value: f64,
        /// The only value glTF 2.0 permits there.
        expected: f64,
    },
    /// A last-row `matrix` entry is not a JSON number at all, so it cannot be
    /// shown to be the affine value.
    UnreadableMatrixEntry {
        /// Stable source node index.
        node_index: usize,
        /// Component index inside the column-major `matrix`.
        component: usize,
    },
}

impl NodeTransformFault {
    /// JSON pointer of the offending member or `matrix` entry.
    pub(crate) fn location(self) -> String {
        match self {
            Self::TrsBesideMatrix { node_index, member } => format!("/nodes/{node_index}/{member}"),
            Self::ProjectiveMatrixEntry {
                node_index,
                component,
                ..
            }
            | Self::UnreadableMatrixEntry {
                node_index,
                component,
            } => format!("/nodes/{node_index}/matrix/{component}"),
        }
    }

    /// The preflight violation kind this fault is reported as.
    fn kind(self) -> GltfCapabilityViolationKind {
        match self {
            Self::TrsBesideMatrix { .. } => GltfCapabilityViolationKind::ConflictingNodeTransform,
            // An entry that is not a readable number is not the affine value
            // either, so it fails closed as the same kind.
            Self::ProjectiveMatrixEntry { .. } | Self::UnreadableMatrixEntry { .. } => {
                GltfCapabilityViolationKind::NonAffineNodeMatrix
            }
        }
    }
}

/// The value `object` declares for `member`, treating an explicit JSON `null`
/// as no declaration at all.
///
/// `serde_json` reports `"matrix": null` as `Some(Value::Null)`, while the
/// typed glTF parse deserializes the same member into `Option<[f32; 16]>` as
/// `None`. A raw-JSON walker asking only whether the key is *present*
/// therefore disagrees with the typed parse about what the node declared: it
/// reads `{"matrix": null, "translation": [...]}` as a node declaring both,
/// and refuses a document the typed parse reads as a plain TRS node — naming
/// the innocent `translation` as the offender.
///
/// Every walker deciding whether a node authored a transform goes through
/// here, so the gate, the rewriter's guard and [`crate::scale`]'s rewrite
/// selection cannot disagree about it. Presence checks whose only outcome is
/// a fail-closed refusal — `/nodes/*/camera` and `/nodes/*/weights` — are
/// deliberately left key-based: over-refusing a `null` there costs a source
/// nothing that could have converted, while over-refusing a transform member
/// costs a source that converts correctly.
pub(crate) fn declared<'a>(object: &'a Value, member: &str) -> Option<&'a Value> {
    object.get(member).filter(|value| !value.is_null())
}

/// Every glTF 2.0 node-transform contract violation in `nodes`, in node order
/// and, within a node, TRS members before `matrix` entries.
///
/// The `gltf` crate parses both shapes, so neither is refused by the typed
/// parse and neither is a wrong answer on schema-valid input:
///
/// * A node declaring `matrix` **and** a TRS member. glTF 2.0 §3.5 makes the
///   two mutually exclusive, and the typed parse silently honours `matrix`
///   while ignoring the TRS members, so a consumer cannot know which the
///   author meant.
/// * A node `matrix` whose last row is not `(0, 0, 0, 1)`. glTF 2.0 requires
///   `matrix` to be decomposable to translation, rotation and scale. The
///   whole-document conversion's `M' = U M U^-1` identity leaves entries 3, 7,
///   11 and 15 alone, which is only correct when they are the affine row: a
///   projective row transforms as `1/q`, so treating it as invariant would
///   emit a matrix that is not the converted transform.
///
/// A `matrix` of the wrong arity fails the typed glTF parse — which
/// deserializes it as `[f32; 16]` — before either caller runs, so shape
/// errors keep their existing owner rather than gaining a second report here.
///
/// A member authored as JSON `null` is not a declaration: see [`declared`].
pub(crate) fn node_transform_faults(nodes: &[Value]) -> Vec<NodeTransformFault> {
    let mut faults = Vec::new();
    for (node_index, node) in nodes.iter().enumerate() {
        let Some(matrix) = declared(node, "matrix") else {
            continue;
        };
        for member in ["translation", "rotation", "scale"] {
            if declared(node, member).is_some() {
                faults.push(NodeTransformFault::TrsBesideMatrix { node_index, member });
            }
        }
        let Some(values) = matrix.as_array().filter(|values| values.len() == 16) else {
            continue;
        };
        for (component, expected) in AFFINE_LAST_ROW {
            match values[component].as_f64() {
                None => faults.push(NodeTransformFault::UnreadableMatrixEntry {
                    node_index,
                    component,
                }),
                Some(value) if value != expected => {
                    faults.push(NodeTransformFault::ProjectiveMatrixEntry {
                        node_index,
                        component,
                        value,
                        expected,
                    });
                }
                Some(_) => {}
            }
        }
    }
    faults
}

fn inventory_nodes(
    root: &Map<String, Value>,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    let Some(nodes) = root.get("nodes").and_then(Value::as_array) else {
        return;
    };
    for fault in node_transform_faults(nodes) {
        violation(violations, fault.kind(), fault.location());
    }
    for (node_index, node) in nodes.iter().enumerate() {
        if !node.is_object() {
            continue;
        }
        // `weights` stays key-based because the raw writer preserves the
        // complete JSON value byte-for-byte; its presence is still an
        // operation-aware capability fact. `camera` remains a rejection.
        // `matrix` below cannot use a key-based check, because there a false
        // positive refuses a source that converts correctly.
        if node.get("weights").is_some() {
            manifest
                .morph_weight_locations
                .push(format!("/nodes/{node_index}/weights"));
        }
        if node.get("camera").is_some() {
            violation(
                violations,
                GltfCapabilityViolationKind::Camera,
                format!("/nodes/{node_index}/camera"),
            );
        }
        if let Some(attributes) = node
            .get("extensions")
            .and_then(|extensions| extensions.get("EXT_mesh_gpu_instancing"))
            .and_then(|extension| extension.get("attributes"))
            .and_then(Value::as_object)
        {
            let mut attributes = attributes
                .iter()
                .map(|(semantic, accessor)| GltfAttributeCapability {
                    semantic: semantic.clone(),
                    accessor_index: as_index(Some(accessor)).unwrap_or(usize::MAX),
                })
                .collect::<Vec<_>>();
            attributes.sort_by(|left, right| left.semantic.cmp(&right.semantic));
            manifest.instancing.push(GltfInstancingCapability {
                node_index,
                attributes,
            });
        }
        manifest.nodes.push(GltfNodeCapability {
            node_index,
            // A key-based check would report a `"matrix": null` node as
            // `Matrix` while the typed parse reads it as `Trs`.
            rest_kind: if declared(node, "matrix").is_some() {
                GltfNodeRestKind::Matrix
            } else {
                GltfNodeRestKind::Trs
            },
            mesh_index: as_index(node.get("mesh")),
            skin_index: as_index(node.get("skin")),
        });
    }
}

fn inventory_animations(
    root: &Map<String, Value>,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    let Some(animations) = root.get("animations").and_then(Value::as_array) else {
        return;
    };
    for (animation_index, animation) in animations.iter().enumerate() {
        let Some(animation) = animation.as_object() else {
            continue;
        };
        let samplers = animation
            .get("samplers")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or_default();
        let channels = animation
            .get("channels")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or_default();
        for (channel_index, channel) in channels.iter().enumerate() {
            let Some(channel) = channel.as_object() else {
                continue;
            };
            let sampler_index = as_index(channel.get("sampler")).unwrap_or(usize::MAX);
            let Some(sampler) = samplers.get(sampler_index).and_then(Value::as_object) else {
                continue;
            };
            let Some(target) = channel.get("target").and_then(Value::as_object) else {
                continue;
            };
            let target_path = target
                .get("path")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned();
            if target_path == "weights" {
                manifest.morph_weight_locations.push(format!(
                    "/animations/{animation_index}/channels/{channel_index}/target/path"
                ));
            }
            let target_node_index = as_index(target.get("node")).unwrap_or(usize::MAX);
            if manifest
                .nodes
                .get(target_node_index)
                .is_some_and(|node| node.rest_kind == GltfNodeRestKind::Matrix)
            {
                violation(
                    violations,
                    GltfCapabilityViolationKind::AnimatedMatrixNode,
                    format!("/animations/{animation_index}/channels/{channel_index}/target"),
                );
            }
            manifest
                .animation_channels
                .push(GltfAnimationChannelCapability {
                    animation_index,
                    channel_index,
                    target_node_index,
                    target_path,
                    interpolation: sampler
                        .get("interpolation")
                        .and_then(Value::as_str)
                        .unwrap_or("LINEAR")
                        .to_owned(),
                    input_accessor_index: as_index(sampler.get("input")).unwrap_or(usize::MAX),
                    output_accessor_index: as_index(sampler.get("output")).unwrap_or(usize::MAX),
                });
        }
    }
}

fn inventory_meshes(
    root: &Map<String, Value>,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    let Some(meshes) = root.get("meshes").and_then(Value::as_array) else {
        return;
    };
    for (mesh_index, mesh) in meshes.iter().enumerate() {
        let Some(mesh) = mesh.as_object() else {
            continue;
        };
        if mesh.contains_key("weights") {
            manifest
                .morph_weight_locations
                .push(format!("/meshes/{mesh_index}/weights"));
        }
        let primitives = mesh
            .get("primitives")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or_default();
        for (primitive_index, primitive) in primitives.iter().enumerate() {
            let Some(primitive) = primitive.as_object() else {
                continue;
            };
            let mode = primitive.get("mode").and_then(Value::as_u64).unwrap_or(4);
            if mode != 4 {
                violation(
                    violations,
                    GltfCapabilityViolationKind::NonTrianglePrimitive,
                    format!("/meshes/{mesh_index}/primitives/{primitive_index}/mode"),
                );
            }
            let mut attributes = primitive
                .get("attributes")
                .and_then(Value::as_object)
                .map(|attributes| {
                    attributes
                        .iter()
                        .map(|(semantic, accessor)| GltfAttributeCapability {
                            semantic: semantic.clone(),
                            accessor_index: as_index(Some(accessor)).unwrap_or(usize::MAX),
                        })
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default();
            attributes.sort_by(|left, right| left.semantic.cmp(&right.semantic));
            for attribute in &attributes {
                let semantic = &attribute.semantic;
                let semantic_pointer = json_pointer_token(semantic);
                let location = format!(
                    "/meshes/{mesh_index}/primitives/{primitive_index}/attributes/{semantic_pointer}"
                );
                if is_secondary_influence(semantic) {
                    violation(
                        violations,
                        GltfCapabilityViolationKind::SecondarySkinInfluences,
                        location,
                    );
                } else if !matches!(
                    semantic.as_str(),
                    "POSITION" | "NORMAL" | "TEXCOORD_0" | "JOINTS_0" | "WEIGHTS_0"
                ) {
                    violation(
                        violations,
                        GltfCapabilityViolationKind::UnsupportedVertexAttribute,
                        location,
                    );
                }
            }
            let morph_target_count = primitive
                .get("targets")
                .and_then(Value::as_array)
                .map_or(0, Vec::len);
            let mut morph_position_accessors = Vec::new();
            let mut unsupported_morph_locations = Vec::new();
            for (target_index, target) in primitive
                .get("targets")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .enumerate()
            {
                let Some(target) = target.as_object() else {
                    continue;
                };
                for (semantic, accessor) in target {
                    let location = format!(
                        "/meshes/{mesh_index}/primitives/{primitive_index}/targets/{target_index}/{}",
                        json_pointer_token(semantic)
                    );
                    if semantic == "POSITION" {
                        if let Some(accessor_index) = as_index(Some(accessor)) {
                            morph_position_accessors.push(accessor_index);
                        }
                    } else {
                        violation(
                            violations,
                            GltfCapabilityViolationKind::MorphTarget,
                            location.clone(),
                        );
                        unsupported_morph_locations.push(location);
                    }
                }
            }
            manifest.primitives.push(GltfPrimitiveCapability {
                mesh_index,
                primitive_index,
                mode,
                attributes,
                morph_target_count,
                morph_position_accessors,
                unsupported_morph_locations,
            });
        }
    }
}

fn is_secondary_influence(semantic: &str) -> bool {
    semantic
        .strip_prefix("JOINTS_")
        .or_else(|| semantic.strip_prefix("WEIGHTS_"))
        .and_then(|index| index.parse::<u32>().ok())
        .is_some_and(|index| index >= 1)
}

fn inventory_skins(
    root: &Map<String, Value>,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    let accessors = root
        .get("accessors")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    let Some(skins) = root.get("skins").and_then(Value::as_array) else {
        return;
    };
    for (skin_index, skin) in skins.iter().enumerate() {
        let Some(skin) = skin.as_object() else {
            continue;
        };
        let joint_count = skin
            .get("joints")
            .and_then(Value::as_array)
            .map_or(0, Vec::len);
        let inverse_bind_accessor_index = as_index(skin.get("inverseBindMatrices"));
        let inverse_bind_count = inverse_bind_accessor_index
            .and_then(|index| accessors.get(index))
            .and_then(|accessor| accessor.get("count"))
            .and_then(Value::as_u64);
        let inverse_bind_readable = inverse_bind_accessor_index
            .and_then(|index| accessors.get(index))
            .and_then(Value::as_object)
            .is_some_and(|accessor| {
                accessor.get("bufferView").and_then(Value::as_u64).is_some()
                    && accessor.get("componentType").and_then(Value::as_u64) == Some(5126)
                    && accessor.get("type").and_then(Value::as_str) == Some("MAT4")
                    && !accessor.contains_key("sparse")
            });
        match (inverse_bind_accessor_index, inverse_bind_count) {
            (None, _) => violation(
                violations,
                GltfCapabilityViolationKind::MissingInverseBinds,
                format!("/skins/{skin_index}/inverseBindMatrices"),
            ),
            (Some(_), Some(0)) => violation(
                violations,
                GltfCapabilityViolationKind::EmptyInverseBindAccessor,
                format!("/skins/{skin_index}/inverseBindMatrices"),
            ),
            (Some(_), Some(count)) if count != joint_count as u64 => violation(
                violations,
                GltfCapabilityViolationKind::InverseBindCountMismatch,
                format!("/skins/{skin_index}/inverseBindMatrices"),
            ),
            (Some(_), _) if !inverse_bind_readable => violation(
                violations,
                GltfCapabilityViolationKind::UnreadableInverseBinds,
                format!("/skins/{skin_index}/inverseBindMatrices"),
            ),
            _ => {}
        }
        manifest.skins.push(GltfSkinCapability {
            skin_index,
            joint_count,
            inverse_bind_accessor_index,
            inverse_bind_count,
        });
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum AccessorUse {
    ScaleBearing,
    Dimensionless,
}

/// Which source object owns one byte range in the disjointness inspection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum RangeOwner {
    /// An accessor's dense element range.
    Accessor(usize),
    /// An accessor's sparse-index element range.
    SparseIndices(usize),
    /// An accessor's sparse-value element range.
    SparseValues(usize),
    /// An `image`'s complete buffer view.
    ImagePayload(usize),
}

impl RangeOwner {
    /// JSON pointer identifying the owner.
    fn location(self) -> String {
        match self {
            Self::Accessor(index) => format!("/accessors/{index}"),
            Self::SparseIndices(index) => {
                format!("/accessors/{index}/sparse/indices/bufferView")
            }
            Self::SparseValues(index) => {
                format!("/accessors/{index}/sparse/values/bufferView")
            }
            Self::ImagePayload(index) => format!("/images/{index}/bufferView"),
        }
    }

    /// The violation kind reported when this owner's range is not disjoint
    /// from a scale-bearing accessor's.
    fn overlap_kind(self) -> GltfCapabilityViolationKind {
        match self {
            Self::Accessor(_) | Self::SparseIndices(_) | Self::SparseValues(_) => {
                GltfCapabilityViolationKind::OverlappingAccessorRanges
            }
            Self::ImagePayload(_) => GltfCapabilityViolationKind::ImagePayloadOverlap,
        }
    }
}

/// One `(buffer, start, end, owner, scale_bearing)` range entry.
type OwnedRange = (usize, usize, usize, RangeOwner, bool);

fn inspect_accessor_layouts(
    root: &Value,
    buffers: &[Vec<u8>],
    uses: &BTreeMap<usize, BTreeSet<AccessorUse>>,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    let Some(root) = root.as_object() else { return };
    let mut ranges: Vec<OwnedRange> = Vec::new();
    let accessors = root
        .get("accessors")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    for accessor_index in 0..accessors.len() {
        let accessor_uses = uses.get(&accessor_index);
        let scale_bearing =
            accessor_uses.is_some_and(|uses| uses.contains(&AccessorUse::ScaleBearing));
        let accessor_ranges = if scale_bearing {
            dense_f32_accessor_range(root, buffers, accessor_index).map(|range| {
                vec![(
                    range.0,
                    range.1,
                    range.2,
                    RangeOwner::Accessor(accessor_index),
                    true,
                )]
            })
        } else if accessor_uses.is_some() {
            accessor_range(root, buffers, accessor_index).map(|range| {
                vec![(
                    range.buffer,
                    range.start,
                    range.end,
                    RangeOwner::Accessor(accessor_index),
                    false,
                )]
            })
        } else {
            preserved_accessor_ranges(root, buffers, accessor_index)
        };
        match accessor_ranges {
            Some(accessor_ranges) => ranges.extend(accessor_ranges),
            None => violation(
                violations,
                GltfCapabilityViolationKind::UnsafeAccessorLayout,
                format!("/accessors/{accessor_index}"),
            ),
        }
    }
    ranges.extend(image_payload_ranges(root));
    ranges.sort_unstable();

    let mut overlapping = BTreeSet::new();
    let mut prior_scale: Option<(usize, usize, RangeOwner)> = None;
    for &(buffer, start, end, owner, scale_bearing) in &ranges {
        if let Some((left_buffer, left_end, left_owner)) = prior_scale
            && left_buffer == buffer
            && start < left_end
        {
            overlapping.insert(left_owner);
            overlapping.insert(owner);
        }
        if scale_bearing
            && prior_scale
                .is_none_or(|(left_buffer, left_end, _)| left_buffer != buffer || end > left_end)
        {
            prior_scale = Some((buffer, end, owner));
        }
    }
    let mut later_scale: Option<(usize, usize, RangeOwner)> = None;
    for &(buffer, start, end, owner, scale_bearing) in ranges.iter().rev() {
        if let Some((right_buffer, right_start, right_owner)) = later_scale
            && right_buffer == buffer
            && right_start < end
        {
            overlapping.insert(owner);
            overlapping.insert(right_owner);
        }
        if scale_bearing
            && later_scale.is_none_or(|(right_buffer, right_start, _)| {
                right_buffer != buffer || start < right_start
            })
        {
            later_scale = Some((buffer, start, owner));
        }
    }
    for owner in overlapping {
        violation(violations, owner.overlap_kind(), owner.location());
    }
}

/// Every byte range owned by an unreferenced accessor.
///
/// Unlike a referenced sparse accessor, which remains an unsupported reader
/// layout, an unreferenced sparse accessor is source payload to preserve. Its
/// optional dense base plus its sparse indices and values therefore enter the
/// same disjointness ledger as ordinary dense accessors. Returning `None`
/// fails closed when a declared span cannot be resolved; an empty vector is a
/// valid accessor with no owned bytes.
fn preserved_accessor_ranges(
    root: &Map<String, Value>,
    buffers: &[Vec<u8>],
    accessor_index: usize,
) -> Option<Vec<OwnedRange>> {
    let accessor = root
        .get("accessors")?
        .as_array()?
        .get(accessor_index)?
        .as_object()?;
    let count: usize = accessor.get("count")?.as_u64()?.try_into().ok()?;
    if count == 0 {
        return Some(Vec::new());
    }
    let Some(sparse) = accessor.get("sparse") else {
        let range = accessor_range(root, buffers, accessor_index)?;
        return Some(vec![(
            range.buffer,
            range.start,
            range.end,
            RangeOwner::Accessor(accessor_index),
            false,
        )]);
    };

    let mut ranges = Vec::with_capacity(3);
    if accessor.get("bufferView").is_some() {
        let range = dense_accessor_range(root, buffers, accessor_index)?;
        ranges.push((
            range.buffer,
            range.start,
            range.end,
            RangeOwner::Accessor(accessor_index),
            false,
        ));
    }

    let sparse = sparse.as_object()?;
    let sparse_count: usize = sparse.get("count")?.as_u64()?.try_into().ok()?;
    if sparse_count == 0 {
        return Some(ranges);
    }
    let indices = sparse.get("indices")?.as_object()?;
    let index_size = match indices.get("componentType")?.as_u64()? {
        5121 => 1,
        5123 => 2,
        5125 => 4,
        _ => return None,
    };
    let indices_range = packed_view_range(
        root,
        buffers,
        as_index(indices.get("bufferView"))?,
        indices
            .get("byteOffset")
            .and_then(Value::as_u64)
            .unwrap_or(0),
        sparse_count,
        index_size,
        index_size,
    )?;
    ranges.push((
        indices_range.0,
        indices_range.1,
        indices_range.2,
        RangeOwner::SparseIndices(accessor_index),
        false,
    ));

    let values = sparse.get("values")?.as_object()?;
    let component_size = component_size(accessor.get("componentType")?.as_u64()?)?;
    let element_layout = accessor_element_layout(accessor.get("type")?.as_str()?, component_size)?;
    let values_range = packed_view_range(
        root,
        buffers,
        as_index(values.get("bufferView"))?,
        values
            .get("byteOffset")
            .and_then(Value::as_u64)
            .unwrap_or(0),
        sparse_count,
        element_layout.stride,
        element_layout.terminal_size,
    )?;
    ranges.push((
        values_range.0,
        values_range.1,
        values_range.2,
        RangeOwner::SparseValues(accessor_index),
        false,
    ));
    Some(ranges)
}

/// Resolve one tightly packed walk within a declared buffer view.
fn packed_view_range(
    root: &Map<String, Value>,
    buffers: &[Vec<u8>],
    view_index: usize,
    relative_offset: u64,
    count: usize,
    element_stride: usize,
    terminal_size: usize,
) -> Option<(usize, usize, usize)> {
    let view = root
        .get("bufferViews")?
        .as_array()?
        .get(view_index)?
        .as_object()?;
    let buffer_index = as_index(view.get("buffer"))?;
    let buffer = buffers.get(buffer_index)?;
    let view_offset: usize = view
        .get("byteOffset")
        .and_then(Value::as_u64)
        .unwrap_or(0)
        .try_into()
        .ok()?;
    let view_length: usize = view.get("byteLength")?.as_u64()?.try_into().ok()?;
    if view_offset.checked_add(view_length)? > buffer.len() {
        return None;
    }
    let relative_offset: usize = relative_offset.try_into().ok()?;
    let relative_end = relative_offset
        .checked_add(count.checked_sub(1)?.checked_mul(element_stride)?)?
        .checked_add(terminal_size)?;
    if relative_end > view_length {
        return None;
    }
    let start = view_offset.checked_add(relative_offset)?;
    let end = view_offset.checked_add(relative_end)?;
    Some((buffer_index, start, end))
}

/// The byte range every `image` reads directly from a buffer view.
///
/// # Why images, and why only images
///
/// An `image` is the one consumer in the supported subset that reads a
/// `bufferView` without ever becoming an accessor, so its bytes are invisible
/// to a disjointness proof built from accessor ranges alone. The complete
/// enumeration of `bufferView` consumers in glTF 2.0 core is:
///
/// | Consumer | Treatment |
/// |---|---|
/// | `/accessors/*/bufferView` | Every accessor is ranged by [`inspect_accessor_layouts`] above, whether referenced or not. |
/// | `/accessors/*/sparse/indices/bufferView`, `/accessors/*/sparse/values/bufferView` | Ranged for unreferenced accessors. A referenced sparse accessor remains an `UnsafeAccessorLayout` refusal and never reaches a rewrite. |
/// | `/images/*/bufferView` | Ranged here. |
/// | Extension payloads such as `EXT_meshopt_compression` or `KHR_draco_mesh_compression` | Out of range: this crate registers no extension handler, so every extension declaration *and* every extension payload is already an `ExtensionDeclaration`/`ExtensionPayload` violation. |
///
/// # Bounds
///
/// The range is taken from the declared view, without requiring it to fit the
/// resolved buffer: a view running past the buffer still aliases whatever real
/// bytes it starts on. Where `usize` is narrower than `u64`, a declared value
/// past `usize::MAX` clamps, and neither clamp can hide a real overlap.
/// [`accessor_range`] admits a range only when its end is within the resolved
/// buffer's length, so every range compared against ends below `usize::MAX`: a
/// start large enough to clamp is already past all of them, and a clamped end
/// only widens the image range.
fn image_payload_ranges(root: &Map<String, Value>) -> Vec<OwnedRange> {
    let Some(images) = root.get("images").and_then(Value::as_array) else {
        return Vec::new();
    };
    let buffer_views = root
        .get("bufferViews")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    let mut out = Vec::new();
    for (image_index, image) in images.iter().enumerate() {
        let Some(view_index) = as_index(image.get("bufferView")) else {
            continue;
        };
        // An out-of-range index is an `IndexOutOfBounds` validation error,
        // which `validate_document` raises before this inspection runs.
        let Some(view) = buffer_views.get(view_index).and_then(Value::as_object) else {
            continue;
        };
        let Some(buffer) = as_index(view.get("buffer")) else {
            continue;
        };
        let start = clamped_usize(view.get("byteOffset").and_then(Value::as_u64).unwrap_or(0));
        let end = start.saturating_add(clamped_usize(
            view.get("byteLength").and_then(Value::as_u64).unwrap_or(0),
        ));
        // An empty view shares no byte with anything under the half-open
        // comparison every range here uses, so it is dropped rather than
        // ranged. [`crate::scale::reject_image_payload_overlap`] skips the
        // same shape, so the gate and the guard give one answer for it.
        if start < end {
            out.push((
                buffer,
                start,
                end,
                RangeOwner::ImagePayload(image_index),
                false,
            ));
        }
    }
    out
}

fn clamped_usize(value: u64) -> usize {
    usize::try_from(value).unwrap_or(usize::MAX)
}

fn inspect_accessor_uses(
    root: &Value,
    violations: &mut Vec<GltfCapabilityViolation>,
) -> BTreeMap<usize, BTreeSet<AccessorUse>> {
    let Some(root) = root.as_object() else {
        return BTreeMap::new();
    };
    let uses = collect_accessor_uses(root);
    for (accessor_index, accessor_uses) in &uses {
        if accessor_uses.len() > 1 {
            violation(
                violations,
                GltfCapabilityViolationKind::ConflictingAccessorUse,
                format!("/accessors/{accessor_index}"),
            );
        }
    }
    uses
}

fn collect_accessor_uses(root: &Map<String, Value>) -> BTreeMap<usize, BTreeSet<AccessorUse>> {
    let mut uses: BTreeMap<usize, BTreeSet<AccessorUse>> = BTreeMap::new();
    let mut add = |index: Option<usize>, kind| {
        if let Some(index) = index {
            uses.entry(index).or_default().insert(kind);
        }
    };
    if let Some(meshes) = root.get("meshes").and_then(Value::as_array) {
        for mesh in meshes {
            let Some(primitives) = mesh.get("primitives").and_then(Value::as_array) else {
                continue;
            };
            for primitive in primitives {
                if let Some(attributes) = primitive.get("attributes").and_then(Value::as_object) {
                    for (semantic, index) in attributes {
                        add(
                            as_index(Some(index)),
                            if semantic == "POSITION" {
                                AccessorUse::ScaleBearing
                            } else {
                                AccessorUse::Dimensionless
                            },
                        );
                    }
                }
                add(
                    as_index(primitive.get("indices")),
                    AccessorUse::Dimensionless,
                );
                if let Some(targets) = primitive.get("targets").and_then(Value::as_array) {
                    for target in targets {
                        if let Some(target) = target.as_object() {
                            for (semantic, index) in target {
                                add(
                                    as_index(Some(index)),
                                    if semantic == "POSITION" {
                                        AccessorUse::ScaleBearing
                                    } else {
                                        AccessorUse::Dimensionless
                                    },
                                );
                            }
                        }
                    }
                }
            }
        }
    }
    if let Some(skins) = root.get("skins").and_then(Value::as_array) {
        for skin in skins {
            add(
                as_index(skin.get("inverseBindMatrices")),
                AccessorUse::ScaleBearing,
            );
        }
    }
    if let Some(animations) = root.get("animations").and_then(Value::as_array) {
        for animation in animations {
            let samplers = animation
                .get("samplers")
                .and_then(Value::as_array)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let channels = animation
                .get("channels")
                .and_then(Value::as_array)
                .map(Vec::as_slice)
                .unwrap_or_default();
            let referenced: BTreeSet<usize> = channels
                .iter()
                .filter_map(|channel| as_index(channel.get("sampler")))
                .collect();
            for (sampler_index, sampler) in samplers.iter().enumerate() {
                add(as_index(sampler.get("input")), AccessorUse::Dimensionless);
                if !referenced.contains(&sampler_index) {
                    add(as_index(sampler.get("output")), AccessorUse::Dimensionless);
                }
            }
            for channel in channels {
                let sampler_index = as_index(channel.get("sampler")).unwrap_or(usize::MAX);
                let Some(sampler) = samplers.get(sampler_index) else {
                    continue;
                };
                let path = channel
                    .get("target")
                    .and_then(|target| target.get("path"))
                    .and_then(Value::as_str);
                add(
                    as_index(sampler.get("output")),
                    if path == Some("translation") {
                        AccessorUse::ScaleBearing
                    } else {
                        AccessorUse::Dimensionless
                    },
                );
            }
        }
    }
    uses
}

/// The `(buffer, start, end)` byte range of a dense, non-normalized,
/// non-sparse, 4-byte-aligned `f32` accessor, or `None` when the accessor is
/// not in that shape.
///
/// Shared with [`crate::scale`]: the byte rewriter must resolve exactly the
/// same range this preflight vouched for, so re-deriving it there would let
/// the two definitions drift apart.
pub(crate) fn dense_f32_accessor_range(
    root: &Map<String, Value>,
    buffers: &[Vec<u8>],
    accessor_index: usize,
) -> Option<(usize, usize, usize)> {
    let accessors = root.get("accessors")?.as_array()?;
    let accessor = accessors.get(accessor_index)?.as_object()?;
    if accessor.get("componentType")?.as_u64()? != 5126
        || accessor.get("normalized").and_then(Value::as_bool) == Some(true)
        || accessor.contains_key("sparse")
    {
        return None;
    }
    let range = accessor_range(root, buffers, accessor_index)?;
    if range.stride != range.element_stride || !range.start.is_multiple_of(4) {
        return None;
    }
    Some((range.buffer, range.start, range.end))
}

/// The complete resolved range of any dense used accessor, irrespective of
/// component type or stride.
///
/// Rest/bind rewriting uses this only for operation-specific alias checks:
/// a rewritten `f32` accessor must not overlap bytes owned by a preserved
/// integer attribute, index accessor, or animation sampler. Keeping range
/// arithmetic here gives that guard exactly the same layout interpretation
/// as the common preflight.
pub(crate) fn resolved_accessor_range(
    root: &Map<String, Value>,
    buffers: &[Vec<u8>],
    accessor_index: usize,
) -> Option<(usize, usize, usize)> {
    accessor_range(root, buffers, accessor_index)
        .map(|range| (range.buffer, range.start, range.end))
}

#[derive(Debug, Clone, Copy)]
struct AccessorRange {
    buffer: usize,
    start: usize,
    end: usize,
    stride: usize,
    element_stride: usize,
}

fn accessor_range(
    root: &Map<String, Value>,
    buffers: &[Vec<u8>],
    accessor_index: usize,
) -> Option<AccessorRange> {
    let accessor = root
        .get("accessors")?
        .as_array()?
        .get(accessor_index)?
        .as_object()?;
    if accessor.contains_key("sparse") {
        return None;
    }
    dense_accessor_range(root, buffers, accessor_index)
}

/// The dense base range of an accessor, including one that also declares
/// sparse replacement data.
fn dense_accessor_range(
    root: &Map<String, Value>,
    buffers: &[Vec<u8>],
    accessor_index: usize,
) -> Option<AccessorRange> {
    let accessors = root.get("accessors")?.as_array()?;
    let buffer_views = root.get("bufferViews")?.as_array()?;
    let accessor = accessors.get(accessor_index)?.as_object()?;
    let component_size = component_size(accessor.get("componentType")?.as_u64()?)?;
    let element_layout = accessor_element_layout(accessor.get("type")?.as_str()?, component_size)?;
    let count: usize = accessor.get("count")?.as_u64()?.try_into().ok()?;
    if count == 0 {
        return None;
    }
    let view_index = as_index(accessor.get("bufferView"))?;
    let view = buffer_views.get(view_index)?.as_object()?;
    let buffer_index = as_index(view.get("buffer"))?;
    let buffer = buffers.get(buffer_index)?;
    let view_offset: usize = view
        .get("byteOffset")
        .and_then(Value::as_u64)
        .unwrap_or(0)
        .try_into()
        .ok()?;
    let view_length: usize = view.get("byteLength")?.as_u64()?.try_into().ok()?;
    if view_offset.checked_add(view_length)? > buffer.len() {
        return None;
    }
    let accessor_offset: usize = accessor
        .get("byteOffset")
        .and_then(Value::as_u64)
        .unwrap_or(0)
        .try_into()
        .ok()?;
    let stride: usize = view
        .get("byteStride")
        .and_then(Value::as_u64)
        .unwrap_or(element_layout.stride as u64)
        .try_into()
        .ok()?;
    if stride < element_layout.stride {
        return None;
    }
    let relative_end = accessor_offset
        .checked_add(count.checked_sub(1)?.checked_mul(stride)?)?
        .checked_add(element_layout.terminal_size)?;
    if relative_end > view_length {
        return None;
    }
    let start = view_offset.checked_add(accessor_offset)?;
    let end = view_offset.checked_add(relative_end)?;
    (end <= buffer.len()).then_some(AccessorRange {
        buffer: buffer_index,
        start,
        end,
        stride,
        element_stride: element_layout.stride,
    })
}

fn component_size(component_type: u64) -> Option<usize> {
    match component_type {
        5120 | 5121 => Some(1),
        5122 | 5123 => Some(2),
        5125 | 5126 => Some(4),
        _ => None,
    }
}

/// The stored spacing and terminal occupied extent of one accessor element.
///
/// Integer `MAT2` and `MAT3` columns begin on four-byte boundaries. That
/// padding contributes to the stride between elements, but glTF permits the
/// trailing padding after the final matrix column to be omitted when no data
/// follows. Keeping the two lengths separate admits that compact final
/// element without weakening the bounds on preceding elements.
#[derive(Debug, Clone, Copy)]
struct AccessorElementLayout {
    stride: usize,
    terminal_size: usize,
}

fn accessor_element_layout(
    accessor_type: &str,
    component_size: usize,
) -> Option<AccessorElementLayout> {
    let (columns, rows, matrix) = match accessor_type {
        "SCALAR" => (1usize, 1usize, false),
        "VEC2" => (1, 2, false),
        "VEC3" => (1, 3, false),
        "VEC4" => (1, 4, false),
        "MAT2" => (2, 2, true),
        "MAT3" => (3, 3, true),
        "MAT4" => (4, 4, true),
        _ => return None,
    };
    let column_size = rows.checked_mul(component_size)?;
    let stored_column_size = if matrix {
        column_size.checked_add(3)? & !3
    } else {
        column_size
    };
    let stride = columns.checked_mul(stored_column_size)?;
    let terminal_size = columns
        .checked_sub(1)?
        .checked_mul(stored_column_size)?
        .checked_add(column_size)?;
    Some(AccessorElementLayout {
        stride,
        terminal_size,
    })
}

fn inspect_schema_members(
    value: &Value,
    pointer: &str,
    manifest: &mut GltfCapabilityManifest,
    violations: &mut Vec<GltfCapabilityViolation>,
) {
    match value {
        Value::Object(object) => {
            if object.get("extras").is_some_and(|value| !value.is_null()) {
                let location = format!("{pointer}/extras");
                manifest.extras_locations.push(location.clone());
                violation(violations, GltfCapabilityViolationKind::Extras, location);
            }
            if let Some(extensions) = object.get("extensions").and_then(Value::as_object) {
                for name in extensions.keys() {
                    let location = json_pointer_child(&format!("{pointer}/extensions"), name);
                    manifest.extensions.push(name.clone());
                    manifest.extension_locations.push(location.clone());
                    violation(
                        violations,
                        match name.as_str() {
                            "KHR_lights_punctual" => GltfCapabilityViolationKind::Light,
                            "EXT_mesh_gpu_instancing" => GltfCapabilityViolationKind::Instancing,
                            _ => GltfCapabilityViolationKind::ExtensionPayload,
                        },
                        location,
                    );
                }
            }
            if let Some(allowed) = allowed_members(pointer) {
                for key in object.keys() {
                    if !allowed.contains(&key.as_str()) {
                        let location = json_pointer_child(pointer, key);
                        manifest.unknown_member_locations.push(location.clone());
                        violation(
                            violations,
                            GltfCapabilityViolationKind::UnknownJsonMember,
                            location,
                        );
                    }
                }
            }
            for (key, child) in object {
                if key == "extras" || key == "extensions" {
                    continue;
                }
                inspect_schema_members(
                    child,
                    &json_pointer_child(pointer, key),
                    manifest,
                    violations,
                );
            }
        }
        Value::Array(values) => {
            for (index, child) in values.iter().enumerate() {
                inspect_schema_members(child, &format!("{pointer}/{index}"), manifest, violations);
            }
        }
        _ => {}
    }
}

fn json_pointer_child(pointer: &str, token: &str) -> String {
    format!("{pointer}/{}", json_pointer_token(token))
}

fn json_pointer_token(token: &str) -> String {
    token.replace('~', "~0").replace('/', "~1")
}

fn allowed_members(pointer: &str) -> Option<&'static [&'static str]> {
    const ROOT: &[&str] = &[
        "accessors",
        "animations",
        "asset",
        "buffers",
        "bufferViews",
        "cameras",
        "extensions",
        "extensionsRequired",
        "extensionsUsed",
        "extras",
        "images",
        "materials",
        "meshes",
        "nodes",
        "samplers",
        "scene",
        "scenes",
        "skins",
        "textures",
    ];
    const ASSET: &[&str] = &[
        "copyright",
        "extensions",
        "extras",
        "generator",
        "minVersion",
        "version",
    ];
    const ACCESSOR: &[&str] = &[
        "bufferView",
        "byteOffset",
        "componentType",
        "count",
        "extensions",
        "extras",
        "max",
        "min",
        "name",
        "normalized",
        "sparse",
        "type",
    ];
    const BUFFER: &[&str] = &["byteLength", "extensions", "extras", "name", "uri"];
    const VIEW: &[&str] = &[
        "buffer",
        "byteLength",
        "byteOffset",
        "byteStride",
        "extensions",
        "extras",
        "name",
        "target",
    ];
    const NODE: &[&str] = &[
        "camera",
        "children",
        "extensions",
        "extras",
        "matrix",
        "mesh",
        "name",
        "rotation",
        "scale",
        "skin",
        "translation",
        "weights",
    ];
    const MESH: &[&str] = &["extensions", "extras", "name", "primitives", "weights"];
    const PRIMITIVE: &[&str] = &[
        "attributes",
        "extensions",
        "extras",
        "indices",
        "material",
        "mode",
        "targets",
    ];
    const ANIMATION: &[&str] = &["channels", "extensions", "extras", "name", "samplers"];
    const CHANNEL: &[&str] = &["extensions", "extras", "sampler", "target"];
    const TARGET: &[&str] = &["extensions", "extras", "node", "path"];
    const ANIM_SAMPLER: &[&str] = &["extensions", "extras", "input", "interpolation", "output"];
    const SKIN: &[&str] = &[
        "extensions",
        "extras",
        "inverseBindMatrices",
        "joints",
        "name",
        "skeleton",
    ];
    const SCENE: &[&str] = &["extensions", "extras", "name", "nodes"];
    const IMAGE: &[&str] = &[
        "bufferView",
        "extensions",
        "extras",
        "mimeType",
        "name",
        "uri",
    ];
    const TEXTURE: &[&str] = &["extensions", "extras", "name", "sampler", "source"];
    const SAMPLER: &[&str] = &[
        "extensions",
        "extras",
        "magFilter",
        "minFilter",
        "name",
        "wrapS",
        "wrapT",
    ];
    const CAMERA: &[&str] = &[
        "extensions",
        "extras",
        "name",
        "orthographic",
        "perspective",
        "type",
    ];
    const MATERIAL: &[&str] = &[
        "alphaCutoff",
        "alphaMode",
        "doubleSided",
        "emissiveFactor",
        "emissiveTexture",
        "extensions",
        "extras",
        "name",
        "normalTexture",
        "occlusionTexture",
        "pbrMetallicRoughness",
    ];
    const PBR: &[&str] = &[
        "baseColorFactor",
        "baseColorTexture",
        "extensions",
        "extras",
        "metallicFactor",
        "metallicRoughnessTexture",
        "roughnessFactor",
    ];
    const TEXTURE_INFO: &[&str] = &["extensions", "extras", "index", "texCoord"];
    const NORMAL_TEXTURE_INFO: &[&str] = &["extensions", "extras", "index", "scale", "texCoord"];
    const OCCLUSION_TEXTURE_INFO: &[&str] =
        &["extensions", "extras", "index", "strength", "texCoord"];
    const PERSPECTIVE: &[&str] = &[
        "aspectRatio",
        "extensions",
        "extras",
        "yfov",
        "zfar",
        "znear",
    ];
    const ORTHOGRAPHIC: &[&str] = &["extensions", "extras", "xmag", "ymag", "zfar", "znear"];
    const SPARSE: &[&str] = &["count", "extensions", "extras", "indices", "values"];
    const SPARSE_INDICES: &[&str] = &[
        "bufferView",
        "byteOffset",
        "componentType",
        "extensions",
        "extras",
    ];
    const SPARSE_VALUES: &[&str] = &["bufferView", "byteOffset", "extensions", "extras"];
    if pointer.is_empty() {
        Some(ROOT)
    } else if pointer == "/asset" {
        Some(ASSET)
    } else if indexed_member(pointer, "/accessors/") {
        Some(ACCESSOR)
    } else if indexed_member(pointer, "/buffers/") {
        Some(BUFFER)
    } else if indexed_member(pointer, "/bufferViews/") {
        Some(VIEW)
    } else if indexed_member(pointer, "/nodes/") {
        Some(NODE)
    } else if indexed_member(pointer, "/meshes/") {
        Some(MESH)
    } else if indexed_nested_member(pointer, "/meshes/", "/primitives/") {
        Some(PRIMITIVE)
    } else if indexed_member(pointer, "/animations/") {
        Some(ANIMATION)
    } else if indexed_nested_member(pointer, "/animations/", "/channels/") {
        Some(CHANNEL)
    } else if pointer.contains("/animations/") && pointer.ends_with("/target") {
        Some(TARGET)
    } else if indexed_nested_member(pointer, "/animations/", "/samplers/") {
        Some(ANIM_SAMPLER)
    } else if indexed_member(pointer, "/skins/") {
        Some(SKIN)
    } else if indexed_member(pointer, "/scenes/") {
        Some(SCENE)
    } else if indexed_member(pointer, "/images/") {
        Some(IMAGE)
    } else if indexed_member(pointer, "/textures/") {
        Some(TEXTURE)
    } else if indexed_member(pointer, "/samplers/") {
        Some(SAMPLER)
    } else if indexed_member(pointer, "/cameras/") {
        Some(CAMERA)
    } else if indexed_member(pointer, "/materials/") {
        Some(MATERIAL)
    } else if pointer.contains("/materials/") && pointer.ends_with("/pbrMetallicRoughness") {
        Some(PBR)
    } else if pointer.contains("/materials/")
        && (pointer.ends_with("/baseColorTexture")
            || pointer.ends_with("/metallicRoughnessTexture")
            || pointer.ends_with("/emissiveTexture"))
    {
        Some(TEXTURE_INFO)
    } else if pointer.contains("/materials/") && pointer.ends_with("/normalTexture") {
        Some(NORMAL_TEXTURE_INFO)
    } else if pointer.contains("/materials/") && pointer.ends_with("/occlusionTexture") {
        Some(OCCLUSION_TEXTURE_INFO)
    } else if pointer.contains("/cameras/") && pointer.ends_with("/perspective") {
        Some(PERSPECTIVE)
    } else if pointer.contains("/cameras/") && pointer.ends_with("/orthographic") {
        Some(ORTHOGRAPHIC)
    } else if pointer.contains("/accessors/") && pointer.ends_with("/sparse") {
        Some(SPARSE)
    } else if pointer.contains("/accessors/") && pointer.ends_with("/sparse/indices") {
        Some(SPARSE_INDICES)
    } else if pointer.contains("/accessors/") && pointer.ends_with("/sparse/values") {
        Some(SPARSE_VALUES)
    } else {
        None
    }
}

fn indexed_member(pointer: &str, prefix: &str) -> bool {
    pointer
        .strip_prefix(prefix)
        .is_some_and(|suffix| !suffix.is_empty() && !suffix.contains('/'))
}

fn indexed_nested_member(pointer: &str, prefix: &str, nested: &str) -> bool {
    let Some(suffix) = pointer.strip_prefix(prefix) else {
        return false;
    };
    let Some((outer, inner)) = suffix.split_once(nested) else {
        return false;
    };
    !outer.is_empty() && !outer.contains('/') && !inner.is_empty() && !inner.contains('/')
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn accessor_use_inventory_claims_orphan_sampler_fields_without_self_conflicting_channels() {
        let root = json!({
            "animations": [{
                "samplers": [
                    { "input": 1, "output": 2 },
                    { "input": 3, "output": 4 }
                ],
                "channels": [{
                    "sampler": 0,
                    "target": { "node": 0, "path": "translation" }
                }]
            }]
        });
        let uses = collect_accessor_uses(root.as_object().expect("root"));
        assert_eq!(uses[&1], BTreeSet::from([AccessorUse::Dimensionless]));
        assert_eq!(uses[&2], BTreeSet::from([AccessorUse::ScaleBearing]));
        assert_eq!(uses[&3], BTreeSet::from([AccessorUse::Dimensionless]));
        assert_eq!(uses[&4], BTreeSet::from([AccessorUse::Dimensionless]));
    }
}