threers 0.1.0

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
//! Turning a layer into a scene, and a scene back into a layer.
//!
//! USD's geometry model and [`BufferGeometry`]'s differ in two ways that matter,
//! and both are resolved here rather than being pushed onto the caller:
//!
//! - **Faces are arbitrary polygons.** `faceVertexCounts` says how many corners
//!   each face has; a `BufferGeometry` holds triangles. Faces are fanned, and
//!   which triangles were one face is kept in [`BufferGeometry::polygons`].
//! - **Primvars can be per-face-corner.** A `faceVarying` normal or UV gives a
//!   different value to the same point depending on which face is using it,
//!   which an indexed buffer cannot express. When any primvar is face-varying
//!   the mesh is expanded to unindexed triangles, which is the only lossless
//!   reading of it.

use crate::animation::{AnimationClip, KeyframeTrack, TrackTarget};
use crate::core::{
    BufferAttribute, BufferGeometry, Mesh, Object3D, ObjectArena, ObjectId, ObjectKind,
};
use crate::materials::{Material, StandardMaterial};
use crate::math::{Color, Matrix4, Quaternion, Vector3};

use super::parse::{UsdLayer, UsdPrim, UsdProperty};
use super::schemas::{self, UsdCamera};
use super::shade;
use super::skel::{self, UsdSkeleton};
use super::subdiv;
use super::usdz::UsdzArchive;
use super::value::UsdValue;
use crate::core::Skeleton;
use crate::textures::{Texture, TextureFormat, TextureWrap};
use std::rc::Rc;

/// A USD layer as a scene graph.
pub struct UsdScene {
    pub roots: Vec<ObjectId>,
    pub arena: ObjectArena,
    /// `metersPerUnit` from the layer, for callers that care what a unit was.
    pub meters_per_unit: f32,
    /// `upAxis` — `Y` unless the layer says `Z`.
    pub up_axis: char,
    /// One clip holding every animated transform in the layer, or nothing if
    /// the layer is static. USD has no notion of separate named animations
    /// within a layer the way glTF does — the layer *is* the animation — so
    /// there is at most one.
    pub animations: Vec<AnimationClip>,
    /// The cameras on the stage. Nothing in `ObjectKind` is a camera, so they
    /// come back beside the graph, each naming the node that places it.
    pub cameras: Vec<UsdCamera>,
    /// The skeletons, in the order they were found. A skinned mesh holds its
    /// own copy; these are here for a caller that wants to pose one.
    pub skeletons: Vec<Skeleton>,
    /// The blend shapes each mesh carries, by prim name.
    ///
    /// `Mesh` holds the influences but has nowhere for the targets, so they
    /// come back beside the graph the way the cameras and textures do.
    pub morph_targets: Vec<(String, crate::core::MorphAttributes)>,
    /// The textures each mesh's material asked for, by prim name.
    ///
    /// Decoding an image needs a decoder and the files beside the layer,
    /// neither of which belongs in a scene-description reader — so what the
    /// material wants is reported and the caller loads it.
    pub textures: Vec<(String, Vec<shade::TextureRequest>)>,
}

/// What to do while turning a layer into a scene.
#[derive(Debug, Clone, Default)]
pub struct SceneOptions {
    /// How many times to refine meshes that are subdivision surfaces.
    ///
    /// Zero — the default — draws the control cage, which is what every
    /// real-time loader does and what this crate did before the option
    /// existed. It is *not* what the file says: `subdivisionScheme` defaults
    /// to `catmullClark`, so most meshes are surfaces whose points are only a
    /// cage. One level is usually enough to look right; each one multiplies
    /// the face count by four, which is why nothing is refined unasked.
    pub subdivision_level: usize,
    /// Draw `purpose = "guide"` geometry, which is normally for the rigger.
    pub show_guides: bool,
    /// Draw `purpose = "proxy"` stand-ins alongside the real geometry.
    pub show_proxies: bool,
}

/// Build a scene from a parsed layer.
///
/// An animated layer is built at the first frame of its time range, and the
/// animation comes back alongside as a clip.
pub fn to_scene(layer: &UsdLayer) -> UsdScene {
    let start = layer
        .time_range()
        .or_else(|| layer.sampled_time_range())
        .map(|(start, _)| start)
        .unwrap_or(0.0);
    to_scene_at(layer, start)
}

/// Build a scene showing one instant of the layer.
pub fn to_scene_at(layer: &UsdLayer, time: f64) -> UsdScene {
    to_scene_with(layer, time, &SceneOptions::default())
}

/// Build a scene at an instant, with the options spelled out.
pub fn to_scene_with(layer: &UsdLayer, time: f64, options: &SceneOptions) -> UsdScene {
    // Resolve once up front so nothing below has to know about time.
    let resolved = layer.at_time(time);
    let mut arena = ObjectArena::new();
    let mut roots = Vec::new();
    let mut placed = Vec::new();
    let mut cameras = Vec::new();
    let mut skeletons = Vec::new();
    let mut skeleton_clips = Vec::new();
    let mut texture_requests: Vec<(String, Vec<shade::TextureRequest>)> = Vec::new();
    let mut morph_targets: Vec<(String, crate::core::MorphAttributes)> = Vec::new();
    for (prim, source) in resolved.prims.iter().zip(&layer.prims) {
        let mut context = Build {
            layer: &resolved,
            source_layer: layer,
            placed: &mut placed,
            cameras: &mut cameras,
            skeletons: &mut skeletons,
            clips: &mut skeleton_clips,
            rate: layer.time_codes_per_second(),
            options,
            skeleton_animation: None,
            textures: &mut texture_requests,
            morphs: &mut morph_targets,
            skeleton: None,
        };
        if let Some(id) = build(prim, &mut arena, source, "", &mut context) {
            roots.push(id);
        }
    }
    let mut animations: Vec<AnimationClip> = clip(layer, &placed).into_iter().collect();
    // A skeleton is driven by a `SkelAnimation` of its own, which keys every
    // joint at once rather than one prim at a time.
    animations.extend(skeleton_clips);
    UsdScene {
        roots,
        arena,
        meters_per_unit: layer.meters_per_unit(),
        up_axis: layer.up_axis(),
        animations,
        cameras,
        skeletons,
        morph_targets,
        textures: texture_requests
            .into_iter()
            .filter(|(_, t)| !t.is_empty())
            .collect(),
    }
}

/// Turn every animated transform in the layer into one clip.
///
/// Each prim's whole `xformOpOrder` stack is evaluated at every time any of
/// its ops is keyed at, then decomposed. Going through the stack rather than
/// translating op by op means a rotation expressed as `rotateXYZ` and one
/// expressed as `orient` produce the same track, and a prim whose translate
/// and rotate are keyed on different frames still animates correctly.
fn clip(layer: &UsdLayer, placed: &[(ObjectId, UsdPrim)]) -> Option<AnimationClip> {
    let rate = layer.time_codes_per_second();
    let mut tracks = Vec::new();
    let mut span: Option<(f64, f64)> = None;

    for (id, prim) in placed {
        let mut times = keyed_times(prim);
        if times.is_empty() {
            continue;
        }
        times.sort_by(|a, b| a.total_cmp(b));
        times.dedup();

        let sampled: Vec<_> = times
            .iter()
            .map(|t| transform_of(&resolve_prim(prim, *t)))
            .collect();
        let seconds: Vec<f32> = times.iter().map(|t| (t / rate) as f32).collect();
        if let (Some(first), Some(last)) = (times.first(), times.last()) {
            span = Some(match span {
                None => (*first, *last),
                Some((lo, hi)) => (lo.min(*first), hi.max(*last)),
            });
        }

        // A channel that never changes is not worth a track; a static scale on
        // an animated prim would otherwise cost as much as the motion does.
        let positions: Vec<_> = sampled.iter().map(|t| t.0).collect();
        if varies(&positions, |a, b| a.distance_to(*b) > 1e-6) {
            tracks.push(KeyframeTrack::vector(
                *id,
                TrackTarget::Position,
                seconds.clone(),
                positions,
            ));
        }
        let rotations: Vec<_> = sampled.iter().map(|t| t.1).collect();
        if varies(&rotations, |a, b| {
            (a.x - b.x).abs() > 1e-6
                || (a.y - b.y).abs() > 1e-6
                || (a.z - b.z).abs() > 1e-6
                || (a.w - b.w).abs() > 1e-6
        }) {
            tracks.push(KeyframeTrack::quaternion(
                *id,
                TrackTarget::Quaternion,
                seconds.clone(),
                rotations,
            ));
        }
        let scales: Vec<_> = sampled.iter().map(|t| t.2).collect();
        if varies(&scales, |a, b| a.distance_to(*b) > 1e-6) {
            tracks.push(KeyframeTrack::vector(
                *id,
                TrackTarget::Scale,
                seconds,
                scales,
            ));
        }
    }

    if tracks.is_empty() {
        return None;
    }
    // The layer's declared range wins over what the samples happen to cover,
    // because a layer may hold a pose past its last key.
    let (start, end) = layer.time_range().or(span).unwrap_or((0.0, 0.0));
    let duration = ((end - start) / rate).max(0.0) as f32;
    Some(AnimationClip::new("usd", duration, tracks))
}

fn varies<T: Copy>(values: &[T], differs: impl Fn(&T, &T) -> bool) -> bool {
    values.windows(2).any(|w| differs(&w[0], &w[1]))
}

/// A refined cage as a geometry: positions and topology only.
///
/// The primvars are deliberately dropped. A normal or a UV authored per corner
/// of the control cage does not index the refined mesh, and carrying it across
/// would attach the wrong value to the wrong vertex — worse than recomputing
/// the normals, which is what happens instead.
fn refined_geometry(
    points: Vec<f32>,
    counts: Vec<u32>,
    indices: Vec<u32>,
    prim: &UsdPrim,
) -> Option<BufferGeometry> {
    let vertices = points.len() / 3;
    if indices.iter().any(|i| *i as usize >= vertices) {
        return None;
    }
    let flip = prim.value("orientation").and_then(|v| v.as_str()) == Some("leftHanded");
    let mut triangles: Vec<u32> = Vec::new();
    let mut polygons: Vec<u32> = Vec::new();
    let mut at = 0usize;
    for count in &counts {
        let count = *count as usize;
        if count < 3 || at + count > indices.len() {
            at += count;
            continue;
        }
        polygons.push(count as u32 - 2);
        for i in 1..count - 1 {
            let (a, b, c) = (indices[at], indices[at + i], indices[at + i + 1]);
            if flip {
                triangles.extend_from_slice(&[a, c, b]);
            } else {
                triangles.extend_from_slice(&[a, b, c]);
            }
        }
        at += count;
    }
    if triangles.is_empty() {
        return None;
    }

    let mut geometry = BufferGeometry::new();
    geometry.set_attribute("position", BufferAttribute::new(points, 3));
    geometry.set_index(triangles);
    crate::compute_vertex_normals(&mut geometry);
    geometry.set_polygons(polygons);
    Some(geometry)
}

/// Morph targets authored per USD point (blend-shape offsets, animated
/// points) onto `geometry`'s vertices, as relative morph attributes: as they
/// are when the geometry keeps one vertex per point, through each corner's
/// point when it went one vertex per corner (face-varying primvars). Returns
/// the influences, or `None` — leaving the geometry alone — when the vertices
/// match neither (a refined mesh).
fn attach_morphs(
    prim: &UsdPrim,
    geometry: &mut BufferGeometry,
    morphs: &crate::core::MorphAttributes,
) -> Option<Vec<f32>> {
    let points = prim.value("points")?.flat_f32().len() / 3;
    let vertices = geometry.get_attribute("position")?.count();
    let corners: Option<Vec<usize>> = if vertices == points {
        None
    } else {
        // The corner order `mesh_geometry_at` emits, fan by fan.
        let counts = prim.value("faceVertexCounts")?.flat_u32();
        let indices = prim.value("faceVertexIndices")?.flat_u32();
        let flip = prim.value("orientation").and_then(|v| v.as_str()) == Some("leftHanded");
        let mut out = Vec::new();
        let mut at = 0usize;
        for count in &counts {
            let n = *count as usize;
            if n >= 3 && at + n <= indices.len() {
                for k in 1..n - 1 {
                    let tri = if flip {
                        [at, at + k + 1, at + k]
                    } else {
                        [at, at + k, at + k + 1]
                    };
                    out.extend(tri.iter().map(|&c| indices[c] as usize));
                }
            }
            at += n;
        }
        if out.len() != vertices {
            return None;
        }
        Some(out)
    };
    let expand = |delta: &[f32]| -> Vec<f32> {
        match &corners {
            None => delta.to_vec(),
            Some(c) => c
                .iter()
                .flat_map(|&p| {
                    delta
                        .get(p * 3..p * 3 + 3)
                        .map(|d| [d[0], d[1], d[2]])
                        .unwrap_or([0.0; 3])
                })
                .collect(),
        }
    };
    let mapped = crate::core::MorphAttributes {
        targets: morphs
            .targets
            .iter()
            .map(|t| crate::core::MorphTarget {
                name: t.name.clone(),
                position_delta: expand(&t.position_delta),
                normal_delta: t.normal_delta.as_deref().map(expand),
            })
            .collect(),
        influences: morphs.influences.clone(),
    };
    Some(mapped.apply_to(geometry))
}

/// A mesh with material subsets as one mesh over a material array: the
/// faces reordered subset by subset — the unclaimed remainder, bound to the
/// mesh's own material, last — with a geometry group per run. `None` when
/// the mesh is refined (the runs would not survive), or the face count does
/// not come out as expected; the caller then splits instead.
fn grouped_by_subset(prim: &UsdPrim, path: &str, context: &mut Build) -> Option<Mesh> {
    let layer = context.layer;
    let level = context.options.subdivision_level;
    if level > 0 && subdiv::wanted(prim) {
        return None;
    }
    let subsets = shade::material_subsets(prim);
    let counts = prim.value("faceVertexCounts")?.flat_u32();
    let indices_len = prim.value("faceVertexIndices")?.flat_u32().len();
    let mut starts = Vec::with_capacity(counts.len());
    let mut at = 0usize;
    for c in &counts {
        starts.push(at);
        at += *c as usize;
    }
    // Triangles a face fans into, as `mesh_geometry_at` fans it.
    let triangles = |f: u32| -> u32 {
        match (counts.get(f as usize), starts.get(f as usize)) {
            (Some(&n), Some(&s)) if n >= 3 && s + n as usize <= indices_len => n - 2,
            _ => 0,
        }
    };
    let remainder = shade::unclaimed_faces(counts.len(), &subsets);
    let parts: Vec<(String, Vec<u32>, Option<String>)> = subsets
        .iter()
        .map(|s| (s.name.clone(), s.faces.clone(), s.material.clone()))
        .chain((!remainder.is_empty()).then(|| (prim.name.clone(), remainder, None)))
        .collect();
    let all: Vec<u32> = parts.iter().flat_map(|p| p.1.iter().copied()).collect();
    let mut geometry = mesh_geometry_of_faces(prim, 0, &all)?;
    let mut materials = Vec::new();
    let mut start = 0u32;
    for (i, (name, faces, material_path)) in parts.iter().enumerate() {
        let count = faces.iter().map(|&f| triangles(f)).sum::<u32>() * 3;
        geometry.add_group(start, count, i as u32);
        start += count;
        // A subset's own binding, or the mesh's where it has none.
        let (material, textures) = match material_path.as_ref().and_then(|p| layer.prim_at(p)) {
            Some(m) => {
                let resolved = shade::resolve(m, layer);
                (resolved.material, resolved.textures)
            }
            None => bound_material_at(path, layer),
        };
        context.textures.push((name.clone(), textures));
        materials.push(std::sync::Arc::new(material));
    }
    if start as usize != geometry.draw_count() {
        return None;
    }
    Some(Mesh::with_materials(
        std::sync::Arc::new(geometry),
        materials,
    ))
}

/// A mesh split into one child per material subset.
///
/// The faces no subset claims keep the mesh's own binding, which is what a
/// `nonOverlapping` family means by leaving them out — a `partition` leaves
/// none, and then there is no remainder to build.
fn split_by_subset(
    prim: &UsdPrim,
    arena: &mut ObjectArena,
    source: &UsdPrim,
    path: &str,
    context: &mut Build,
) -> ObjectId {
    let layer = context.layer;
    let level = context.options.subdivision_level;
    let subsets = shade::material_subsets(prim);

    let mut group = Object3D::group();
    group.name = prim.name.clone();
    let id = arena.insert(group);
    place_transform(arena, id, prim);
    context.placed.push((id, source.clone()));

    let total = prim
        .value("faceVertexCounts")
        .map(|v| v.flat_u32().len())
        .unwrap_or(0);

    // Each subset, then whatever it left behind.
    let remainder = shade::unclaimed_faces(total, &subsets);
    let parts = subsets
        .iter()
        .map(|s| (s.name.clone(), s.faces.clone(), s.material.clone()))
        .chain((!remainder.is_empty()).then(|| (prim.name.clone(), remainder, None)));

    for (name, faces, material_path) in parts {
        let Some(geometry) = mesh_geometry_of_faces(prim, level, &faces) else {
            continue;
        };
        // A subset's own binding, or the mesh's where it has none.
        let (material, textures) = match material_path {
            Some(found) => match layer.prim_at(&found) {
                Some(material) => {
                    let resolved = shade::resolve(material, layer);
                    (resolved.material, resolved.textures)
                }
                None => bound_material_at(path, layer),
            },
            None => bound_material_at(path, layer),
        };
        context.textures.push((name.clone(), textures));

        let mut node = Object3D::mesh(Mesh::new(geometry, material));
        node.name = name;
        let child = arena.insert(node);
        arena.add_child(id, child);
    }
    id
}

/// Put a prim's own transform onto a node already in the arena.
fn place_transform(arena: &mut ObjectArena, id: ObjectId, prim: &UsdPrim) {
    let (position, quaternion, scale) = transform_of(prim);
    if let Some(node) = arena.get_mut(id) {
        node.position = position;
        node.quaternion = quaternion;
        node.scale = scale;
    }
}

/// Animated vertices, as morph targets and the weights that switch between
/// them.
///
/// USD animates a mesh's points by keying the whole array. A renderer has no
/// per-frame vertex buffer to hand, but it has morph targets — so each frame
/// after the first becomes a target holding its difference from the first, and
/// the weights ramp one into the next. That is exactly how a cached
/// simulation is played back in three.js, and it costs one target per frame
/// rather than one mesh per frame.
///
/// The base mesh is the first sample, so a stage opened at its start time looks
/// right before anything is played.
fn vertex_animation(
    source: &UsdPrim,
    object: ObjectId,
    rate: f64,
) -> Option<(crate::core::MorphAttributes, Vec<KeyframeTrack>)> {
    let samples = source.value("points")?.samples()?.to_vec();
    if samples.len() < 2 {
        return None;
    }
    let base = samples[0].1.flat_f32();
    if base.is_empty() {
        return None;
    }

    let mut targets = Vec::new();
    let mut tracks = Vec::new();
    for (index, (_, frame)) in samples.iter().enumerate().skip(1) {
        let points = frame.flat_f32();
        if points.len() != base.len() {
            // A frame with a different vertex count is a different mesh, not a
            // deformation of this one.
            return None;
        }
        targets.push(crate::core::MorphTarget {
            name: format!("frame{index}"),
            position_delta: points.iter().zip(&base).map(|(p, b)| p - b).collect(),
            normal_delta: None,
        });

        // This frame's weight rises from the frame before and falls to the one
        // after, so the blend between any two neighbours is exactly the linear
        // interpolation USD specifies.
        let mut times = Vec::new();
        let mut values = Vec::new();
        for (slot, (time, _)) in samples.iter().enumerate() {
            times.push((time / rate) as f32);
            values.push(if slot == index { 1.0 } else { 0.0 });
        }
        tracks.push(KeyframeTrack::scalar(
            object,
            TrackTarget::MorphWeight { index: index - 1 },
            times,
            values,
        ));
    }

    Some((
        crate::core::MorphAttributes {
            influences: vec![0.0; targets.len()],
            targets,
        },
        tracks,
    ))
}

/// Tracks for everything else a prim animates: a light's colour and
/// brightness, a material's colour, whether the prim is drawn at all.
///
/// These are not transform ops, so the op-stack pass does not see them, and a
/// lamp that switches on halfway through a shot stays on — or off — for all of
/// it.
fn property_tracks(
    prim: &UsdPrim,
    layer: &UsdLayer,
    path: &str,
    object: ObjectId,
    rate: f64,
) -> Vec<KeyframeTrack> {
    let mut out = Vec::new();

    let scalar = |out: &mut Vec<KeyframeTrack>, value: &UsdValue, target: TrackTarget| {
        let Some(samples) = value.samples() else {
            return;
        };
        let times: Vec<f32> = samples.iter().map(|(t, _)| (t / rate) as f32).collect();
        let values: Vec<f32> = samples
            .iter()
            .map(|(_, v)| v.as_f64().unwrap_or(0.0) as f32)
            .collect();
        out.push(KeyframeTrack::scalar(object, target, times, values));
    };
    let colour = |out: &mut Vec<KeyframeTrack>, value: &UsdValue| {
        let Some(samples) = value.samples() else {
            return;
        };
        let times: Vec<f32> = samples.iter().map(|(t, _)| (t / rate) as f32).collect();
        let values: Vec<Color> = samples
            .iter()
            .map(|(_, v)| {
                let n = v.flat_f32();
                if n.len() >= 3 {
                    Color::new(n[0], n[1], n[2])
                } else {
                    Color::WHITE
                }
            })
            .collect();
        out.push(KeyframeTrack::color(
            object,
            TrackTarget::Color,
            times,
            values,
        ));
    };

    // `visibility` is a token — `inherited` or `invisible` — so what is
    // animated is which of the two, not a number.
    if let Some(value) = prim.value("visibility")
        && let Some(samples) = value.samples()
    {
        let times: Vec<f32> = samples.iter().map(|(t, _)| (t / rate) as f32).collect();
        let values: Vec<f32> = samples
            .iter()
            .map(|(_, v)| {
                if v.as_str() == Some("invisible") {
                    0.0
                } else {
                    1.0
                }
            })
            .collect();
        out.push(KeyframeTrack::scalar(
            object,
            TrackTarget::Visibility,
            times,
            values,
        ));
    }

    if schemas::is_light(&prim.type_name) {
        if let Some(value) = prim
            .value("inputs:intensity")
            .or_else(|| prim.value("intensity"))
        {
            scalar(&mut out, value, TrackTarget::Intensity);
        }
        if let Some(value) = prim.value("inputs:color").or_else(|| prim.value("color")) {
            colour(&mut out, value);
        }
    }

    // A mesh's colour is animated on the shader that its material binds, which
    // is a different prim in a different part of the tree.
    if (prim.type_name == "Mesh" || schemas::is_gprim(&prim.type_name))
        && let Some(shader) = shade::bound_material_path(layer, path)
            .and_then(|p| layer.prim_at(&p))
            .and_then(|material| shade::surface_shader(material, layer))
        && let Some(value) = shader.value("inputs:diffuseColor")
    {
        colour(&mut out, value);
    }
    out
}

/// Every time code any of this prim's transform ops is keyed at.
fn keyed_times(prim: &UsdPrim) -> Vec<f64> {
    let mut times = Vec::new();
    for property in &prim.properties {
        if !property.name.starts_with("xformOp:") {
            continue;
        }
        if let Some(samples) = property.value.samples() {
            times.extend(samples.iter().map(|(t, _)| *t));
        }
    }
    times
}

fn resolve_prim(prim: &UsdPrim, time: f64) -> UsdPrim {
    let mut out = prim.clone();
    for property in &mut out.properties {
        if property.value.samples().is_some() {
            property.value = property.value.at_time(time);
        }
    }
    out
}

/// What a build pass carries down the tree.
///
/// The skeleton is here because skinning is not local: a `Mesh` says which
/// skeleton binds it, and that skeleton is a sibling — so it has to be read
/// before the mesh that uses it, and carried down.
struct Build<'a> {
    layer: &'a UsdLayer,
    /// The layer *before* it was resolved to an instant. A `SkelAnimation` is
    /// nothing but time samples, and the resolved layer has already replaced
    /// them with the pose at one frame — so reading the animation from it
    /// finds a single unchanging value.
    source_layer: &'a UsdLayer,
    placed: &'a mut Vec<(ObjectId, UsdPrim)>,
    cameras: &'a mut Vec<UsdCamera>,
    skeletons: &'a mut Vec<Skeleton>,
    /// Clips a `SkelAnimation` produced, which are per-skeleton rather than
    /// per-prim and so cannot come from the transform pass.
    clips: &'a mut Vec<AnimationClip>,
    /// Time codes per second, for turning the animation's keys into seconds.
    rate: f64,
    options: &'a SceneOptions,
    /// Textures each mesh asked for, by prim name. Decoding an image is not
    /// this module's business, so what a material wants is reported rather
    /// than loaded.
    textures: &'a mut Vec<(String, Vec<shade::TextureRequest>)>,
    /// Blend shapes, which a `Mesh` has no field for.
    morphs: &'a mut Vec<(String, crate::core::MorphAttributes)>,
    /// The skeleton in scope, and the joints it was built from.
    skeleton: Option<Rc<UsdSkeleton>>,
    /// Where the skeleton's animation lives, for the meshes bound to it: a
    /// blend shape's weights are keyed on the animation and applied to the
    /// mesh, which are different prims.
    skeleton_animation: Option<String>,
}

fn build(
    prim: &UsdPrim,
    arena: &mut ObjectArena,
    source: &UsdPrim,
    parent: &str,
    context: &mut Build,
) -> Option<ObjectId> {
    let layer = context.layer;
    // The absolute path, which material binding needs: a binding applies to
    // everything beneath the prim it sits on, so resolving one means walking
    // back up the namespace.
    let path = format!("{parent}/{}", prim.name);
    // A class is a template for other prims, never itself part of the scene.
    if prim.specifier == super::parse::Specifier::Class {
        return None;
    }
    // `guide` geometry is never drawn, and `proxy` is a stand-in shown only
    // when the real thing is absent — which here it never is.
    if !schemas::is_drawable(
        prim,
        context.options.show_guides,
        context.options.show_proxies,
    ) {
        return None;
    }
    // Filled in if this prim turns out to carry blend shapes, so the weight
    // tracks can index them in the order they came out.
    let mut morph_order: Vec<String> = Vec::new();
    let mut object = match prim.type_name.as_str() {
        // A mesh with material subsets is one mesh with a material array:
        // the faces are ordered subset by subset (the unclaimed ones, under
        // the mesh's own binding, last) and each run is a geometry group —
        // three.js's `geometry.groups` with `mesh.material` an array. Refined
        // meshes still split into a mesh per subset, because refinement
        // rebuilds the faces and the runs would not survive it.
        "Mesh" if !shade::material_subsets(prim).is_empty() => {
            match grouped_by_subset(prim, &path, context) {
                Some(mesh) => Object3D::mesh(mesh),
                None => return Some(split_by_subset(prim, arena, source, &path, context)),
            }
        }
        "Mesh" => {
            let mut geometry = mesh_geometry_at(prim, context.options.subdivision_level)?;
            let (material, textures) = bound_material_at(&path, layer);
            context.textures.push((prim.name.clone(), textures));
            // A mesh that names a skeleton and carries weights is skinned.
            match context.skeleton.clone() {
                Some(skeleton)
                    // It must *say* it binds one: a rig keeps static props in
                    // the same subtree, and they must not be skinned by
                    // proximity.
                    if skel::binds_a_skeleton(prim)
                        && skel::skin_attributes(
                            prim,
                            geometry.get_attribute("position").map(|a| a.count()).unwrap_or(0),
                            &mut geometry,
                        ) =>
                {
                    skel::apply_bind_transform(prim, &mut geometry);
                    // Blend shapes, whose weights the skeleton's animation
                    // drives. The order here is the order the weight tracks
                    // index by.
                    // Offsets are per USD point; `attach_morphs` carries
                    // them onto the geometry's vertices.
                    let points = prim
                        .value("points")
                        .map(|v| v.flat_f32().len() / 3)
                        .unwrap_or(0);
                    let targets = skel::blend_shapes(prim, layer, points);
                    let mut influences = Vec::new();
                    if !targets.is_empty() {
                        morph_order = targets.iter().map(|t| t.name.clone()).collect();
                        let morphs = crate::core::MorphAttributes {
                            influences: vec![0.0; targets.len()],
                            targets,
                        };
                        influences = attach_morphs(prim, &mut geometry, &morphs).unwrap_or_default();
                        context.morphs.push((prim.name.clone(), morphs));
                    }
                    let mut sm = crate::core::SkinnedMesh::new(
                        geometry,
                        material,
                        skeleton.skeleton.clone(),
                    );
                    if !influences.is_empty() {
                        sm.morph_influences = influences;
                    }
                    Object3D::skinned_mesh(sm)
                }
                // Blend shapes without joints: a mesh bound to a joint-less
                // skeleton only for its animation's weights.
                _ if prim.value("skel:blendShapes").is_some() => {
                    let points = prim
                        .value("points")
                        .map(|v| v.flat_f32().len() / 3)
                        .unwrap_or(0);
                    let targets = skel::blend_shapes(prim, layer, points);
                    if targets.is_empty() {
                        Object3D::mesh(Mesh::new(geometry, material))
                    } else {
                        morph_order = targets.iter().map(|t| t.name.clone()).collect();
                        let weights = skel::bound_animation(prim, layer)
                            .map(|anim| skel::blend_shape_weights(anim, &morph_order))
                            .unwrap_or_else(|| vec![0.0; targets.len()]);
                        let morphs = crate::core::MorphAttributes {
                            influences: weights,
                            targets,
                        };
                        let influences = attach_morphs(prim, &mut geometry, &morphs);
                        context.morphs.push((prim.name.clone(), morphs));
                        let mut mesh = Mesh::new(geometry, material);
                        if let Some(influences) = influences {
                            mesh.morph_influences = influences;
                        }
                        Object3D::mesh(mesh)
                    }
                }
                _ => Object3D::mesh(Mesh::new(geometry, material)),
            }
        }
        // The quadrics and the cube, which carry their shape in a handful of
        // numbers rather than in a vertex buffer.
        type_name if schemas::is_gprim(type_name) => match schemas::gprim(prim) {
            Some(geometry) => {
                let (material, textures) = bound_material_at(&path, layer);
                context.textures.push((prim.name.clone(), textures));
                Object3D::mesh(Mesh::new(geometry, material))
            }
            None => Object3D::group(),
        },
        type_name if schemas::is_light(type_name) => match schemas::light(prim) {
            Some(light) => Object3D::light(light),
            None => Object3D::group(),
        },
        "Points" => match schemas::points(prim) {
            Some(points) => Object3D::points(points),
            None => Object3D::group(),
        },
        "BasisCurves" | "NurbsCurves" => match schemas::curves(prim) {
            Some(curves) => Object3D::line_segments(curves),
            None => Object3D::group(),
        },
        // A point instancer becomes a group with one instanced mesh under it
        // per prototype: an instanced draw carries one geometry, so a scatter
        // of trees and rocks is two of them rather than one.
        "PointInstancer" => {
            let level = context.options.subdivision_level;
            let prototype_root = path.clone();
            let meshes = schemas::point_instancer(prim, layer, |prototype| {
                let path = format!("{prototype_root}/{}", prototype.name);
                mesh_geometry_at(prototype, level).map(|g| (g, bound_material_at(&path, layer).0))
            });
            let mut group = Object3D::group();
            group.name = prim.name.clone();
            let id = arena.insert(group);
            for (name, mesh) in meshes {
                let mut node = Object3D::instanced_mesh(mesh);
                node.name = name;
                let child = arena.insert(node);
                arena.add_child(id, child);
            }
            // The prototypes themselves are not part of the scene: they are
            // the thing being instanced, not a copy standing beside it.
            place_transform(arena, id, prim);
            context.placed.push((id, source.clone()));
            return Some(id);
        }
        // Everything else becomes a group: an Xform carries a transform, a
        // Scope carries nothing, and an unknown type is still a place in the
        // hierarchy that its children hang from.
        _ => Object3D::group(),
    };
    object.name = prim.name.clone();
    let (position, quaternion, scale) = transform_of(prim);
    object.position = position;
    object.quaternion = quaternion;
    object.scale = scale;
    if prim.value("visibility").and_then(|v| v.as_str()) == Some("invisible") {
        object.visible = false;
    }

    let id = arena.insert(object);
    // Blend-shape weights are driven by the skeleton's animation, and the
    // tracks point at the mesh rather than at a joint.
    if !morph_order.is_empty()
        && let Some(anim) = source
            .children
            .iter()
            .find(|c| c.type_name == "SkelAnimation")
            .or_else(|| {
                context
                    .skeleton_animation
                    .as_ref()
                    .and_then(|path| context.source_layer.prim_at(path))
            })
            .or_else(|| skel::bound_animation(source, context.source_layer))
    {
        let tracks = skel::blend_shape_tracks(anim, &morph_order, id, context.rate);
        if !tracks.is_empty() {
            context.clips.push(AnimationClip::new(
                format!("{}-blend", prim.name),
                0.0,
                tracks,
            ));
        }
    }
    // A camera is not a node kind, so it is recorded against the node that
    // carries its transform.
    if prim.type_name == "Camera" {
        context.cameras.push(schemas::camera(prim, id));
    }
    // Remember the *unresolved* prim, so the clip can re-evaluate it at each
    // of its own key times.
    context.placed.push((id, source.clone()));

    // Anything animated that is not a transform op: the colours, the
    // brightness, the visibility. Read from the unresolved layer, since the
    // resolved one has already been reduced to a single frame.
    let mut tracks = property_tracks(source, context.source_layer, &path, id, context.rate);

    // Animated vertices, which become morph targets rather than a mesh a
    // frame. Only where the prim has no blend shapes of its own: the two would
    // be indexing the same weights.
    if morph_order.is_empty()
        && let Some((morphs, weights)) = vertex_animation(source, id, context.rate)
    {
        // Onto the geometry, so the renderers play it.
        if let Some(ObjectKind::Mesh(mesh)) = arena.get_mut(id).map(|o| &mut o.kind) {
            let geometry = std::sync::Arc::make_mut(&mut mesh.geometry);
            if let Some(influences) = attach_morphs(prim, geometry, &morphs) {
                mesh.update_morph_targets();
                mesh.morph_influences = influences;
            }
        }
        context.morphs.push((prim.name.clone(), morphs));
        tracks.extend(weights);
    }

    if !tracks.is_empty() {
        context.clips.push(AnimationClip::new(
            format!("{}-properties", prim.name),
            0.0,
            tracks,
        ));
    }

    // A `SkelRoot` reads its skeleton before its meshes, because the meshes
    // are what bind to it.
    let outer = context.skeleton.take();
    let skeleton_prim = prim.children.iter().find(|c| c.type_name == "Skeleton");
    match skeleton_prim.and_then(|c| skel::skeleton(c, arena, id)) {
        Some(found) => {
            // The animation the skeleton names, keyed on its own joints, read
            // from the unresolved layer so its samples are still samples.
            let source_skeleton = source.children.iter().find(|c| c.type_name == "Skeleton");
            if let Some(clip) = source_skeleton
                .and_then(|c| skel::animation_source(c, context.source_layer))
                .or_else(|| {
                    source
                        .children
                        .iter()
                        .find(|c| c.type_name == "SkelAnimation")
                })
                .and_then(|anim| skel::animation(anim, &found, context.rate, &prim.name))
            {
                context.clips.push(clip);
            }
            context.skeleton_animation = source_skeleton
                .and_then(|c| c.value("skel:animationSource"))
                .and_then(|v| v.as_str())
                .map(str::to_string);
            context.skeletons.push(found.skeleton.clone());
            context.skeleton = Some(Rc::new(found));
        }
        None => context.skeleton = outer.clone(),
    }

    for (child, child_source) in prim.children.iter().zip(&source.children) {
        // The skeleton's own joints were built above; the prim itself is not
        // part of the scene.
        if matches!(
            child.type_name.as_str(),
            "Skeleton" | "GeomSubset" | "BlendShape" | "SkelAnimation"
        ) {
            // A subset is part of its mesh (its groups), not a node; so is a
            // blend shape (its morph targets), and an animation is tracks.
            continue;
        }
        if let Some(child_id) = build(child, arena, child_source, &path, context) {
            arena.add_child(id, child_id);
        }
    }
    context.skeleton = outer;
    Some(id)
}

/// The transform a prim's `xformOp`s add up to.
///
/// `xformOpOrder` is authoritative: the ops are applied in the order it lists,
/// and an op present but unlisted is deliberately inactive. Without it, USD
/// applies nothing — which is not the same as identity by accident, so the
/// absence is honoured rather than guessed around.
fn transform_of(prim: &UsdPrim) -> (Vector3, Quaternion, Vector3) {
    let identity = (
        Vector3::ZERO,
        Quaternion::identity(),
        Vector3::new(1.0, 1.0, 1.0),
    );
    let Some(order) = prim.value("xformOpOrder") else {
        return identity;
    };
    let mut matrix = Matrix4::identity();
    let mut any = false;
    for op in order.items() {
        let Some(name) = op.as_str() else { continue };
        // `!invert!xformOp:translate` inverts the op it names.
        let (invert, name) = match name.strip_prefix("!invert!") {
            Some(rest) => (true, rest),
            None => (false, name),
        };
        let Some(value) = prim.value(name) else {
            continue;
        };
        let step = op_matrix(name, value);
        let Some(step) = step else { continue };
        any = true;
        let step = if invert { step.invert() } else { step };
        matrix = matrix.multiply(&step);
    }
    if !any {
        return identity;
    }
    matrix.decompose()
}

fn op_matrix(name: &str, value: &UsdValue) -> Option<Matrix4> {
    let n = value.flat_f32();
    // The op's kind is in its name after the namespace; a suffixed op like
    // `xformOp:translate:pivot` is still a translate.
    let kind = name.strip_prefix("xformOp:")?;
    let kind = kind.split(':').next().unwrap_or(kind);
    match kind {
        "translate" if n.len() >= 3 => Some(Matrix4::compose(
            Vector3::new(n[0], n[1], n[2]),
            Quaternion::identity(),
            Vector3::new(1.0, 1.0, 1.0),
        )),
        "scale" if n.len() >= 3 => Some(Matrix4::compose(
            Vector3::ZERO,
            Quaternion::identity(),
            Vector3::new(n[0], n[1], n[2]),
        )),
        // A single-axis rotation, in degrees as USD writes them.
        "rotateX" | "rotateY" | "rotateZ" if !n.is_empty() => {
            let axis = match kind {
                "rotateX" => Vector3::new(1.0, 0.0, 0.0),
                "rotateY" => Vector3::new(0.0, 1.0, 0.0),
                _ => Vector3::new(0.0, 0.0, 1.0),
            };
            Some(Matrix4::compose(
                Vector3::ZERO,
                Quaternion::from_axis_angle(axis, n[0].to_radians()),
                Vector3::new(1.0, 1.0, 1.0),
            ))
        }
        // Euler triples. The name gives the order the axes are applied in.
        "rotateXYZ" | "rotateXZY" | "rotateYXZ" | "rotateYZX" | "rotateZXY" | "rotateZYX"
            if n.len() >= 3 =>
        {
            let axes = &kind[6..];
            let mut q = Quaternion::identity();
            for (i, axis) in axes.chars().enumerate() {
                let v = match axis {
                    'X' => Vector3::new(1.0, 0.0, 0.0),
                    'Y' => Vector3::new(0.0, 1.0, 0.0),
                    _ => Vector3::new(0.0, 0.0, 1.0),
                };
                let step = Quaternion::from_axis_angle(v, n[i].to_radians());
                q = q.multiply(step);
            }
            Some(Matrix4::compose(
                Vector3::ZERO,
                q,
                Vector3::new(1.0, 1.0, 1.0),
            ))
        }
        // USD writes a quaternion real-part first; this crate stores it last.
        "orient" if n.len() >= 4 => Some(Matrix4::compose(
            Vector3::ZERO,
            Quaternion::new(n[1], n[2], n[3], n[0]),
            Vector3::new(1.0, 1.0, 1.0),
        )),
        "transform" if n.len() >= 16 => {
            // USD writes a matrix row by row, for row vectors (`p * M`): the
            // basis vectors are its first three rows and the translation its
            // last. This crate's matrices act on column vectors and are stored
            // column by column — the transpose of USD's, stored the other way
            // round — so the same sixteen numbers in the same order are already
            // right. Transposing them put the translation in the projective row,
            // where `decompose` drops it, and turned every rotation backwards.
            let mut m = [0.0f32; 16];
            m.copy_from_slice(&n[..16]);
            Some(Matrix4 { elements: m })
        }
        _ => None,
    }
}

/// Read a `UsdGeomMesh` as triangles.
pub fn mesh_geometry(prim: &UsdPrim) -> Option<BufferGeometry> {
    mesh_geometry_at(prim, 0)
}

/// A mesh's geometry restricted to a set of faces.
///
/// The vertices are not re-indexed: dropping the faces a subset does not claim
/// leaves unreferenced points behind, which cost memory and nothing else — and
/// keeping the indices as authored means a primvar or a skin weight still lines
/// up with the vertex it was written for.
pub fn mesh_geometry_of_faces(
    prim: &UsdPrim,
    level: usize,
    faces: &[u32],
) -> Option<BufferGeometry> {
    let counts = prim.value("faceVertexCounts")?.flat_u32();
    let indices = prim.value("faceVertexIndices")?.flat_u32();

    // Where each face starts in the index buffer.
    let mut starts = Vec::with_capacity(counts.len());
    let mut at = 0usize;
    for count in &counts {
        starts.push(at);
        at += *count as usize;
    }

    let mut kept_counts = Vec::with_capacity(faces.len());
    let mut kept_indices = Vec::new();
    for face in faces {
        let (Some(start), Some(count)) = (
            starts.get(*face as usize).copied(),
            counts.get(*face as usize).copied(),
        ) else {
            continue;
        };
        if start + count as usize > indices.len() {
            continue;
        }
        kept_counts.push(count);
        kept_indices.extend_from_slice(&indices[start..start + count as usize]);
    }
    if kept_counts.is_empty() {
        return None;
    }

    // Build a prim standing for just those faces, so the usual path — winding,
    // primvars, subdivision — applies unchanged.
    let mut only = prim.clone();
    only.children.clear();
    for (name, value) in [
        (
            "faceVertexCounts",
            UsdValue::Array(
                kept_counts
                    .iter()
                    .map(|c| UsdValue::Int(*c as i128))
                    .collect(),
            ),
        ),
        (
            "faceVertexIndices",
            UsdValue::Array(
                kept_indices
                    .iter()
                    .map(|i| UsdValue::Int(*i as i128))
                    .collect(),
            ),
        ),
    ] {
        if let Some(property) = only.properties.iter_mut().find(|p| p.name == name) {
            property.value = value;
        }
    }
    mesh_geometry_at(&only, level)
}

/// The same, refined `level` times if the mesh says it is a subdivision
/// surface.
///
/// Worth knowing: `subdivisionScheme` defaults to `catmullClark`, so a mesh
/// that says nothing is one — and its points are a control cage rather than
/// the surface. Refining is not free and the level is the renderer's call, not
/// the file's, which is why it is a parameter here and a complexity slider in
/// usdview.
pub fn mesh_geometry_at(prim: &UsdPrim, level: usize) -> Option<BufferGeometry> {
    let mut points = prim.value("points")?.flat_f32();
    if points.len() < 9 {
        return None;
    }
    let mut counts = prim
        .value("faceVertexCounts")
        .map(|v| v.flat_u32())
        .unwrap_or_default();
    let mut indices = prim
        .value("faceVertexIndices")
        .map(|v| v.flat_u32())
        .unwrap_or_default();
    // A mesh with no topology is a point cloud as far as this is concerned, and
    // there is nothing to draw.
    if counts.is_empty() || indices.is_empty() {
        return None;
    }

    // Refinement happens on the polygons, before anything is triangulated:
    // Catmull–Clark is defined on the cage, and a fan of triangles is a
    // different cage with a different limit surface.
    if level > 0 && subdiv::wanted(prim) {
        let refined = subdiv::subdivide(
            subdiv::Cage {
                positions: points
                    .as_chunks::<3>()
                    .0
                    .iter()
                    .map(|p| [p[0], p[1], p[2]])
                    .collect(),
                counts: counts.clone(),
                indices: indices.clone(),
            },
            level,
            &subdiv::options_of(prim),
        );
        points = refined.positions.iter().flat_map(|p| *p).collect();
        counts = refined.counts;
        indices = refined.indices;
        // Refining rebuilds the topology, so anything authored per corner of
        // the old cage no longer lines up with the new one.
        return refined_geometry(points, counts, indices, prim);
    }

    // `leftHanded` reverses what USD considers the front of every face.
    let flip = prim.value("orientation").and_then(|v| v.as_str()) == Some("leftHanded");

    // An index past the end of the points is a file saying something about a
    // vertex that is not there. It has to be refused here: everything
    // downstream — normals, tangents, the renderer — trusts an index buffer to
    // be in range, and a corrupt asset would otherwise take the process with
    // it.
    let vertices = points.len() / 3;
    if indices.iter().any(|i| *i as usize >= vertices) {
        return None;
    }

    // Corner `c` of the mesh, as a position in `indices`, fanned into triangles.
    let mut corners: Vec<usize> = Vec::new();
    // Triangles per face, kept so the faces survive as polygons.
    let mut polygons: Vec<u32> = Vec::new();
    let mut at = 0usize;
    for count in &counts {
        let n = *count as usize;
        if n >= 3 && at + n <= indices.len() {
            polygons.push(n as u32 - 2);
            for k in 1..n - 1 {
                if flip {
                    corners.extend_from_slice(&[at, at + k + 1, at + k]);
                } else {
                    corners.extend_from_slice(&[at, at + k, at + k + 1]);
                }
            }
        }
        at += n;
    }
    if corners.is_empty() {
        return None;
    }

    let normals = primvar(prim, "normals").or_else(|| primvar(prim, "primvars:normals"));
    let uvs = pick_uvs(prim);
    // `displayColor` is USD's fallback shading and every tool that does not
    // evaluate a shader graph uses it. Per vertex it is a colour attribute;
    // one value for the whole mesh is the material's colour and is left to the
    // material, which already reads it.
    let colours = primvar(prim, "primvars:displayColor").filter(|pv| !pv.constant);
    let face_varying = [&normals, &uvs, &colours]
        .iter()
        .any(|p| matches!(p, Some(pv) if pv.face_varying));

    let mut geometry = BufferGeometry::new();
    if face_varying {
        // One vertex per corner: the only way a per-corner normal survives.
        let mut pos = Vec::with_capacity(corners.len() * 3);
        let mut nrm = Vec::new();
        let mut uv = Vec::new();
        let mut col = Vec::new();
        for &c in &corners {
            let point = indices[c] as usize;
            pos.extend_from_slice(slice3(&points, point));
            if let Some(pv) = &normals {
                nrm.extend_from_slice(&pv.at3(c, indices[c] as usize));
            }
            if let Some(pv) = &uvs {
                uv.extend_from_slice(&pv.at2(c, indices[c] as usize));
            }
            if let Some(pv) = &colours {
                col.extend_from_slice(&pv.at3(c, indices[c] as usize));
            }
        }
        geometry.set_attribute("position", BufferAttribute::new(pos, 3));
        if !nrm.is_empty() {
            geometry.set_attribute("normal", BufferAttribute::new(nrm, 3));
        }
        if !uv.is_empty() {
            geometry.set_attribute("uv", BufferAttribute::new(uv, 2));
        }
        if !col.is_empty() {
            geometry.set_attribute("color", BufferAttribute::new(col, 3));
        }
    } else {
        geometry.set_attribute("position", BufferAttribute::new(points.clone(), 3));
        let vertices = points.len() / 3;
        if let Some(pv) = &normals {
            let mut nrm = Vec::with_capacity(vertices * 3);
            for v in 0..vertices {
                nrm.extend_from_slice(&pv.at3(v, v));
            }
            geometry.set_attribute("normal", BufferAttribute::new(nrm, 3));
        }
        if let Some(pv) = &uvs {
            let mut uv = Vec::with_capacity(vertices * 2);
            for v in 0..vertices {
                uv.extend_from_slice(&pv.at2(v, v));
            }
            geometry.set_attribute("uv", BufferAttribute::new(uv, 2));
        }
        if let Some(pv) = &colours {
            let mut col = Vec::with_capacity(vertices * 3);
            for v in 0..vertices {
                col.extend_from_slice(&pv.at3(v, v));
            }
            geometry.set_attribute("color", BufferAttribute::new(col, 3));
        }
        geometry.set_index(corners.iter().map(|&c| indices[c]).collect());
    }
    if geometry.get_attribute("normal").is_none() {
        crate::compute_vertex_normals(&mut geometry);
    }
    geometry.set_polygons(polygons);
    Some(geometry)
}

fn slice3(v: &[f32], i: usize) -> &[f32] {
    let at = i * 3;
    if at + 3 <= v.len() {
        &v[at..at + 3]
    } else {
        &[0.0, 0.0, 0.0]
    }
}

/// A primvar's values, plus how they are addressed.
struct Primvar {
    data: Vec<f32>,
    /// `primvars:st:indices` — an indirection USD uses to share values.
    indices: Vec<u32>,
    face_varying: bool,
    /// `interpolation = "constant"` — one value for the whole surface, which
    /// is a material colour rather than a vertex attribute. Reading it as one
    /// gives the first vertex the colour and the rest whatever
    /// out-of-range reads back, which for `displayColor` is black.
    constant: bool,
    stride: usize,
}

impl Primvar {
    fn get(&self, corner: usize, vertex: usize) -> usize {
        let i = if self.face_varying { corner } else { vertex };
        if self.indices.is_empty() {
            i
        } else {
            *self.indices.get(i).unwrap_or(&0) as usize
        }
    }

    fn at3(&self, corner: usize, vertex: usize) -> [f32; 3] {
        let at = self.get(corner, vertex) * self.stride;
        [
            *self.data.get(at).unwrap_or(&0.0),
            *self.data.get(at + 1).unwrap_or(&0.0),
            *self.data.get(at + 2).unwrap_or(&0.0),
        ]
    }

    fn at2(&self, corner: usize, vertex: usize) -> [f32; 2] {
        let at = self.get(corner, vertex) * self.stride;
        [
            *self.data.get(at).unwrap_or(&0.0),
            *self.data.get(at + 1).unwrap_or(&0.0),
        ]
    }
}

/// The UV set a mesh is actually laid out in.
///
/// `primvars:st` is the conventional one and usually the only one, but a mesh
/// may carry several — and the first is not always the one the textures were
/// authored against. Apple's AR assets carry two: `st` runs well outside the
/// unit square, from −3.9 to 9.3 on the iPhone's rails, because it is a
/// *tiling* parameterisation for a repeating material; `st1` sits inside it,
/// 0.017 to 0.967, because it is the atlas the textures are actually painted
/// in. Read `st` and every map repeats about thirteen times across the rail —
/// anodised metal comes out as a block pattern, which is how this was noticed.
///
/// Which to take is a question the geometry can answer on its own, without
/// reading a single material: an atlas is normalised and a tiling set is not,
/// so a mesh carrying both has already said which is which. Sets are tried in
/// order and one that escapes the unit square gives way to one that stays
/// inside it. If they all escape, or none do, the first still wins — a model
/// with one tiling set is correctly tiled, and nothing here should second-guess
/// a mesh that carries only what it needs.
///
/// The alternative is to read `inputs:varname` off each texture and bind per
/// map, which is what USD actually specifies. That needs a UV channel per
/// texture in the material and a shader to match; this needs neither, and
/// settles the case that occurs.
fn pick_uvs(prim: &UsdPrim) -> Option<Primvar> {
    const SETS: [&str; 5] = [
        "primvars:st",
        "primvars:st0",
        "primvars:UVMap",
        "primvars:st1",
        "primvars:st2",
    ];
    let mut first: Option<Primvar> = None;
    for name in SETS {
        let Some(pv) = primvar(prim, name) else {
            continue;
        };
        if !escapes_unit_square(&pv) {
            return Some(pv);
        }
        first.get_or_insert(pv);
    }
    first
}

/// Whether a UV set reaches outside the unit square by more than a rounding.
///
/// The margin is there because an atlas is packed up to its edges and a
/// coordinate may land a hair past one; a tiling set misses by whole turns, so
/// nothing sits near the boundary between the two.
fn escapes_unit_square(pv: &Primvar) -> bool {
    const SLACK: f32 = 0.01;
    pv.data.iter().any(|v| *v < -SLACK || *v > 1.0 + SLACK)
}

fn primvar(prim: &UsdPrim, name: &str) -> Option<Primvar> {
    let property: &UsdProperty = prim.property(name)?;
    let data = property.value.flat_f32();
    if data.is_empty() {
        return None;
    }
    let interpolation = property.meta("interpolation").and_then(|v| v.as_str());
    let face_varying = interpolation == Some("faceVarying");
    let constant = interpolation == Some("constant");
    let indices = prim
        .value(&format!("{name}:indices"))
        .map(|v| v.flat_u32())
        .unwrap_or_default();
    let stride = if name.contains("st") || name.contains("UV") {
        2
    } else {
        3
    };
    // One value and nothing said about interpolation is constant too: USD's
    // default is `constant`, and a single colour is not a vertex attribute.
    let constant = constant || data.len() == stride;
    Some(Primvar {
        data,
        indices,
        face_varying,
        constant,
        stride,
    })
}

/// The material a mesh is bound to, read as a `UsdPreviewSurface`.
/// The material bound to a prim, resolved through its shader graph.
///
/// `path` is the prim's absolute path, which is needed because binding is
/// inherited: a mesh with none of its own wears the nearest ancestor's.
fn bound_material_at(path: &str, layer: &UsdLayer) -> (Material, Vec<shade::TextureRequest>) {
    let (mut material, textures) =
        match shade::bound_material_path(layer, path).and_then(|p| layer.prim_at(&p)) {
            Some(prim) => {
                let resolved = shade::resolve(prim, layer);
                (resolved.material, resolved.textures)
            }
            None => (
                StandardMaterial::new(Color::new(0.8, 0.8, 0.8)).into(),
                Vec::new(),
            ),
        };
    // USD keeps sidedness on the surface and this crate keeps it on the
    // material, so it has to move across. It is a gprim attribute and does not
    // inherit, so it is read from the mesh itself and from nowhere else.
    if matches!(
        layer.prim_at(path).and_then(|p| p.value("doubleSided")),
        Some(UsdValue::Bool(true))
    ) {
        material.set_side(2);
    }
    (material, textures)
}

/// Load the images a `.usdz`'s materials asked for, out of the archive itself.
///
/// [`UsdScene::textures`] exists because a scene-description reader has no
/// business decoding images or reaching for files beside the layer. A `.usdz`
/// is the case where neither objection holds: the package is required to be
/// self-contained, so the bytes are already in hand, and this crate decodes
/// PNG, and JPEG with the `jpeg` feature (on by default). So a packaged asset
/// arrives ready to draw instead of arriving with a list of homework.
///
/// Requests this cannot satisfy — a JPEG without the `jpeg` feature, another
/// format, or a file the archive does not carry — are left in
/// [`UsdScene::textures`] for the caller, so nothing is lost by asking.
///
/// Returns how many images were attached.
pub fn attach_textures(scene: &mut UsdScene, archive: &UsdzArchive) -> usize {
    attach_with(scene, |request| decode_from(archive, request))
}

/// Walk every request, attaching whatever `load` can resolve and keeping the
/// rest for the caller.
fn attach_with(
    scene: &mut UsdScene,
    load: impl Fn(&shade::TextureRequest) -> Option<Texture>,
) -> usize {
    let mut attached = 0;
    let mut pending: Vec<(String, Vec<shade::TextureRequest>)> = Vec::new();

    for (name, requests) in std::mem::take(&mut scene.textures) {
        let mut unresolved = Vec::new();
        let targets: Vec<ObjectId> = scene
            .roots
            .iter()
            .flat_map(|root| scene.arena.get_objects_by_name(*root, &name))
            .collect();
        for request in requests {
            match load(&request) {
                Some(texture) => {
                    let texture = std::sync::Arc::new(texture);
                    let mut used = false;
                    for id in &targets {
                        if let Some(object) = scene.arena.get_mut(*id) {
                            used |= put_map(object, request.slot, &texture);
                        }
                    }
                    if used {
                        attached += 1;
                    } else {
                        unresolved.push(request);
                    }
                }
                None => unresolved.push(request),
            }
        }
        if !unresolved.is_empty() {
            pending.push((name, unresolved));
        }
    }
    scene.textures = pending;
    attached
}

/// Load the images a `.usda` or `.usdc` asked for, from beside the layer.
///
/// The counterpart to [`attach_textures`] for the two forms that are not
/// packages. A layer refers to its maps by path relative to itself, so `base`
/// is the directory the layer was read from. Nothing is guessed at: a path
/// that escapes `base` or names a file that is not there is left in
/// [`UsdScene::textures`] for the caller, exactly as before.
///
/// Returns how many images were attached.
#[cfg(not(target_arch = "wasm32"))]
pub fn attach_textures_from_dir(scene: &mut UsdScene, base: &std::path::Path) -> usize {
    let read = |request: &shade::TextureRequest| -> Option<Vec<u8>> {
        let relative = std::path::Path::new(request.file.trim_start_matches("./"));
        // An absolute path, or one climbing out with `..`, is not this
        // function's to follow — it was asked for a directory, not the disk.
        if relative.is_absolute()
            || relative
                .components()
                .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            return None;
        }
        std::fs::read(base.join(relative)).ok()
    };
    attach_with(scene, |request| {
        read(request).and_then(|bytes| decode(&bytes, request))
    })
}

/// One request as a texture, out of the archive that carries it.
fn decode_from(archive: &UsdzArchive, request: &shade::TextureRequest) -> Option<Texture> {
    // An asset path may be written `./foo.png` or with the package prefix a
    // flattened layer picks up; the archive keys on the plain name.
    let wanted = request.file.trim_start_matches("./");
    let entry = archive
        .entries
        .iter()
        .find(|e| e.name == wanted || e.name.ends_with(&format!("/{wanted}")))?;
    decode(&entry.data, request)
}

/// Image bytes as the texture the request describes: PNG, or JPEG with the
/// `jpeg` feature, told apart by their signatures rather than the file name.
fn decode(bytes: &[u8], request: &shade::TextureRequest) -> Option<Texture> {
    let (width, height, rgba) = decode_rgba(bytes)?;
    // A data map must not be read through an sRGB curve, and a colour map
    // must. The request carries which, because USD authors it.
    let format = if request.color_space == "raw" {
        TextureFormat::Rgba8Unorm
    } else {
        TextureFormat::Rgba8UnormSrgb
    };
    Some(Texture {
        wrap_s: wrap_from(&request.wrap_s),
        wrap_t: wrap_from(&request.wrap_t),
        ..Texture::new(width, height, format, rgba)
    })
}

/// PNG or JPEG bytes as RGBA, or `None` for anything this build cannot read.
fn decode_rgba(bytes: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
    #[cfg(feature = "jpeg")]
    if crate::utils::jpeg::is_jpeg(bytes) {
        let image = crate::utils::jpeg::decode_jpeg(bytes).ok()?;
        return Some((image.width, image.height, image.rgba));
    }
    let image = crate::utils::png::decode_png(bytes).ok()?;
    Some((image.width, image.height, image.rgba))
}

/// USD's wrap mode as this crate's.
///
/// `black` has no equivalent here — it is a border colour, not a wrap — and
/// clamping is the nearest thing that does not tile.
fn wrap_from(name: &str) -> TextureWrap {
    match name {
        "repeat" => TextureWrap::Repeat,
        "mirror" => TextureWrap::MirroredRepeat,
        _ => TextureWrap::ClampToEdge,
    }
}

/// Hang a texture on the slot it belongs to, reporting whether it fit.
fn put_map(
    object: &mut Object3D,
    slot: shade::TextureSlot,
    texture: &std::sync::Arc<Texture>,
) -> bool {
    use shade::TextureSlot as S;
    let ObjectKind::Mesh(mesh) = &mut object.kind else {
        return false;
    };
    let material = std::sync::Arc::make_mut(&mut mesh.material);
    macro_rules! set {
        ($m:expr, $($slot:ident => $field:ident),* $(,)?) => {
            match slot {
                $(S::$slot => { $m.$field = Some(texture.clone()); true })*
                _ => false,
            }
        };
    }
    match material {
        Material::Standard(m) => set!(m,
            BaseColor => map,
            Normal => normal_map,
            Roughness => roughness_map,
            Metalness => metalness_map,
            Emissive => emissive_map,
            Occlusion => ao_map,
            Displacement => displacement_map,
        ),
        Material::Physical(m) => set!(m,
            BaseColor => map,
            Normal => normal_map,
            Roughness => roughness_map,
            Metalness => metalness_map,
            Emissive => emissive_map,
            Occlusion => ao_map,
            Displacement => displacement_map,
        ),
        Material::Basic(m) => set!(m, BaseColor => map),
        Material::Sprite(m) => set!(m, BaseColor => map),
        _ => false,
    }
}

#[cfg(test)]
mod tests {

    /// A tiling `st` beside an atlas `st1` — Apple's AR assets, and the
    /// difference between anodised metal and a repeating block pattern.
    #[test]
    fn a_tiling_uv_set_gives_way_to_an_atlas() {
        let src = r#"#usda 1.0
def Mesh "m"
{
    int[] faceVertexCounts = [4]
    int[] faceVertexIndices = [0, 1, 2, 3]
    point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
    texCoord2f[] primvars:st = [(-3.9, 0), (9.3, 0), (9.3, 8.8), (-3.9, 8.8)] (
        interpolation = "vertex"
    )
    texCoord2f[] primvars:st1 = [(0.017, 0.063), (0.967, 0.063), (0.967, 0.974), (0.017, 0.974)] (
        interpolation = "vertex"
    )
}
"#;
        let layer = crate::loaders::usd::parse::parse(src).unwrap();
        let prim = layer.prim_at("/m").unwrap();
        let uvs = super::pick_uvs(prim).unwrap();
        assert!(
            (uvs.data[0] - 0.017).abs() < 1e-5,
            "st runs -3.9..9.3 and tiles; st1 is the atlas the textures are painted in"
        );
    }

    /// One set and no choice to make: a mesh that tiles is meant to tile.
    #[test]
    fn a_lone_tiling_set_is_left_alone() {
        let src = r#"#usda 1.0
def Mesh "m"
{
    int[] faceVertexCounts = [4]
    int[] faceVertexIndices = [0, 1, 2, 3]
    point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
    texCoord2f[] primvars:st = [(0, 0), (4, 0), (4, 4), (0, 4)] (
        interpolation = "vertex"
    )
}
"#;
        let layer = crate::loaders::usd::parse::parse(src).unwrap();
        let prim = layer.prim_at("/m").unwrap();
        let uvs = super::pick_uvs(prim).unwrap();
        assert_eq!(uvs.data[2], 4.0, "nothing to prefer it to, so it stays");
    }

    /// Both inside the unit square: the conventional one wins, as before.
    #[test]
    fn the_first_set_wins_when_neither_escapes() {
        let src = r#"#usda 1.0
def Mesh "m"
{
    int[] faceVertexCounts = [4]
    int[] faceVertexIndices = [0, 1, 2, 3]
    point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
    texCoord2f[] primvars:st = [(0, 1), (1, 1), (0, 0), (1, 0)] (
        interpolation = "vertex"
    )
    texCoord2f[] primvars:st1 = [(0.1, 0.9), (0.4, 0.9), (0.4, 0.2), (0.1, 0.2)] (
        interpolation = "vertex"
    )
}
"#;
        let layer = crate::loaders::usd::parse::parse(src).unwrap();
        let prim = layer.prim_at("/m").unwrap();
        let uvs = super::pick_uvs(prim).unwrap();
        assert_eq!(uvs.data[0], 0.0, "st is a real parameterisation here");
    }
    use super::super::parse::parse;
    use super::*;
    use crate::animation::TrackValues;

    const QUAD: &str = r#"#usda 1.0
def Xform "World"
{
    double3 xformOp:translate = (1, 2, 3)
    uniform token[] xformOpOrder = ["xformOp:translate"]

    def Mesh "Quad"
    {
        int[] faceVertexCounts = [4]
        int[] faceVertexIndices = [0, 1, 2, 3]
        point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
        texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 1)] (
            interpolation = "vertex"
        )
        rel material:binding = </World/Red>
    }

    def Material "Red"
    {
        def Shader "S"
        {
            uniform token info:id = "UsdPreviewSurface"
            color3f inputs:diffuseColor = (1, 0, 0)
            float inputs:roughness = 0.25
            float inputs:metallic = 1
        }
    }
}
"#;

    #[test]
    fn an_animated_layer_comes_back_with_a_clip() {
        let layer = parse(include_str!("testdata/anim.usda")).unwrap();
        let scene = to_scene(&layer);

        let clip = scene.animations.first().expect("a clip");
        // 48 time codes at 24 a second.
        assert_eq!(clip.duration, 2.0);

        // The prim has a moving translate and a moving rotate, so it gets a
        // position and a quaternion track — and no scale track, because
        // nothing scales it.
        let spin = scene.roots[0];
        let targets: Vec<_> = clip
            .tracks
            .iter()
            .filter(|t| t.object == spin)
            .map(|t| format!("{:?}", t.target))
            .collect();
        assert!(targets.contains(&"Position".to_string()), "{targets:?}");
        assert!(targets.contains(&"Quaternion".to_string()), "{targets:?}");
        assert!(!targets.contains(&"Scale".to_string()), "{targets:?}");
    }

    #[test]
    fn the_position_track_holds_what_the_samples_said() {
        let layer = parse(include_str!("testdata/anim.usda")).unwrap();
        let scene = to_scene(&layer);
        let clip = &scene.animations[0];
        let track = clip
            .tracks
            .iter()
            .find(|t| matches!(t.target, TrackTarget::Position))
            .expect("position track");

        // Times are seconds, not time codes.
        assert_eq!(track.times, vec![0.0, 1.0, 2.0]);
        let TrackValues::Vector(values) = &track.values else {
            panic!("expected vectors");
        };
        assert_eq!(values[0], Vector3::new(0.0, 0.0, 0.0));
        assert_eq!(values[1], Vector3::new(10.0, 0.0, 0.0));
        assert_eq!(values[2], Vector3::new(10.0, 10.0, 0.0));
    }

    /// A prim keyed on two different frame sets gets one track covering both,
    /// because the transform is one thing however it was authored.
    #[test]
    fn ops_keyed_on_different_frames_are_merged() {
        let layer = parse(
            r#"#usda 1.0
def Xform "A"
{
    double3 xformOp:translate.timeSamples = { 0: (0, 0, 0), 10: (1, 0, 0) }
    float3 xformOp:scale.timeSamples = { 5: (1, 1, 1), 20: (2, 2, 2) }
    uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
}
"#,
        )
        .unwrap();
        let scene = to_scene(&layer);
        let clip = &scene.animations[0];
        let position = clip
            .tracks
            .iter()
            .find(|t| matches!(t.target, TrackTarget::Position))
            .unwrap();
        // The union of both key sets: 0, 5, 10, 20.
        assert_eq!(position.times.len(), 4);
        assert_eq!(
            clip.tracks
                .iter()
                .filter(|t| matches!(t.target, TrackTarget::Scale))
                .count(),
            1
        );
    }

    /// The scene is posed at the first frame, not left at the identity.
    #[test]
    fn a_scene_is_built_at_the_start_of_its_range() {
        let layer = parse(
            r#"#usda 1.0
(
    startTimeCode = 10
    endTimeCode = 20
)
def Xform "A"
{
    double3 xformOp:translate.timeSamples = { 0: (0, 0, 0), 10: (7, 0, 0), 20: (9, 0, 0) }
    uniform token[] xformOpOrder = ["xformOp:translate"]
}
"#,
        )
        .unwrap();
        let scene = to_scene(&layer);
        let a = scene.arena.get(scene.roots[0]).unwrap();
        assert_eq!(a.position, Vector3::new(7.0, 0.0, 0.0), "posed at frame 10");

        // And any other instant can be asked for directly.
        let midway = to_scene_at(&layer, 15.0);
        assert_eq!(
            midway.arena.get(midway.roots[0]).unwrap().position,
            Vector3::new(8.0, 0.0, 0.0)
        );
    }

    /// `xformOp:transform` is a row-vector matrix with the translation in its
    /// last row. Read transposed, a part offset by a matrix — a laptop's lid
    /// moved back to its hinge — lost the offset and sat at its parent's
    /// origin, and every matrix rotation turned the wrong way.
    #[test]
    fn a_matrix_op_keeps_its_translation_and_turns_the_right_way() {
        // A quarter turn about +z (x goes to y, written as USD's first row),
        // then a move to (1, 2, 3).
        let layer = parse(
            r#"#usda 1.0
def Xform "A"
{
    matrix4d xformOp:transform = ( (0, 1, 0, 0), (-1, 0, 0, 0), (0, 0, 1, 0), (1, 2, 3, 1) )
    uniform token[] xformOpOrder = ["xformOp:transform"]
}
"#,
        )
        .unwrap();
        let scene = to_scene(&layer);
        let a = scene.arena.get(scene.roots[0]).unwrap();
        assert!(
            (a.position - Vector3::new(1.0, 2.0, 3.0)).length() < 1e-5,
            "{:?}",
            a.position
        );
        let x = a.quaternion * Vector3::new(1.0, 0.0, 0.0);
        assert!(
            (x - Vector3::new(0.0, 1.0, 0.0)).length() < 1e-5,
            "x went to {x:?}"
        );
    }

    /// An animated mesh still has geometry — the points resolve to the frame
    /// the scene was built at rather than flattening to nothing.
    #[test]
    fn an_animated_mesh_still_has_its_points() {
        let layer = parse(include_str!("testdata/anim.usda")).unwrap();
        let scene = to_scene(&layer);
        let body = scene
            .arena
            .get(scene.arena.get(scene.roots[0]).unwrap().children[0])
            .unwrap();
        let crate::core::ObjectKind::Mesh(mesh) = &body.kind else {
            panic!("expected a mesh");
        };
        let position = mesh.geometry.get_attribute("position").expect("positions");
        assert_eq!(position.count(), 3);
        // Frame 0's triangle, not frame 48's.
        assert_eq!(&position.array[..3], &[0.0, 0.0, 0.0]);
        assert_eq!(&position.array[3..6], &[1.0, 0.0, 0.0]);
    }

    #[test]
    fn a_static_layer_has_no_clip() {
        let scene = to_scene(&parse(QUAD).unwrap());
        assert!(scene.animations.is_empty());
    }

    #[test]
    fn a_quad_becomes_two_triangles() {
        let layer = parse(QUAD).unwrap();
        let quad = layer.prim_at("/World/Quad").unwrap();
        let g = mesh_geometry(quad).unwrap();
        assert_eq!(g.get_attribute("position").unwrap().array.len(), 12);
        // Fanned: 4 corners give 2 triangles.
        assert_eq!(g.index.as_ref().unwrap().len(), 6);
        assert_eq!(g.get_attribute("uv").unwrap().array.len(), 8);
    }

    #[test]
    fn a_quad_is_remembered_as_one_polygon() {
        let layer = parse(QUAD).unwrap();
        let g = mesh_geometry(layer.prim_at("/World/Quad").unwrap()).unwrap();
        assert_eq!(g.polygon_counts(), Some(&[2u32][..]));
        assert_eq!(g.polygon_loop(0..2), Some(vec![0, 1, 2, 3]));

        // Face-varying splits the vertices per corner; the polygon survives.
        let src = QUAD.replace(
            "interpolation = \"vertex\"",
            "interpolation = \"faceVarying\"",
        );
        let layer = parse(&src).unwrap();
        let g = mesh_geometry(layer.prim_at("/World/Quad").unwrap()).unwrap();
        assert_eq!(g.polygon_counts(), Some(&[2u32][..]));
        assert_eq!(g.polygon_loop(0..2).map(|l| l.len()), Some(4));

        // Left-handed reverses the outline along with the triangles.
        let src = QUAD.replace(
            "int[] faceVertexCounts = [4]",
            "uniform token orientation = \"leftHanded\"\n        int[] faceVertexCounts = [4]",
        );
        let layer = parse(&src).unwrap();
        let g = mesh_geometry(layer.prim_at("/World/Quad").unwrap()).unwrap();
        assert_eq!(g.polygon_loop(0..2), Some(vec![0, 3, 2, 1]));
    }

    #[test]
    fn left_handed_orientation_flips_the_winding() {
        let right = parse(QUAD).unwrap();
        let a = mesh_geometry(right.prim_at("/World/Quad").unwrap()).unwrap();
        let flipped = QUAD.replace(
            "int[] faceVertexCounts = [4]",
            "uniform token orientation = \"leftHanded\"\n        int[] faceVertexCounts = [4]",
        );
        let left = parse(&flipped).unwrap();
        let b = mesh_geometry(left.prim_at("/World/Quad").unwrap()).unwrap();
        let (ia, ib) = (a.index.clone().unwrap(), b.index.clone().unwrap());
        assert_eq!(ia.len(), ib.len());
        // Same first corner, opposite order for the other two.
        assert_eq!((ia[0], ia[1], ia[2]), (ib[0], ib[2], ib[1]));
    }

    #[test]
    fn face_varying_primvars_split_the_vertices() {
        let src = QUAD.replace(
            "interpolation = \"vertex\"",
            "interpolation = \"faceVarying\"",
        );
        let layer = parse(&src).unwrap();
        let g = mesh_geometry(layer.prim_at("/World/Quad").unwrap()).unwrap();
        // Unindexed: six corners, because a per-corner UV cannot be shared.
        assert!(g.index.is_none());
        assert_eq!(g.get_attribute("position").unwrap().array.len(), 18);
        assert_eq!(g.get_attribute("uv").unwrap().array.len(), 12);
    }

    #[test]
    fn transforms_come_from_the_op_order() {
        let layer = parse(QUAD).unwrap();
        let scene = to_scene(&layer);
        let world = scene.arena.get(scene.roots[0]).unwrap();
        assert_eq!(world.name, "World");
        assert!((world.position.x - 1.0).abs() < 1e-6);
        assert!((world.position.z - 3.0).abs() < 1e-6);
    }

    #[test]
    fn an_op_that_is_not_in_the_order_is_inactive() {
        // USD applies exactly what xformOpOrder lists; an authored op that is
        // left out is deliberately off.
        let src = QUAD.replace(
            "uniform token[] xformOpOrder = [\"xformOp:translate\"]",
            "uniform token[] xformOpOrder = []",
        );
        let scene = to_scene(&parse(&src).unwrap());
        let world = scene.arena.get(scene.roots[0]).unwrap();
        assert!(world.position.length() < 1e-9);
    }

    #[test]
    fn the_bound_material_is_read() {
        let layer = parse(QUAD).unwrap();
        let scene = to_scene(&layer);
        let world = scene.roots[0];
        let quad = scene.arena.get(world).unwrap().children[0];
        let mesh = scene.arena.get(quad).unwrap();
        let material = match &mesh.kind {
            crate::core::ObjectKind::Mesh(m) => m.material.clone(),
            other => panic!("expected a mesh, got {other:?}"),
        };
        match &*material {
            Material::Standard(s) => {
                assert!((s.color.r - 1.0).abs() < 1e-6);
                assert!((s.roughness - 0.25).abs() < 1e-6);
                assert!((s.metalness - 1.0).abs() < 1e-6);
            }
            other => panic!("expected a standard material, got {other:?}"),
        }
    }

    #[test]
    fn the_hierarchy_is_preserved() {
        let scene = to_scene(&parse(QUAD).unwrap());
        assert_eq!(scene.roots.len(), 1);
        // World has the mesh and the material prim beneath it; the material is
        // a group with nothing to draw, which is still a node.
        assert_eq!(scene.arena.get(scene.roots[0]).unwrap().children.len(), 2);
    }
}

#[cfg(test)]
mod animation_kinds {
    use super::*;
    use crate::animation::{TrackTarget, TrackValues};
    use crate::core::ObjectKind;

    fn stage() -> UsdScene {
        to_scene(
            &super::super::parse::parse(include_str!("testdata/allanim.usda")).expect("parses"),
        )
    }

    fn id_of(scene: &UsdScene, name: &str) -> ObjectId {
        fn walk(scene: &UsdScene, id: ObjectId, name: &str) -> Option<ObjectId> {
            let node = scene.arena.get(id)?;
            if node.name == name {
                return Some(id);
            }
            node.children.iter().find_map(|c| walk(scene, *c, name))
        }
        scene
            .roots
            .iter()
            .find_map(|r| walk(scene, *r, name))
            .unwrap_or_else(|| panic!("no prim called {name}"))
    }

    fn tracks_for(scene: &UsdScene, object: ObjectId) -> Vec<&crate::animation::KeyframeTrack> {
        scene
            .animations
            .iter()
            .flat_map(|c| &c.tracks)
            .filter(|t| t.object == object)
            .collect()
    }

    /// A lamp that brightens and changes colour. Neither is a transform op, so
    /// the op-stack pass never saw them and the lamp stayed as it started.
    #[test]
    fn a_lights_brightness_and_colour_animate() {
        let scene = stage();
        let lamp = id_of(&scene, "Lamp");
        let tracks = tracks_for(&scene, lamp);

        let intensity = tracks
            .iter()
            .find(|t| matches!(t.target, TrackTarget::Intensity))
            .expect("an intensity track");
        assert_eq!(intensity.times, vec![0.0, 2.0], "48 codes at 24 a second");
        let TrackValues::Scalar(values) = &intensity.values else {
            panic!("scalars");
        };
        assert_eq!(values, &vec![0.0, 100.0]);

        let colour = tracks
            .iter()
            .find(|t| matches!(t.target, TrackTarget::Color))
            .expect("a colour track");
        let TrackValues::Color(values) = &colour.values else {
            panic!("colours");
        };
        assert_eq!((values[0].r, values[0].b), (1.0, 0.0));
        assert_eq!((values[1].r, values[1].b), (0.0, 1.0));
    }

    /// `visibility` is a token rather than a number, so what animates is which
    /// of two words it holds.
    #[test]
    fn visibility_animates() {
        let scene = stage();
        let track = tracks_for(&scene, id_of(&scene, "Blinker"))
            .into_iter()
            .find(|t| matches!(t.target, TrackTarget::Visibility))
            .expect("a visibility track");
        let TrackValues::Scalar(values) = &track.values else {
            panic!("scalars");
        };
        assert_eq!(values, &vec![1.0, 0.0, 1.0], "on, off, on");
    }

    /// A material's colour is animated on the shader its binding names, which
    /// is a different prim in a different part of the tree.
    #[test]
    fn a_bound_materials_colour_animates() {
        let scene = stage();
        let track = tracks_for(&scene, id_of(&scene, "Painted"))
            .into_iter()
            .find(|t| matches!(t.target, TrackTarget::Color))
            .expect("the bound material's colour");
        let TrackValues::Color(values) = &track.values else {
            panic!("colours");
        };
        assert_eq!((values[0].r, values[0].g, values[0].b), (1.0, 1.0, 0.0));
        assert_eq!((values[1].r, values[1].g, values[1].b), (0.0, 1.0, 1.0));
    }

    /// Animated vertices become morph targets: one per frame after the first,
    /// each holding its difference from the base, with weights that ramp one
    /// into the next.
    #[test]
    fn animated_vertices_become_morph_targets() {
        let scene = stage();
        let (_, morphs) = scene
            .morph_targets
            .iter()
            .find(|(name, _)| name == "Wobble")
            .expect("the wobbling mesh");
        assert_eq!(morphs.targets.len(), 2, "three frames, two targets");

        // Frame 1 moves the second point from x=1 to x=2.
        assert_eq!(morphs.targets[0].position_delta[3], 1.0);
        // Frame 2 moves the third point from y=1 to y=3.
        assert_eq!(morphs.targets[1].position_delta[7], 2.0);

        let tracks = tracks_for(&scene, id_of(&scene, "Wobble"));
        let weights: Vec<&crate::animation::KeyframeTrack> = tracks
            .iter()
            .filter(|t| matches!(t.target, TrackTarget::MorphWeight { .. }))
            .copied()
            .collect();
        assert_eq!(weights.len(), 2);

        // Each weight is one at its own frame and zero at the others, so the
        // blend between two neighbours is the linear interpolation USD means.
        let TrackValues::Scalar(values) = &weights[0].values else {
            panic!("scalars");
        };
        assert_eq!(values, &vec![0.0, 1.0, 0.0]);
        let TrackValues::Scalar(values) = &weights[1].values else {
            panic!("scalars");
        };
        assert_eq!(values, &vec![0.0, 0.0, 1.0]);

        // The targets are on the geometry too, so the renderers play them.
        let ObjectKind::Mesh(m) = &scene.arena.get(id_of(&scene, "Wobble")).unwrap().kind else {
            panic!("a mesh");
        };
        assert!(m.geometry.morph_targets_relative);
        assert_eq!(m.geometry.morph_attributes["position"].len(), 2);
        assert_eq!(m.geometry.morph_attributes["position"][1].array[7], 2.0);
        assert_eq!(m.morph_influences, vec![0.0, 0.0]);
        assert_eq!(m.morph_target_dictionary.get("frame2"), Some(&1));

        // And the mesh itself is the first frame, so a stage opened at its
        // start looks right before anything is played.
        let ObjectKind::Mesh(mesh) = &scene.arena.get(id_of(&scene, "Wobble")).unwrap().kind else {
            panic!("a mesh");
        };
        assert_eq!(
            &mesh.geometry.get_attribute("position").unwrap().array[3..5],
            &[1.0, 0.0]
        );
    }

    /// And every one of them again out of the crate form.
    #[test]
    fn every_kind_survives_the_binary_form() {
        let binary = to_scene(
            &super::super::UsdLoader::parse_layer(include_bytes!("testdata/allanim.usdc"))
                .expect("the crate parses"),
        );
        let kinds: std::collections::BTreeSet<String> = binary
            .animations
            .iter()
            .flat_map(|c| &c.tracks)
            .map(|t| format!("{:?}", t.target))
            .collect();
        for expected in ["Intensity", "Visibility", "Color"] {
            assert!(
                kinds.iter().any(|k| k.contains(expected)),
                "{expected} missing from {kinds:?}"
            );
        }
        assert!(binary.morph_targets.iter().any(|(n, _)| n == "Wobble"));
    }
}