polysmelt 0.23.0

Pure-Rust 3D asset interchange: glTF/GLB reading and writing, meshopt compression, and readers for common mesh formats, SketchUp included
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
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
//! Autodesk 3DS, read here rather than by Blender, whose 3DS importer has been an extension (not shipped) since 4.2.
//! A 3DS file is nested chunks (`u16` id, `u32` length counting its 6-byte header). The editor chunk holds the
//! objects (triangle meshes, cameras, lights) and the materials; the keyframer chunk beside it holds the hierarchy and
//! the animation.
//!
//! Each object becomes a node and its mesh, with a primitive per material. Mesh vertices are stored in world space
//! (the mesh matrix only records how they got there), so an object the keyframer doesn't place keeps them as they
//! are. The keyframer's object nodes become the hierarchy: their first keys are the rest pose and their tracks the
//! animation, its TCB splines as glTF cubic splines (rotations as linear, between the turns the keys add up to). A
//! node's parent can also be a camera, a light or the target one aims at, which have nodes of their own in the
//! keyframer; those join the hierarchy when something hangs under them. A camera or spotlight node stands where its
//! position track has it and turns to face its target (itself a node with a position track), rolled as its roll
//! track says: its children are in that frame, which looks down -Z with Y up, as glTF's cameras do. Its turning
//! under animation is sampled each frame from the three tracks. A
//! placed mesh is moved into its node's space as lib3ds does (back through the mesh matrix and the pivot), unless that
//! wouldn't put it back where the editor has it at rest or at any later key (a file saved on a later frame holds that
//! frame's vertices and mesh matrix); then the rest pose decides. Materials have a diffuse color, a
//! transparency and maybe a texture named by file; every value they hold, maps included, is kept in `extras`. Of the
//! other maps, the specular map tints the highlight, the self-illumination map glows, and the bump map is the normal
//! map when its image is one (scaled by its amount); a bump map that is a height map, the shininess map (glossiness,
//! the inverse of glTF's roughness) and the reflection map (an environment) have no glTF slot and stay in `extras`.
//! Smoothing groups are bit masks: faces sharing a bit share normals at their common corners (by position, so a
//! texture seam doesn't crease them), and a material shaded flat ignores them. A mesh matrix that mirrors leaves its
//! faces wound inside out in world space; they are turned back. An opacity map that is the color map uses its alpha.
//! 3DS is Z up; the data stays so, as the file has it, under the root node (`RootNode`) that turns it to glTF's Y
//! up and scales it by the file's master scale.
//!
//! The source info has Z up and right-handed, declared (3D Studio's space is every file's), 30 frames a second
//! assumed when there is a keyframer (the file doesn't say), and no unit: 3DS names none, so its length is unknown. The `MASTER_SCALE` chunk is, in Autodesk's
//! words, "a master scale factor for all geometry coordinates", which 3ds Max's importer multiplies them by: the
//! root node scales by it (by 1 when the chunk is missing or isn't a positive number), and camera clip planes and
//! light ranges with it. Autodesk's toolkit adds that "a master scale of 1.0 translates into one unit per inch", but
//! the file has no field for a unit and other programs write their own units with a master scale of 1, so no unit
//! is assumed and `converted` doesn't list `units`: a file with a master scale of 1 is the size its numbers say.
//! The master scale is kept as `masterScale`, beside
//! the `meshVersion`, the `ambient` light and the `keyframer`'s name, revision, length and segment.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;

use serde_json::{Map, Value, json};

use super::frame::{self, Frame};
use super::keys::{self, Interp, Track};
use super::xform::{self, IDENTITY, M4};
use crate::Result;
use crate::assets::Assets;
use crate::bytes::{Le, array_at, f32_at, floats, records, u16_at, u32_at, until_nul};
use crate::document::{Builder, Document, Keep};
use crate::images::Images;
use crate::legacy_material::{self, Highlight, Phong, Rgb, Transparency};
use crate::material::{self, Factor, Full, Specular, Tex, UvTransform};
use crate::mesh::{FastMap, GRAY, Material, Prim, face_normal, srgb_to_linear};
use crate::num::{u32_of, usize_of};
use crate::quat;
use crate::source::{Axis, Fact, Handedness, SourceInfo};

const MAIN: u16 = 0x4D4D;
/// A 3D Studio project file, which holds the same editor chunk.
const PROJECT: u16 = 0xC23D;
const VERSION: u16 = 0x0002;
const MASTER_SCALE: u16 = 0x0100;
const AMBIENT_LIGHT: u16 = 0x2100;
const EDITOR: u16 = 0x3D3D;
const MESH_VERSION: u16 = 0x3D3E;
const OBJECT: u16 = 0x4000;
const OBJ_HIDDEN: u16 = 0x4010;
const TRIMESH: u16 = 0x4100;
const VERTICES: u16 = 0x4110;
const FACES: u16 = 0x4120;
const FACE_MATERIAL: u16 = 0x4130;
const UVS: u16 = 0x4140;
const SMOOTHING: u16 = 0x4150;
const MESH_MATRIX: u16 = 0x4160;
const LIGHT: u16 = 0x4600;
const DL_SPOTLIGHT: u16 = 0x4610;
const DL_OFF: u16 = 0x4620;
const DL_ATTENUATE: u16 = 0x4625;
const DL_INNER_RANGE: u16 = 0x4659;
const DL_OUTER_RANGE: u16 = 0x465A;
const DL_MULTIPLIER: u16 = 0x465B;
const CAMERA: u16 = 0x4700;
const CAM_RANGES: u16 = 0x4720;
const MATERIAL: u16 = 0xAFFF;
const MAT_NAME: u16 = 0xA000;
const MAT_AMBIENT: u16 = 0xA010;
const MAT_DIFFUSE: u16 = 0xA020;
const MAT_SPECULAR: u16 = 0xA030;
const MAT_SHININESS: u16 = 0xA040;
const MAT_SHIN_STRENGTH: u16 = 0xA041;
const MAT_TRANSPARENCY: u16 = 0xA050;
const MAT_XPFALL: u16 = 0xA052;
const MAT_REFBLUR: u16 = 0xA053;
const MAT_TWO_SIDE: u16 = 0xA081;
const MAT_ADDITIVE: u16 = 0xA083;
const MAT_SELF_ILPCT: u16 = 0xA084;
const MAT_WIRE: u16 = 0xA085;
const MAT_WIRESIZE: u16 = 0xA087;
const MAT_SHADING: u16 = 0xA100;
const MAT_TEXTURE: u16 = 0xA200;
const MAT_SPECMAP: u16 = 0xA204;
const MAT_OPACMAP: u16 = 0xA210;
const MAT_REFLMAP: u16 = 0xA220;
const MAT_BUMPMAP: u16 = 0xA230;
const MAT_TEXTURE2: u16 = 0xA33A;
const MAT_SHINMAP: u16 = 0xA33C;
const MAT_SELFIMAP: u16 = 0xA33D;
const MAP_FILE: u16 = 0xA300;
const MAP_TILING: u16 = 0xA351;
const MAP_BLUR: u16 = 0xA353;
const MAP_USCALE: u16 = 0xA354;
const MAP_VSCALE: u16 = 0xA356;
const MAP_UOFFSET: u16 = 0xA358;
const MAP_VOFFSET: u16 = 0xA35A;
const MAP_ANGLE: u16 = 0xA35C;
const COLOR_F32: u16 = 0x0010;
const COLOR_U8: u16 = 0x0011;
const COLOR_U8_GAMMA: u16 = 0x0012;
const COLOR_F32_GAMMA: u16 = 0x0013;
const PERCENT_U16: u16 = 0x0030;
const PERCENT_F32: u16 = 0x0031;
const KEYFRAMER: u16 = 0xB000;
const OBJECT_NODE_TAG: u16 = 0xB002;
const CAMERA_NODE_TAG: u16 = 0xB003;
const TARGET_NODE_TAG: u16 = 0xB004;
const LIGHT_NODE_TAG: u16 = 0xB005;
const L_TARGET_NODE_TAG: u16 = 0xB006;
const SPOTLIGHT_NODE_TAG: u16 = 0xB007;
const KF_SEGMENT: u16 = 0xB008;
const KF_HEADER: u16 = 0xB00A;
const NODE_HDR: u16 = 0xB010;
const INSTANCE_NAME: u16 = 0xB011;
const PIVOT: u16 = 0xB013;
const POS_TRACK: u16 = 0xB020;
const ROT_TRACK: u16 = 0xB021;
const SCL_TRACK: u16 = 0xB022;
const ROLL_TRACK: u16 = 0xB024;
const NODE_ID: u16 = 0xB030;

/// Frames a second: the readers' shared assumption. The keyframer counts frames and no chunk gives their rate (the
/// keyframer header is a revision, a name and a frame count, `KFSEG` a range and `KFCURTIME` a frame:
/// `kfdata_read` in lib3ds's `lib3ds_file.c`); it's 3ds Max's scene setting, not the file's.
#[allow(clippy::cast_possible_truncation, reason = "a small whole number")]
const FRAMES_PER_SECOND: f32 = keys::ASSUMED_FRAME_RATE as f32;

/// The chunks in `data`, as (id, body). A chunk claiming more than is left (a wrong length, a cut-off file) gets
/// what is left; the readers below take only whole records from it.
fn chunks(mut data: &[u8]) -> impl Iterator<Item = (u16, &[u8])> {
    std::iter::from_fn(move || {
        let id = u16_at(data, 0)?;
        let len = usize_of(u64::from(u32_at(data, 2)?));
        if len < 6 {
            return None;
        }
        let (chunk, rest) = data.split_at(len.min(data.len()));
        data = rest;
        Some((id, chunk.get(6..)?))
    })
}

fn vec3_at(d: &[u8], i: usize) -> Option<[f32; 3]> {
    array_at::<12>(d, i).map(|b| floats(Le, b))
}

/// A zero-terminated name and what follows it.
fn cstr(d: &[u8]) -> (String, &[u8]) {
    let name = until_nul(d);
    (
        crate::bytes::text(name).trim_end().to_owned(),
        d.get(name.len() + 1..).unwrap_or_default(),
    )
}

/// An `f32` as the decimal it was written as (0.1, not 0.10000000149011612); null when it isn't a number.
fn clean(x: f32) -> Value {
    if x.is_finite() {
        json!(x.to_string().parse::<f64>().unwrap_or(0.0))
    } else {
        Value::Null
    }
}

fn cleans(xs: &[f32]) -> Value {
    Value::Array(xs.iter().map(|&x| clean(x)).collect())
}

/// The color chunk shown, of those in `d`. Every form holds the color picker's values, which are sRGB. 3D Studio R3
/// added "linear" twins (0x0012, 0x0013) that 3ds Max writes beside the plain ones, normally equal; the plain one is
/// the color shown, so it wins, and 8-bit wins over float.
fn color_chunk(d: &[u8]) -> Option<(u16, &[u8])> {
    let rank = |id| match id {
        COLOR_U8 => 0,
        COLOR_F32 => 1,
        COLOR_U8_GAMMA => 2,
        _ => 3,
    };
    chunks(d)
        .filter(|&(id, b)| match id {
            COLOR_U8 | COLOR_U8_GAMMA => b.len() >= 3,
            COLOR_F32 | COLOR_F32_GAMMA => b.len() >= 12,
            _ => false,
        })
        .min_by_key(|&(id, _)| rank(id))
}

fn rgb(id: u16, b: &[u8]) -> [f32; 3] {
    match id {
        COLOR_U8 | COLOR_U8_GAMMA => [b[0], b[1], b[2]].map(|v| f32::from(v) / 255.0),
        _ => vec3_at(b, 0).unwrap_or_default(),
    }
}

/// The color shown, as linear RGB.
fn color(d: &[u8]) -> Option<[f32; 3]> {
    color_chunk(d).map(|(id, b)| rgb(id, b).map(|v| srgb_to_linear(v.clamp(0.0, 1.0))))
}

/// The color shown, as written: 0 to 255, or 0 to 1 for a float chunk.
fn color_raw(d: &[u8]) -> Option<Value> {
    color_chunk(d).map(|(id, b)| match id {
        COLOR_U8 | COLOR_U8_GAMMA => json!([b[0], b[1], b[2]]),
        _ => cleans(&rgb(id, b)),
    })
}

/// A percent chunk among `d`, as written (0 to 100).
fn percent_raw(d: &[u8]) -> Option<f32> {
    chunks(d).find_map(|(id, b)| percent_of(id, b))
}

fn percent_of(id: u16, b: &[u8]) -> Option<f32> {
    match id {
        PERCENT_U16 => u16_at(b, 0).map(f32::from),
        PERCENT_F32 => f32_at(b, 0).filter(|v| v.is_finite()),
        _ => None,
    }
}

fn percent(d: &[u8]) -> Option<f32> {
    percent_raw(d).map(|p| p / 100.0)
}

struct Mat {
    name: String,
    color: [f32; 3],
    alpha: f32,
    texture: Option<String>,
    glossiness: Option<f32>,
    /// The highlight's color (sRGB, as written), and how strong it is (0 to 1).
    specular: Option<[f32; 3]>,
    shine_strength: Option<f32>,
    self_illum: f32,
    two_sided: bool,
    /// Every value the material chunk holds, by name, as written.
    raw: Map<String, Value>,
}

fn material(d: &[u8]) -> Mat {
    let mut m = Mat {
        name: String::new(),
        color: [GRAY[0], GRAY[1], GRAY[2]],
        alpha: 1.0,
        texture: None,
        glossiness: None,
        specular: None,
        shine_strength: None,
        self_illum: 0.0,
        two_sided: false,
        raw: Map::new(),
    };
    let mut maps = Map::new();
    for (id, b) in chunks(d) {
        let (key, value) = match id {
            MAT_NAME => {
                m.name = cstr(b).0;
                continue;
            }
            MAT_AMBIENT | MAT_DIFFUSE | MAT_SPECULAR => {
                if id == MAT_DIFFUSE {
                    m.color = color(b).unwrap_or(m.color);
                } else if id == MAT_SPECULAR {
                    m.specular = color_chunk(b).map(|(id, b)| rgb(id, b));
                }
                let key = match id {
                    MAT_AMBIENT => "ambient",
                    MAT_DIFFUSE => "diffuse",
                    _ => "specular",
                };
                (key, color_raw(b))
            }
            MAT_SHININESS | MAT_SHIN_STRENGTH | MAT_TRANSPARENCY | MAT_XPFALL | MAT_REFBLUR | MAT_SELF_ILPCT => {
                let p = percent(b).map(|p| p.clamp(0.0, 1.0));
                let key = match id {
                    MAT_SHININESS => {
                        m.glossiness = p;
                        "shininess"
                    }
                    MAT_TRANSPARENCY => {
                        m.alpha = 1.0 - p.unwrap_or(0.0);
                        "transparency"
                    }
                    MAT_SELF_ILPCT => {
                        m.self_illum = p.unwrap_or(0.0);
                        "selfIllumination"
                    }
                    MAT_SHIN_STRENGTH => {
                        m.shine_strength = p;
                        "shininessStrength"
                    }
                    MAT_XPFALL => "transparencyFalloff",
                    _ => "reflectionBlur",
                };
                (key, percent_raw(b).map(clean))
            }
            MAT_TWO_SIDE => {
                m.two_sided = true;
                ("twoSided", Some(json!(true)))
            }
            MAT_ADDITIVE => ("additive", Some(json!(true))),
            MAT_WIRE => ("wire", Some(json!(true))),
            MAT_WIRESIZE => ("wireSize", f32_at(b, 0).map(clean)),
            MAT_SHADING => ("shading", u16_at(b, 0).map(|s| json!(s))),
            MAT_TEXTURE | MAT_TEXTURE2 | MAT_SPECMAP | MAT_OPACMAP | MAT_REFLMAP | MAT_BUMPMAP | MAT_SHINMAP
            | MAT_SELFIMAP => {
                let (file, map) = texture_map(b);
                if id == MAT_TEXTURE {
                    m.texture = file;
                }
                let key = match id {
                    MAT_TEXTURE => "texture",
                    MAT_TEXTURE2 => "texture2",
                    MAT_SPECMAP => "specular",
                    MAT_OPACMAP => "opacity",
                    MAT_REFLMAP => "reflection",
                    MAT_BUMPMAP => "bump",
                    MAT_SHINMAP => "shininess",
                    _ => "selfIllumination",
                };
                maps.insert(key.into(), Value::Object(map));
                continue;
            }
            _ => continue,
        };
        if let Some(v) = value {
            m.raw.insert(key.into(), v);
        }
    }
    if !maps.is_empty() {
        m.raw.insert("maps".into(), Value::Object(maps));
    }
    m
}

/// What a material shows beyond its flat view: how its color map is laid out, its highlight and the map that
/// tints it, its glow map, its normal map, and whether the color map's alpha cuts it.
#[derive(Default)]
struct Look {
    color: Option<Tex>,
    specular: Option<Specular<Tex>>,
    emissive: Option<Tex>,
    normal: Option<Tex>,
    alpha_source: bool,
}

/// Whether the bump map `file` is a tangent-space normal map rather than the height map 3DS bump maps were made as.
/// The image says when it can: gray is a height map, and a PNG's sampled pixels are a normal map when they are mostly
/// unit vectors leaning toward +Z (bluish, red and green near the middle). A color JPEG, or a PNG without a decoder
/// for its pixels, goes by its name (`_n`, `normal`, `nrm`, ...). Unreadable, it's neither.
fn bump_is_normal_map(assets: &dyn Assets, dir: &Path, file: &str) -> bool {
    let Some(path) = assets.find(file, dir) else {
        return false;
    };
    let Some(image) = assets.read(&path).and_then(|b| assets.image(&b, &path)) else {
        return false;
    };
    let b = &image.bytes;
    if b.starts_with(b"\x89PNG") {
        // IHDR's color type: gray, or gray and alpha.
        if matches!(b.get(25), Some(0 | 4)) {
            return false;
        }
        #[cfg(any(
            feature = "webp",
            feature = "skp",
            feature = "tga",
            feature = "bmp",
            feature = "gif",
            feature = "tiff",
            feature = "psd",
            feature = "dds"
        ))]
        if let Some(pixels) = crate::png::sample(b) {
            return normal_pixels(&pixels);
        }
    } else if jpeg_components(b) == Some(1) {
        return false;
    }
    named_normal_map(file)
}

/// Whether sampled RGB pixels read as a tangent-space normal map: on average blue well above red and green, those
/// near the middle, and three in four of them unit vectors (within 20%) facing +Z.
#[cfg_attr(
    not(any(
        feature = "webp",
        feature = "skp",
        feature = "tga",
        feature = "bmp",
        feature = "gif",
        feature = "tiff",
        feature = "psd",
        feature = "dds"
    )),
    allow(dead_code, reason = "only builds that read a PNG's pixels sample them")
)]
fn normal_pixels(pixels: &[[u8; 3]]) -> bool {
    let n = pixels.len().max(1);
    let mut sum = [0usize; 3];
    let mut unit = 0;
    for p in pixels {
        for (s, &c) in sum.iter_mut().zip(p) {
            *s += usize::from(c);
        }
        let v = p.map(|c| f32::from(c) / 127.5 - 1.0);
        let len2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
        if v[2] > 0.0 && (0.64..=1.44).contains(&len2) {
            unit += 1;
        }
    }
    let [r, g, b] = sum.map(|s| s / n);
    let middle = |c: usize| (88..=168).contains(&c);
    b >= r.max(g) + 48 && middle(r) && middle(g) && unit * 4 >= n * 3
}

/// A JPEG's color components (1 for gray), from its frame header.
fn jpeg_components(b: &[u8]) -> Option<u8> {
    let mut at = 2;
    loop {
        if *b.get(at)? != 0xFF {
            return None;
        }
        let marker = *b.get(at.checked_add(1)?)?;
        match marker {
            // Fill bytes.
            0xFF => at += 1,
            // Start of frame, any kind (not DHT, JPG or DAC).
            0xC0..=0xCF if !matches!(marker, 0xC4 | 0xC8 | 0xCC) => return b.get(at.checked_add(9)?).copied(),
            // Markers without a length, or the scan: no frame header.
            0xD0..=0xDA | 0x01 => return None,
            _ => at = at.checked_add(2 + usize::from(u16::from_be_bytes(array_at(b, at.checked_add(2)?)?)))?,
        }
    }
}

/// Whether a texture's file name marks it as a normal map: `normal`, `norm`, `nrm`, `nmap` or `ddn` in it, or `_n`,
/// `-n`, `_nm` or `_nor` ending it.
fn named_normal_map(file: &str) -> bool {
    let name = file.rsplit(['/', '\\']).next().unwrap_or(file);
    let stem = name.rsplit_once('.').map_or(name, |(s, _)| s).to_ascii_lowercase();
    ["norm", "nrm", "nmap", "ddn"].iter().any(|k| stem.contains(k))
        || ["_n", "-n", "_nm", "_nor"].iter().any(|k| stem.ends_with(k))
}

/// Bit flags of a map's tiling: mirrored, not tiled, the image's alpha as opacity.
const TILE_MIRROR: u64 = 0x2;
const TILE_NONE: u64 = 0x10;
const TILE_ALPHA: u64 = 0x40;

/// `image` laid out as a map says: its tiling as the wrap and its scale, offset and angle as a texture transform.
/// 3DS's are taken as `uv' = rotate(angle) * scale * uv + offset` with V up, and turned into glTF's V-down UVs.
fn map_tex(map: &Map<String, Value>, image: usize) -> Tex {
    #[allow(clippy::cast_possible_truncation, reason = "they were f32s")]
    let num = |k: &str, d: f32| map.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32);
    let scale = |k: &str| Some(num(k, 1.0)).filter(|s| *s != 0.0).unwrap_or(1.0);
    let (su, sv) = (scale("uScale"), scale("vScale"));
    let (tu, tv) = (num("uOffset", 0.0), num("vOffset", 0.0));
    let angle = num("rotation", 0.0).to_radians();
    let (sin, cos) = angle.sin_cos();
    let mut t = Tex::new(image);
    let x = UvTransform {
        offset: [tu - sv * sin, 1.0 - tv - sv * cos],
        rotation: angle,
        scale: [su, sv],
    };
    // With V flipped, the identity comes back as (0, 0) offset.
    if (su, sv, tu, tv, angle) != (1.0, 1.0, 0.0, 0.0, 0.0) {
        t.transform = Some(x);
    }
    let tiling = map.get("tiling").and_then(Value::as_u64).unwrap_or(0);
    if tiling & TILE_NONE != 0 {
        t.wrap = [material::CLAMP; 2];
    } else if tiling & TILE_MIRROR != 0 {
        t.wrap = [material::MIRROR; 2];
    }
    t
}

impl Look {
    fn full(&self, m: &Material) -> Full {
        let mut f = Full::from(m);
        if let (Some(t), Some(c)) = (&mut f.base_color_tex, &self.color) {
            *t = Tex {
                image: t.image,
                ..c.clone()
            };
            if self.alpha_source {
                let transparency = Transparency {
                    texture_alpha: true,
                    ..Transparency::of(f.base_color[3])
                };
                f.alpha = transparency.mode();
            }
        }
        f.specular.clone_from(&self.specular);
        f.emissive_tex.clone_from(&self.emissive);
        f.normal_tex.clone_from(&self.normal);
        f
    }
}

/// A texture map's file and every value it holds.
fn texture_map(d: &[u8]) -> (Option<String>, Map<String, Value>) {
    let mut file = None;
    let mut out = Map::new();
    for (id, b) in chunks(d) {
        let (key, value) = match id {
            MAP_FILE => {
                let f = cstr(b).0;
                let v = json!(f);
                file = Some(f).filter(|f| !f.is_empty());
                ("file", Some(v))
            }
            PERCENT_U16 | PERCENT_F32 => ("percent", percent_of(id, b).map(clean)),
            MAP_TILING => ("tiling", u16_at(b, 0).map(|t| json!(t))),
            MAP_BLUR => ("blur", f32_at(b, 0).map(clean)),
            MAP_USCALE => ("uScale", f32_at(b, 0).map(clean)),
            MAP_VSCALE => ("vScale", f32_at(b, 0).map(clean)),
            MAP_UOFFSET => ("uOffset", f32_at(b, 0).map(clean)),
            MAP_VOFFSET => ("vOffset", f32_at(b, 0).map(clean)),
            MAP_ANGLE => ("rotation", f32_at(b, 0).map(clean)),
            _ => continue,
        };
        if let Some(v) = value {
            out.insert(key.into(), v);
        }
    }
    (file, out)
}

#[derive(Default)]
struct Trimesh {
    vertices: Vec<[f32; 3]>,
    uvs: Vec<[f32; 2]>,
    faces: Vec<[u16; 3]>,
    smoothing: Vec<u32>,
    /// Material name → its faces.
    materials: Vec<(String, Vec<u16>)>,
    /// The mesh matrix as written: the X, Y and Z axes, then the origin.
    matrix: Option<[f32; 12]>,
}

fn trimesh(d: &[u8]) -> Trimesh {
    let mut t = Trimesh::default();
    for (id, b) in chunks(d) {
        match id {
            VERTICES => {
                let n = usize::from(u16_at(b, 0).unwrap_or(0));
                t.vertices = records::<12>(b, 2, n).iter().map(|&v| floats(Le, v)).collect();
            }
            UVS => {
                let n = usize::from(u16_at(b, 0).unwrap_or(0));
                t.uvs = records::<8>(b, 2, n).iter().map(|&v| floats(Le, v)).collect();
            }
            MESH_MATRIX => {
                let m: Option<Vec<f32>> = (0..12).map(|i| f32_at(b, i * 4)).collect();
                t.matrix = m.and_then(|m| m.try_into().ok());
            }
            FACES => {
                let n = usize::from(u16_at(b, 0).unwrap_or(0));
                t.faces = records::<8>(b, 2, n)
                    .iter()
                    .map(|f| [0, 2, 4].map(|o| u16::from_le_bytes([f[o], f[o + 1]])))
                    .collect();
                for (id, s) in chunks(b.get(2 + n * 8..).unwrap_or_default()) {
                    match id {
                        FACE_MATERIAL => {
                            let (name, rest) = cstr(s);
                            let k = usize::from(u16_at(rest, 0).unwrap_or(0));
                            let faces = records(rest, 2, k).iter().map(|&f| u16::from_le_bytes(f)).collect();
                            t.materials.push((name, faces));
                        }
                        SMOOTHING => {
                            t.smoothing = s
                                .as_chunks::<4>()
                                .0
                                .iter()
                                .take(n)
                                .map(|c| u32::from_le_bytes(*c))
                                .collect();
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
    t
}

/// A mesh matrix as a transform.
fn mesh_matrix(m: &[f32; 12]) -> M4 {
    let mut r = IDENTITY;
    for (col, axis) in m.chunks_exact(3).enumerate() {
        for (row, &v) in axis.iter().enumerate() {
            r[row][col] = f64::from(v);
        }
    }
    r
}

struct Camera {
    position: [f32; 3],
    target: [f32; 3],
    /// Degrees about the line of sight.
    roll: f32,
    /// The focal length in millimeters, on 35 mm film.
    lens: f32,
    /// Near and far.
    range: Option<[f32; 2]>,
}

fn camera(d: &[u8]) -> Option<Camera> {
    let mut c = Camera {
        position: vec3_at(d, 0)?,
        target: vec3_at(d, 12)?,
        roll: f32_at(d, 24)?,
        lens: f32_at(d, 28)?,
        range: None,
    };
    for (id, b) in chunks(d.get(32..).unwrap_or_default()) {
        if id == CAM_RANGES {
            c.range = Some([f32_at(b, 0)?, f32_at(b, 4)?]);
        }
    }
    Some(c)
}

struct Spot {
    target: [f32; 3],
    /// The full cone angles in degrees: full brightness inside the hotspot, none past the falloff.
    hotspot: f32,
    falloff: f32,
}

struct Light {
    position: [f32; 3],
    color: Option<([f32; 3], Value)>,
    spot: Option<Spot>,
    off: bool,
    multiplier: Option<f32>,
    attenuate: bool,
    inner: Option<f32>,
    outer: Option<f32>,
}

fn light(d: &[u8]) -> Option<Light> {
    let rest = d.get(12..).unwrap_or_default();
    let mut l = Light {
        position: vec3_at(d, 0)?,
        color: color(rest).zip(color_raw(rest)),
        spot: None,
        off: false,
        multiplier: None,
        attenuate: false,
        inner: None,
        outer: None,
    };
    for (id, b) in chunks(rest) {
        match id {
            DL_SPOTLIGHT => {
                l.spot = Some(Spot {
                    target: vec3_at(b, 0)?,
                    hotspot: f32_at(b, 12)?,
                    falloff: f32_at(b, 16)?,
                });
            }
            DL_OFF => l.off = true,
            DL_ATTENUATE => l.attenuate = true,
            DL_MULTIPLIER => l.multiplier = f32_at(b, 0),
            DL_INNER_RANGE => l.inner = f32_at(b, 0),
            DL_OUTER_RANGE => l.outer = f32_at(b, 0),
            _ => {}
        }
    }
    Some(l)
}

enum Body {
    Mesh(Vec<Trimesh>),
    Camera(Camera),
    Light(Light),
    Empty,
}

struct Object {
    name: String,
    hidden: bool,
    body: Body,
}

fn object(d: &[u8]) -> Object {
    let (name, rest) = cstr(d);
    let (mut trimeshes, mut cam, mut lamp, mut hidden) = (Vec::new(), None, None, false);
    for (id, b) in chunks(rest) {
        match id {
            TRIMESH => trimeshes.push(trimesh(b)),
            CAMERA => cam = cam.or_else(|| camera(b)),
            LIGHT => lamp = lamp.or_else(|| light(b)),
            OBJ_HIDDEN => hidden = true,
            _ => {}
        }
    }
    let body = if !trimeshes.is_empty() {
        Body::Mesh(trimeshes)
    } else if let Some(c) = cam {
        Body::Camera(c)
    } else if let Some(l) = lamp {
        Body::Light(l)
    } else {
        Body::Empty
    };
    Object { name, hidden, body }
}

/// A key: its frame, its tension, continuity, bias, ease to and ease from, and its value.
struct Key<const N: usize> {
    frame: i32,
    tcb: [f32; 5],
    value: [f32; N],
}

/// A track's keys: after the flags and two unused words, the key count, then each key's frame, the flags saying
/// which spline parameters follow, those parameters, and its value.
fn track<const N: usize>(b: &[u8]) -> Vec<Key<N>> {
    let n = u32_at(b, 10).unwrap_or(0);
    let mut keys = Vec::new();
    let mut o = 14;
    for _ in 0..n {
        let (Some(frame), Some(flags)) = (u32_at(b, o), u16_at(b, o.saturating_add(4))) else {
            break;
        };
        o += 6;
        let mut tcb = [0.0; 5];
        for (bit, t) in tcb.iter_mut().enumerate() {
            if flags & (1 << bit) != 0 {
                let Some(v) = f32_at(b, o) else { return keys };
                *t = v;
                o += 4;
            }
        }
        let mut value = [0.0; N];
        for v in &mut value {
            let Some(x) = f32_at(b, o) else { return keys };
            *v = x;
            o += 4;
        }
        #[allow(clippy::cast_possible_wrap, reason = "frames are signed in the file")]
        let frame = frame as i32;
        // A key whose value isn't a number places nothing: it is left out, and the track runs through the
        // keys beside it. Spline parameters that aren't numbers are the default, 0.
        if value.iter().any(|v| !v.is_finite()) {
            continue;
        }
        let tcb = tcb.map(|t| if t.is_finite() { t } else { 0.0 });
        keys.push(Key { frame, tcb, value });
    }
    keys
}

/// What a keyframer node moves.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Kind {
    /// An object (a mesh), or a dummy (`$$$DUMMY`).
    Object,
    Camera,
    /// The point a camera looks at: a node of its own, named as its camera.
    CameraTarget,
    /// A light shining every way.
    Light,
    Spot,
    /// The point a spotlight shines at, named as its light.
    SpotTarget,
}

impl Kind {
    fn of(tag: u16) -> Option<Self> {
        Some(match tag {
            OBJECT_NODE_TAG => Self::Object,
            CAMERA_NODE_TAG => Self::Camera,
            TARGET_NODE_TAG => Self::CameraTarget,
            LIGHT_NODE_TAG => Self::Light,
            SPOTLIGHT_NODE_TAG => Self::Spot,
            L_TARGET_NODE_TAG => Self::SpotTarget,
            _ => return None,
        })
    }

    /// The kind of node a node of this kind aims at.
    fn target(self) -> Option<Self> {
        match self {
            Self::Camera => Some(Self::CameraTarget),
            Self::Spot => Some(Self::SpotTarget),
            _ => None,
        }
    }

    /// The kind of node that goes with a node of this kind, under one name: what it aims at, or what aims at it.
    fn pair(self) -> Option<Self> {
        match self {
            Self::CameraTarget => Some(Self::Camera),
            Self::SpotTarget => Some(Self::Spot),
            _ => self.target(),
        }
    }
}

/// A node of the keyframer: the hierarchy's piece of an object, or of a dummy (`$$$DUMMY`), or a camera, a light or
/// the target of one.
struct KfNode {
    kind: Kind,
    id: u16,
    name: String,
    instance: String,
    parent: Option<u16>,
    pivot: [f32; 3],
    pos: Vec<Key<3>>,
    /// Angle (radians) and axis.
    rot: Vec<Key<4>>,
    scl: Vec<Key<3>>,
    /// Degrees about the line of sight, for a camera or a spotlight.
    roll: Vec<Key<1>>,
}

#[derive(Default)]
struct Keyframer {
    name: String,
    revision: Option<u16>,
    length: Option<u32>,
    segment: Option<[u32; 2]>,
    nodes: Vec<KfNode>,
}

fn keyframer(d: &[u8]) -> Keyframer {
    let mut k = Keyframer::default();
    // Nodes of every kind count toward the ids of a file that has none.
    let mut count = 0usize;
    for (id, b) in chunks(d) {
        match id {
            KF_HEADER => {
                k.revision = u16_at(b, 0);
                let (name, rest) = cstr(b.get(2..).unwrap_or_default());
                k.name = name;
                k.length = u32_at(rest, 0);
            }
            KF_SEGMENT => k.segment = u32_at(b, 0).zip(u32_at(b, 4)).map(|(s, e)| [s, e]),
            _ => {
                if let Some(kind) = Kind::of(id) {
                    let index = u16::try_from(count).unwrap_or(u16::MAX);
                    count += 1;
                    k.nodes.push(kf_node(b, index, kind));
                }
            }
        }
    }
    k
}

/// Drops the camera, light and target nodes nothing hangs under: those cameras and lights stay where the editor has
/// them. One with a node under it is part of the hierarchy, and so are the nodes above it and the one it goes with:
/// the target it aims at, or the camera or spotlight aiming at it.
fn prune(kf: &mut Keyframer) {
    let mut used: Vec<bool> = kf.nodes.iter().map(|n| n.kind == Kind::Object).collect();
    if used.iter().all(|&u| u) {
        return;
    }
    {
        let nodes = &kf.nodes;
        let index_of: HashMap<u16, usize> = nodes.iter().enumerate().rev().map(|(i, n)| (n.id, i)).collect();
        let named: HashMap<(Kind, &str), usize> = nodes
            .iter()
            .enumerate()
            .rev()
            .map(|(i, n)| ((n.kind, n.name.as_str()), i))
            .collect();
        let mut todo: Vec<usize> = (0..nodes.len()).filter(|&i| used[i]).collect();
        while let Some(i) = todo.pop() {
            let n = &nodes[i];
            let parent = n.parent.and_then(|p| index_of.get(&p).copied());
            let pair = n.kind.pair().and_then(|k| named.get(&(k, n.name.as_str())).copied());
            for j in [parent, pair].into_iter().flatten() {
                if !used[j] {
                    used[j] = true;
                    todo.push(j);
                }
            }
        }
    }
    let mut used = used.into_iter();
    kf.nodes.retain(|_| used.next().unwrap_or(true));
}

/// The track of something that doesn't move: one key.
fn still<const N: usize>(value: [f32; N]) -> Vec<Key<N>> {
    let (frame, tcb) = (0, [0.0; 5]);
    vec![Key { frame, tcb, value }]
}

/// A node, its id the order it came in when it has no id chunk (as early files have).
fn kf_node(d: &[u8], index: u16, kind: Kind) -> KfNode {
    let mut n = KfNode {
        kind,
        id: index,
        name: String::new(),
        instance: String::new(),
        parent: None,
        pivot: [0.0; 3],
        pos: Vec::new(),
        rot: Vec::new(),
        scl: Vec::new(),
        roll: Vec::new(),
    };
    let object = kind == Kind::Object;
    for (id, b) in chunks(d) {
        match id {
            NODE_ID => n.id = u16_at(b, 0).unwrap_or(index),
            NODE_HDR => {
                let (name, rest) = cstr(b);
                n.name = name;
                n.parent = u16_at(rest, 4).filter(|&p| p != u16::MAX);
            }
            INSTANCE_NAME => n.instance = cstr(b).0,
            PIVOT if object => n.pivot = vec3_at(b, 0).unwrap_or_default(),
            POS_TRACK => n.pos = track(b),
            ROT_TRACK if object => n.rot = track(b),
            SCL_TRACK if object => n.scl = track(b),
            ROLL_TRACK if !object => n.roll = track(b),
            _ => {}
        }
    }
    n
}

/// A rotation key's turn. 3DS turns clockwise about the axis, as lib3ds reads it.
fn axis_angle(k: &Key<4>) -> [f64; 4] {
    let [angle, x, y, z] = k.value.map(f64::from);
    let l = (x * x + y * y + z * z).sqrt();
    if !angle.is_finite() || l.is_nan() || l < 1e-12 {
        return [0.0, 0.0, 0.0, 1.0];
    }
    let half = -0.5 * angle;
    let s = half.sin() / l;
    [x * s, y * s, z * s, half.cos()]
}

/// The rotation at each key: each key turns further from the one before.
fn rotations(keys: &[Key<4>]) -> Vec<[f64; 4]> {
    let mut q = [0.0, 0.0, 0.0, 1.0];
    keys.iter()
        .map(|k| {
            q = quat::unit_unchecked(quat::mul(axis_angle(k), q));
            q
        })
        .collect()
}

fn trs(t: [f64; 3], q: [f64; 4], s: [f64; 3]) -> M4 {
    let r = quat::matrix(q);
    let mut m = IDENTITY;
    for i in 0..3 {
        for j in 0..3 {
            m[i][j] = r[j * 3 + i] * s[j];
        }
        m[i][3] = t[i];
    }
    m
}

/// A node's rest pose, from its first keys: translation, rotation, scale.
fn rest(n: &KfNode) -> ([f64; 3], [f64; 4], [f64; 3]) {
    let t = n.pos.first().map_or([0.0; 3], |k| k.value.map(f64::from));
    let q = rotations(&n.rot[..n.rot.len().min(1)])
        .first()
        .copied()
        .unwrap_or([0.0, 0.0, 0.0, 1.0]);
    let s = n.scl.first().map_or([1.0; 3], |k| k.value.map(f64::from));
    (t, q, s)
}

/// Whether `back` (a mesh's way into its node's space, through its mesh matrix and pivot) undoes where the node
/// stands at one of its keys after the first, under `above`. A file saved on a later frame records where the object
/// stood then: its mesh matrix and vertices are that frame's, and the tracks still place it at every other.
fn stands_at_a_key(n: &KfNode, above: Option<&M4>, back: &M4, scale: f64) -> bool {
    // A track's value on a frame: its key there, or its only key (none: the default).
    fn on<const N: usize>(keys: &[Key<N>], frame: i32, default: [f32; N]) -> Option<[f64; N]> {
        let key = match keys {
            [] => return Some(default.map(f64::from)),
            [only] => only,
            _ => keys.iter().find(|k| k.frame == frame)?,
        };
        Some(key.value.map(f64::from))
    }
    let turns = rotations(&n.rot);
    let frames = n.pos.iter().map(|k| k.frame);
    let frames = frames.chain(n.rot.iter().map(|k| k.frame));
    let frames = frames.chain(n.scl.iter().map(|k| k.frame));
    frames.into_iter().any(|frame| {
        let q = match n.rot.len() {
            0 => Some([0.0, 0.0, 0.0, 1.0]),
            1 => turns.first().copied(),
            _ => n
                .rot
                .iter()
                .position(|k| k.frame == frame)
                .and_then(|at| turns.get(at).copied()),
        };
        let (Some(t), Some(q), Some(s)) = (on(&n.pos, frame, [0.0; 3]), q, on(&n.scl, frame, [1.0; 3])) else {
            return false;
        };
        let local = trs(t, q, s);
        let world = above.map_or(local, |a| xform::mul(a, &local));
        near_identity(&xform::mul(&world, back), scale)
    })
}

fn near_identity(m: &M4, scale: f64) -> bool {
    (0..3).all(|i| (0..3).all(|j| (m[i][j] - IDENTITY[i][j]).abs() < 1e-3) && m[i][3].abs() < 1e-3 * scale.max(1.0))
}

/// `prims` moved by `m`, their normals turned with them. A mirroring `m` would turn the faces inside out, so their
/// corners are put in the other order.
fn placed(mut prims: Vec<Prim>, m: &M4) -> Vec<Prim> {
    #[allow(clippy::float_cmp, reason = "only the exact identity moves nothing")]
    if *m == IDENTITY {
        return prims;
    }
    // The cofactor matrix turns normals (the inverse transpose, up to scale).
    let c: [[f64; 3]; 3] = std::array::from_fn(|i| {
        std::array::from_fn(|j| {
            let (i1, i2, j1, j2) = ((i + 1) % 3, (i + 2) % 3, (j + 1) % 3, (j + 2) % 3);
            m[i1][j1] * m[i2][j2] - m[i1][j2] * m[i2][j1]
        })
    });
    // The cofactors are the inverse transpose times the determinant: a mirror's points them inward.
    let mirror = xform::det3(m) < 0.0;
    let sign = if mirror { -1.0 } else { 1.0 };
    #[allow(clippy::cast_possible_truncation, reason = "back to the f32 the file had")]
    for p in &mut prims {
        if mirror {
            for t in p.indices.chunks_exact_mut(3) {
                t.swap(1, 2);
            }
        }
        for v in &mut p.positions {
            let x = v.map(f64::from);
            *v = std::array::from_fn(|i| (m[i][0] * x[0] + m[i][1] * x[1] + m[i][2] * x[2] + m[i][3]) as f32);
        }
        for n in &mut p.normals {
            let x = n.map(f64::from);
            let r: [f64; 3] = std::array::from_fn(|i| c[i][0] * x[0] + c[i][1] * x[1] + c[i][2] * x[2]);
            let len = r.iter().map(|v| v * v).sum::<f64>().sqrt();
            if len > 0.0 {
                *n = r.map(|v| (sign * v / len) as f32);
            }
        }
    }
    prims
}

/// The rotation that points a camera or spotlight (which look down their -Z, Y up) from `from` at `to`, Z up,
/// turned `roll` degrees about that line.
fn look_at(from: [f64; 3], to: [f64; 3], roll: f64) -> Option<[f64; 4]> {
    let norm = |v: [f64; 3]| {
        let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
        (l > 1e-12).then(|| v.map(|c| c / l))
    };
    let cross = |a: [f64; 3], b: [f64; 3]| {
        [
            a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0],
        ]
    };
    let f = norm(std::array::from_fn(|i| to[i] - from[i]))?;
    let up = if f[2].abs() > 0.999 {
        [0.0, 1.0, 0.0]
    } else {
        [0.0, 0.0, 1.0]
    };
    let r = norm(cross(f, up))?;
    let u = cross(r, f);
    let (s, c) = roll.to_radians().sin_cos();
    let (r, u): ([f64; 3], [f64; 3]) = (
        std::array::from_fn(|i| r[i] * c + u[i] * s),
        std::array::from_fn(|i| u[i] * c - r[i] * s),
    );
    Some(xform::quaternion(&std::array::from_fn(|i| [r[i], u[i], -f[i]])))
}

/// What a camera or spotlight node aims at: its target's node, or the point the editor has when the keyframer has
/// no such node.
#[derive(Clone, Copy)]
enum Aim {
    Node(usize),
    Point([f64; 3]),
}

fn point(m: &M4, p: [f64; 3]) -> [f64; 3] {
    std::array::from_fn(|i| m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3])
}

/// The rotation of a camera or spotlight node at `from`, under `above`, that faces it at `to` (a point of the
/// scene), rolled `roll` degrees.
fn aimed(above: Option<&M4>, from: [f64; 3], to: [f64; 3], roll: f64) -> Option<[f64; 4]> {
    let Some(a) = above else {
        return look_at(from, to, roll);
    };
    let q = look_at(point(a, from), to, roll)?;
    Some(quat::unit_unchecked(quat::mul(
        quat::conjugate(xform::decompose(a).r),
        q,
    )))
}

/// A track as the curve its keys draw, the one its spline channel draws.
struct Curve<'a, const N: usize> {
    keys: Vec<&'a Key<N>>,
    tangents: Vec<([f32; N], [f32; N])>,
}

impl<'a, const N: usize> Curve<'a, N> {
    fn new(keys: &'a [Key<N>]) -> Self {
        let keys: Vec<&Key<N>> = rising(keys.iter().map(|k| (k.frame, k)));
        let tangents = tcb_tangents(&keys);
        Self { keys, tangents }
    }

    /// Its first and last frames, when it has more than one key.
    fn span(&self) -> Option<(i32, i32)> {
        let (first, last) = (self.keys.first()?, self.keys.last()?);
        (self.keys.len() > 1).then_some((first.frame, last.frame))
    }

    /// Its value on a frame: held before the first key and after the last.
    fn at(&self, frame: f64) -> Option<[f64; N]> {
        let next = self.keys.partition_point(|k| f64::from(k.frame) <= frame);
        let Some(before) = next.checked_sub(1) else {
            return self.keys.first().map(|k| k.value.map(f64::from));
        };
        let (a, leave) = (self.keys[before], self.tangents[before].1);
        let (Some(b), Some((arrive, _))) = (self.keys.get(next), self.tangents.get(next)) else {
            return Some(a.value.map(f64::from));
        };
        let u = (frame - f64::from(a.frame)) / (f64::from(b.frame) - f64::from(a.frame));
        let (u2, u3) = (u * u, u * u * u);
        Some(std::array::from_fn(|k| {
            (2.0 * u3 - 3.0 * u2 + 1.0) * f64::from(a.value[k])
                + (u3 - 2.0 * u2 + u) * f64::from(leave[k])
                + (3.0 * u2 - 2.0 * u3) * f64::from(b.value[k])
                + (u3 - u2) * f64::from(arrive[k])
        }))
    }
}

fn camera_json(c: &Camera, name: &str, extras: bool) -> Value {
    // 3D Studio's lens is on 35 mm film, 36 mm wide; at its 4:3 frame that is 27 mm high.
    let lens = if c.lens.is_finite() && c.lens > 0.0 {
        f64::from(c.lens)
    } else {
        43.456
    };
    let yfov = 2.0 * (13.5 / lens).atan();
    let mut p = json!({ "yfov": yfov, "aspectRatio": 4.0 / 3.0, "znear": 0.01 });
    if let Some([near, far]) = c.range {
        if near.is_finite() && near > 0.0 {
            p["znear"] = clean(near);
        }
        if far.is_finite() && far > near.max(0.0) {
            p["zfar"] = clean(far);
        }
    }
    let mut out = json!({ "name": name, "type": "perspective", "perspective": p });
    if extras {
        out["extras"] = json!({ "lens": clean(c.lens), "roll": clean(c.roll), "target": cleans(&c.target) });
    }
    out
}

fn light_json(l: &Light, name: &str, extras: bool) -> Value {
    let rgb = l.color.as_ref().map_or([1.0; 3], |(c, _)| *c);
    let mut out = json!({ "name": name, "type": "point", "color": rgb, "intensity": l.multiplier.map_or(1.0, |m| f64::from(m.max(0.0))) });
    if l.attenuate
        && let Some(r) = l.outer.filter(|r| r.is_finite() && *r > 0.0)
    {
        out["range"] = clean(r);
    }
    if let Some(s) = &l.spot {
        let half = std::f64::consts::FRAC_PI_2;
        // A NaN angle takes the widest cone, so the clamps below always have ordered bounds.
        let cone = |deg: f32, wide: f64| {
            Some(f64::from(deg).to_radians() / 2.0)
                .filter(|a| !a.is_nan())
                .unwrap_or(wide)
        };
        let outer = cone(s.falloff, half).clamp(1e-4, half);
        let inner = cone(s.hotspot, outer).clamp(0.0, outer * 0.999);
        out["type"] = json!("spot");
        out["spot"] = json!({ "innerConeAngle": inner, "outerConeAngle": outer });
    }
    if extras {
        let mut e = Map::new();
        if let Some((_, raw)) = &l.color {
            e.insert("color".into(), raw.clone());
        }
        if l.off {
            e.insert("off".into(), json!(true));
        }
        if l.attenuate {
            e.insert("attenuate".into(), json!(true));
        }
        for (k, v) in [("innerRange", l.inner), ("outerRange", l.outer)] {
            if let Some(v) = v {
                e.insert(k.into(), clean(v));
            }
        }
        if let Some(s) = &l.spot {
            e.insert(
                "spot".into(),
                json!({ "target": cleans(&s.target), "hotspot": clean(s.hotspot), "falloff": clean(s.falloff) }),
            );
        }
        if !e.is_empty() {
            out["extras"] = Value::Object(e);
        }
    }
    out
}

/// A Kochanek–Bartels track's tangents at each key as lib3ds works them out (spacing and continuity adjusted): the
/// one arriving and the one leaving, per segment.
fn tcb_tangents<const N: usize>(keys: &[&Key<N>]) -> Vec<([f32; N], [f32; N])> {
    #[allow(clippy::cast_precision_loss, reason = "frame numbers are small")]
    let frame = |k: &Key<N>| k.frame as f32;
    (0..keys.len())
        .map(|i| {
            let c = keys[i];
            let prev = i.checked_sub(1).map(|p| keys[p]);
            let next = keys.get(i + 1).copied();
            let [tens, cont, bias, ..] = c.tcb;
            let (mut fp, mut fnx) = (1.0, 1.0);
            if let (Some(p), Some(n)) = (prev, next) {
                let dt = 0.5 * (frame(n) - frame(p));
                fp = (frame(c) - frame(p)) / dt;
                fnx = (frame(n) - frame(c)) / dt;
                let a = cont.abs();
                fp = fp + a - a * fp;
                fnx = fnx + a - a * fnx;
            }
            let (cm, tm, bm) = (1.0 - cont, 0.5 * (1.0 - tens), 1.0 - bias);
            let (cp, bp) = (2.0 - cm, 2.0 - bm);
            let (ksm, ksp, kdm, kdp) = (
                tm * cm * bp * fp,
                tm * cp * bm * fp,
                tm * cp * bp * fnx,
                tm * cm * bm * fnx,
            );
            let delta = |a: &Key<N>, b: &Key<N>| -> [f32; N] { std::array::from_fn(|k| b.value[k] - a.value[k]) };
            let dm = prev.map(|p| delta(p, c));
            let dp = next.map(|n| delta(c, n));
            let (dm, dp) = match (dm, dp) {
                (Some(m), Some(p)) => (m, p),
                (Some(m), None) => (m, m),
                (None, Some(p)) => (p, p),
                (None, None) => ([0.0; N], [0.0; N]),
            };
            (
                std::array::from_fn(|k| ksm * dm[k] + ksp * dp[k]),
                std::array::from_fn(|k| kdm * dm[k] + kdp * dp[k]),
            )
        })
        .collect()
}

/// The keys of a track whose frames go up, in order (glTF needs times that only increase).
fn rising<T>(frames: impl Iterator<Item = (i32, T)>) -> Vec<T> {
    let mut last = None;
    frames
        .filter(|&(f, _)| {
            let up = last.is_none_or(|l| f > l);
            if up {
                last = Some(f);
            }
            up
        })
        .map(|(_, t)| t)
        .collect()
}

#[allow(clippy::cast_precision_loss, reason = "frame numbers are small")]
fn seconds(frame: i32) -> f32 {
    frame as f32 / FRAMES_PER_SECOND
}

/// A vector track as a cubic spline channel: each key's arriving tangent, value and leaving tangent, per second.
fn spline(keys: &[Key<3>]) -> (Vec<f32>, Vec<f32>) {
    let keys: Vec<&Key<3>> = rising(keys.iter().map(|k| (k.frame, k)));
    let tangents = tcb_tangents(&keys);
    let times: Vec<f32> = keys.iter().map(|k| seconds(k.frame)).collect();
    let mut out = Vec::with_capacity(keys.len() * 9);
    for (i, (k, (arrive, leave))) in keys.iter().zip(&tangents).enumerate() {
        let before = i.checked_sub(1).map_or(0.0, |p| times[i] - times[p]);
        let after = times.get(i + 1).map_or(0.0, |n| n - times[i]);
        out.extend(arrive.map(|v| if before > 0.0 { v / before } else { 0.0 }));
        out.extend(k.value);
        out.extend(leave.map(|v| if after > 0.0 { v / after } else { 0.0 }));
    }
    (times, out)
}

/// Each object's mesh, by the placement its vertices are moved by.
struct Meshes {
    prims: Vec<Option<Vec<Prim>>>,
    /// Uses left of each object's primitives, so the last takes them rather than a copy.
    left: Vec<usize>,
    of: HashMap<(usize, [u64; 16]), Option<usize>>,
    list: Vec<Value>,
}

impl Meshes {
    fn get(&mut self, b: &mut Builder, obj: usize, m: &M4) -> Option<usize> {
        let key = (obj, std::array::from_fn(|k| m[k / 4][k % 4].to_bits()));
        if let Some(&i) = self.of.get(&key) {
            return i;
        }
        self.left[obj] = self.left[obj].saturating_sub(1);
        let prims = if self.left[obj] == 0 {
            self.prims[obj].take()
        } else {
            self.prims[obj].clone()
        }?;
        let mesh = b.mesh(placed(prims, m), usize::MAX).map(|mesh| {
            self.list.push(mesh);
            self.list.len() - 1
        });
        self.of.insert(key, mesh);
        mesh
    }
}

#[allow(clippy::too_many_lines, reason = "one pass over the file's parts, in order")]
pub(crate) fn load(input: super::Input<'_>, assets: &dyn Assets, keep: Keep) -> Result<Document> {
    let data = input.read()?;
    let main = chunks(&data)
        .next()
        .filter(|&(id, _)| id == MAIN || id == PROJECT)
        .map(|(_, b)| b);
    let Some(main) = main else {
        bail!(UnknownFormat, "not a 3DS file")
    };
    // The main chunk's length is the file's: a file shorter than it is cut short, and what's whole is kept.
    let cut = u32_at(&data, 2).is_some_and(|n| usize_of(u64::from(n)) > data.len());
    let mut source = Map::new();
    if cut {
        source.insert("truncated".into(), json!(true));
    }
    let (mut editor, mut kf) = (&[][..], Keyframer::default());
    for (id, b) in chunks(main) {
        match id {
            VERSION => {
                if let Some(v) = u32_at(b, 0) {
                    source.insert("version".into(), json!(v));
                }
            }
            EDITOR if editor.is_empty() => editor = b,
            KEYFRAMER => kf = keyframer(b),
            _ => {}
        }
    }
    prune(&mut kf);

    let mut materials: Vec<Material> = Vec::new();
    let mut raws: Vec<Map<String, Value>> = Vec::new();
    let mut looks: Vec<Look> = Vec::new();
    // Whether each material is shaded flat.
    let mut flat: Vec<bool> = Vec::new();
    let mut by_name: HashMap<String, usize> = HashMap::new();
    let dir = input.dir();
    let mut images = Images::new(!keep.image_bytes, dir);
    // Texture names whatever their case, as 3DS's DOS-era names are: `WOOD.JPG` and `wood.jpg` are one image even
    // where the two find different paths.
    let mut image_of: HashMap<String, Option<usize>> = HashMap::new();
    // Whether each bump map file is a normal map.
    let mut normal_of: HashMap<String, bool> = HashMap::new();
    let mut objects = Vec::new();
    for (id, b) in chunks(editor) {
        match id {
            MESH_VERSION => {
                if let Some(v) = u32_at(b, 0) {
                    source.insert("meshVersion".into(), json!(v));
                }
            }
            MASTER_SCALE => {
                if let Some(s) = f32_at(b, 0) {
                    source.insert("masterScale".into(), clean(s));
                }
            }
            AMBIENT_LIGHT => {
                if let Some(c) = color_raw(b) {
                    source.insert("ambient".into(), c);
                }
            }
            MATERIAL => {
                let m = material(b);
                let mut image_for = |f: &str| {
                    if !(keep.materials && keep.textures) {
                        return None;
                    }
                    *image_of
                        .entry(f.to_lowercase())
                        .or_insert_with(|| images.find(assets, &[f], &[dir]))
                };
                let image = m.texture.as_deref().and_then(&mut image_for);
                let maps = m.raw.get("maps").and_then(Value::as_object);
                let map = |k: &str| maps.and_then(|ms| ms.get(k)).and_then(Value::as_object);
                let mut slot = |k: &str| {
                    let map = map(k)?;
                    let image = image_for(map.get("file")?.as_str()?)?;
                    Some(map_tex(map, image))
                };
                let (spec_tex, emissive) = (slot("specular"), slot("selfIllumination"));
                let bump = map("bump").filter(|b| {
                    let Some(f) = b
                        .get("file")
                        .and_then(Value::as_str)
                        .filter(|_| keep.materials && keep.textures)
                    else {
                        return false;
                    };
                    *normal_of
                        .entry(f.to_lowercase())
                        .or_insert_with(|| bump_is_normal_map(assets, dir, f))
                });
                // The bump amount as the normal map's scale.
                #[allow(clippy::cast_possible_truncation, reason = "it was an f32")]
                let normal = bump.and_then(|_| slot("bump")).map(|mut t| {
                    let amount = bump.and_then(|b| b.get("percent")).and_then(Value::as_f64);
                    t.scale = amount.map_or(1.0, |p| (p / 100.0) as f32);
                    t
                });
                let tiling = map("texture").and_then(|t| t.get("tiling")).and_then(Value::as_u64);
                // An opacity map that is the color map: its alpha.
                let opacity = map("opacity").and_then(|o| o.get("file")).and_then(Value::as_str);
                let cut = opacity
                    .zip(m.texture.as_deref())
                    .is_some_and(|(o, t)| o.eq_ignore_ascii_case(t));
                flat.push(m.raw.get("shading").and_then(Value::as_u64) == Some(1));
                // A texture shows as painted, not tinted by the color under it.
                let rgb = if image.is_some() { [1.0; 3] } else { m.color };
                // The classic material. Its "shininess" percentage is the glossiness of 3ds Max's standard
                // material, whose Phong shader takes an exponent of 2^(10 g) for a glossiness g of 0 to 1 (the
                // SDK's standard shaders); its "shininess strength" scales the specular color, the highlight's.
                let mut phong = Phong::new(Rgb::Linear(rgb));
                phong.opacity = m.alpha;
                phong.exponent = m.glossiness.map(|g| (10.0 * g).exp2());
                if m.specular.is_some() || m.shine_strength.is_some() {
                    phong.specular = Some(Rgb::Srgb(m.specular.unwrap_or([1.0; 3])));
                    phong.strength = m.shine_strength.unwrap_or(1.0);
                }
                let look = phong.pbr();
                // No highlight has no use for a texture coloring it.
                let spec_tex = spec_tex.filter(|_| look.specular != Some(Highlight::NONE));
                let highlight = look.specular.or(spec_tex.as_ref().map(|_| Highlight {
                    factor: 1.0,
                    color: [1.0; 3],
                }));
                looks.push(Look {
                    color: image.and(map("texture")).map(|t| map_tex(t, 0)),
                    specular: highlight.map(|h| Specular {
                        factor: Factor::of(h.factor),
                        color: h.color,
                        color_tex: spec_tex,
                    }),
                    emissive,
                    normal: normal.clone(),
                    alpha_source: cut || tiling.is_some_and(|t| t & TILE_ALPHA != 0),
                });
                let plain = Material::plain(&m.name, look.base_color);
                by_name.insert(m.name.clone(), materials.len());
                materials.push(Material {
                    color_image: image,
                    normal_image: normal.map(|t| t.image),
                    emissive: m.color.map(|c| c * m.self_illum),
                    roughness: look.roughness,
                    double_sided: m.two_sided,
                    ..plain
                });
                raws.push(m.raw);
            }
            OBJECT => objects.push(object(b)),
            _ => {}
        }
    }

    // Each mesh object's primitives, one per material.
    let mut triangles = 0usize;
    let mut prims_of = Vec::with_capacity(objects.len());
    // Faces naming a vertex that isn't there, which are left out.
    let mut dropped = 0;
    for o in &objects {
        let Body::Mesh(ts) = &o.body else {
            prims_of.push(None);
            continue;
        };
        let mut prims: HashMap<usize, Prim> = HashMap::new();
        for t in ts {
            triangles += t.faces.len();
            ensure!(
                triangles <= input.limit,
                LimitExceeded,
                "more than {} triangles",
                input.limit
            );
            let mut face_mat = vec![None; t.faces.len()];
            for (name, faces) in &t.materials {
                let m = by_name.get(name).copied();
                for &f in faces {
                    if let Some(slot) = face_mat.get_mut(f as usize) {
                        *slot = m;
                    }
                }
            }
            let past = |f: &&[u16; 3]| f.iter().any(|&i| usize::from(i) >= t.vertices.len());
            dropped += t.faces.iter().filter(past).count();
            add_faces(t, &face_mat, &flat, &mut prims, &mut materials);
        }
        let mut prims: Vec<Prim> = prims.into_values().filter(|p| !p.indices.is_empty()).collect();
        prims.sort_by_key(|p| p.material);
        prims_of.push(Some(prims).filter(|p| !p.is_empty()));
    }
    // A scene of cameras or lights alone is one still.
    if triangles == 0
        && !objects
            .iter()
            .any(|o| matches!(o.body, Body::Camera(_) | Body::Light(_)))
    {
        if cut {
            return Err(crate::Error::cut_short(
                "3DS file is cut short before its first whole mesh",
            ));
        }
        bail!(Empty, "this 3DS file has no meshes, cameras or lights");
    }
    let mut textured = vec![false; materials.len()];
    for p in prims_of.iter().flatten().flatten().filter(|p| !p.uvs.is_empty()) {
        textured[p.material] = true;
    }
    if keep.materials && keep.textures {
        super::guess_texture(&mut materials, &mut images, &textured, input.path, assets);
    }

    let mut b = Builder::new(keep.crease_angle());
    b.dropped = dropped;
    let mut nodes: Vec<Value> = Vec::new();
    let (mut cameras, mut lights) = (Vec::new(), Vec::new());
    let mut roots = Vec::new();
    let mut meshes = Meshes {
        left: vec![0; objects.len()],
        prims: prims_of,
        of: HashMap::new(),
        list: Vec::new(),
    };
    let object_of: HashMap<&str, usize> = objects
        .iter()
        .enumerate()
        .rev()
        .map(|(i, o)| (o.name.as_str(), i))
        .collect();
    // A camera, light or target node without a track is where the editor has it.
    for n in &mut kf.nodes {
        let at = match (n.kind, object_of.get(n.name.as_str()).map(|&o| &objects[o].body)) {
            (Kind::Camera, Some(Body::Camera(c))) => {
                if n.roll.is_empty() {
                    n.roll = still([c.roll]);
                }
                Some(c.position)
            }
            (Kind::CameraTarget, Some(Body::Camera(c))) => Some(c.target),
            (Kind::Light | Kind::Spot, Some(Body::Light(l))) => Some(l.position),
            (Kind::SpotTarget, Some(Body::Light(l))) => l.spot.as_ref().map(|s| s.target),
            _ => None,
        };
        if let Some(at) = at.filter(|_| n.pos.is_empty()) {
            n.pos = still(at);
        }
    }
    // The object each node places: a camera's node its camera, a light's its light, a target's none.
    let placed_by_kf: Vec<Option<usize>> = kf
        .nodes
        .iter()
        .map(|n| {
            let o = object_of.get(n.name.as_str()).copied()?;
            let fits = match n.kind {
                Kind::Object => true,
                Kind::Camera => matches!(objects[o].body, Body::Camera(_)),
                Kind::Light | Kind::Spot => matches!(objects[o].body, Body::Light(_)),
                Kind::CameraTarget | Kind::SpotTarget => false,
            };
            fits.then_some(o)
        })
        .collect();
    for &o in placed_by_kf.iter().flatten() {
        meshes.left[o] += 1;
    }
    let object_extras = |o: &Object, e: &mut Map<String, Value>| {
        if o.hidden {
            e.insert("hidden".into(), json!(true));
        }
        if let Body::Mesh(ts) = &o.body
            && let Some(m) = ts.iter().find_map(|t| t.matrix)
        {
            e.insert("meshMatrix".into(), cleans(&m));
        }
    };

    // The objects the keyframer doesn't place, where the editor has them.
    for (i, o) in objects.iter().enumerate() {
        if placed_by_kf.contains(&Some(i)) {
            continue;
        }
        // An object with no name has no name key.
        let mut node = if o.name.is_empty() {
            json!({})
        } else {
            json!({ "name": o.name })
        };
        match &o.body {
            Body::Mesh(_) => {
                meshes.left[i] += 1;
                if let Some(m) = meshes.get(&mut b, i, &IDENTITY) {
                    node["mesh"] = json!(m);
                }
            }
            // A camera or light that isn't kept leaves its node where it stood, as pruning one does: the scene
            // is the file's, whatever is kept of it.
            Body::Camera(c) => {
                node["translation"] = cleans(&c.position);
                if let Some(q) = look_at(c.position.map(f64::from), c.target.map(f64::from), f64::from(c.roll)) {
                    node["rotation"] = json!(q);
                }
                if keep.cameras {
                    cameras.push(camera_json(c, &o.name, keep.extras));
                    node["camera"] = json!(cameras.len() - 1);
                }
            }
            Body::Light(l) => {
                node["translation"] = cleans(&l.position);
                let aim = |s: &Spot| look_at(l.position.map(f64::from), s.target.map(f64::from), 0.0);
                if let Some(q) = l.spot.as_ref().and_then(aim) {
                    node["rotation"] = json!(q);
                }
                if keep.lights {
                    lights.push(light_json(l, &o.name, keep.extras));
                    node["extensions"] = json!({ "KHR_lights_punctual": { "light": lights.len() - 1 } });
                }
            }
            Body::Empty => {}
        }
        if keep.extras {
            let mut e = Map::new();
            object_extras(o, &mut e);
            if !e.is_empty() {
                node["extras"] = Value::Object(e);
            }
        }
        roots.push(nodes.len());
        nodes.push(node);
    }

    // The keyframer's hierarchy: its nodes' rest poses, and where each is in the world at rest.
    let first = nodes.len();
    let index_of: HashMap<u16, usize> = kf.nodes.iter().enumerate().rev().map(|(i, n)| (n.id, i)).collect();
    let parent_of: Vec<Option<usize>> = kf
        .nodes
        .iter()
        .enumerate()
        .map(|(i, n)| n.parent.and_then(|p| index_of.get(&p).copied()).filter(|&p| p != i))
        .collect();
    let mut rests: Vec<_> = kf.nodes.iter().map(rest).collect();
    let mut local: Vec<M4> = rests.iter().map(|&(t, q, s)| trs(t, q, s)).collect();
    let mut world: Vec<Option<M4>> = vec![None; kf.nodes.len()];
    let mut parent_ok = vec![true; kf.nodes.len()];
    for i in 0..kf.nodes.len() {
        // Up to the first node placed already, or a root; a loop makes the node a root.
        let mut chain = vec![i];
        while let Some(p) = parent_of[*chain.last().unwrap_or(&i)] {
            if world[p].is_some() {
                break;
            }
            if chain.contains(&p) {
                parent_ok[*chain.last().unwrap_or(&i)] = false;
                break;
            }
            chain.push(p);
        }
        for &n in chain.iter().rev() {
            let above = parent_of[n].filter(|_| parent_ok[n]).and_then(|p| world[p]);
            world[n] = Some(above.map_or(local[n], |w| xform::mul(&w, &local[n])));
        }
    }
    let up = |i: usize| parent_of[i].filter(|_| parent_ok[i]);
    // What each camera and spotlight node aims at.
    let targets: HashMap<(Kind, &str), usize> = kf
        .nodes
        .iter()
        .enumerate()
        .rev()
        .filter(|(_, n)| matches!(n.kind, Kind::CameraTarget | Kind::SpotTarget))
        .map(|(i, n)| ((n.kind, n.name.as_str()), i))
        .collect();
    let aims: Vec<Option<Aim>> = kf
        .nodes
        .iter()
        .map(|n| {
            if let Some(&t) = targets.get(&(n.kind.target()?, n.name.as_str())) {
                return Some(Aim::Node(t));
            }
            match &objects[*object_of.get(n.name.as_str())?].body {
                Body::Camera(c) if n.kind == Kind::Camera => Some(Aim::Point(c.target.map(f64::from))),
                Body::Light(l) if n.kind == Kind::Spot => l.spot.as_ref().map(|s| Aim::Point(s.target.map(f64::from))),
                _ => None,
            }
        })
        .collect();
    let roll_of = |n: &KfNode| n.roll.first().map_or(0.0, |k| f64::from(k.value[0]));
    if aims.iter().any(Option::is_some) {
        // Each aiming node turned to face its target, from the roots down: what is under it moves with it.
        let mut below = vec![Vec::new(); kf.nodes.len()];
        let mut todo = Vec::new();
        for i in 0..kf.nodes.len() {
            match up(i) {
                Some(p) => below[p].push(i),
                None => todo.push(i),
            }
        }
        while let Some(i) = todo.pop() {
            let above = up(i).and_then(|p| world[p]);
            let to = aims[i].and_then(|aim| match aim {
                Aim::Node(t) => world[t].map(|w| [w[0][3], w[1][3], w[2][3]]),
                Aim::Point(p) => Some(p),
            });
            if let Some(q) = to.and_then(|to| aimed(above.as_ref(), rests[i].0, to, roll_of(&kf.nodes[i]))) {
                rests[i].1 = q;
                local[i] = trs(rests[i].0, q, rests[i].2);
            }
            world[i] = Some(above.map_or(local[i], |w| xform::mul(&w, &local[i])));
            todo.extend(&below[i]);
        }
    }
    let mut placed_once = vec![false; objects.len()];
    for (i, n) in kf.nodes.iter().enumerate() {
        let obj = placed_by_kf[i];
        let name = match n.kind {
            // As 3ds Max names a target.
            Kind::CameraTarget | Kind::SpotTarget => Cow::Owned(format!("{}.Target", n.name)),
            _ if n.instance.is_empty() => Cow::Borrowed(&n.name),
            _ => Cow::Borrowed(&n.instance),
        };
        // A node with no name has no name key.
        let mut node = if name.is_empty() {
            json!({})
        } else {
            json!({ "name": name.as_str() })
        };
        let (t, q, s) = rests[i];
        if t.iter().any(|&c| c != 0.0) {
            node["translation"] = cleans(&n.pos[0].value);
        }
        if (q[3] - 1.0).abs() > 1e-12 {
            node["rotation"] = json!(q);
        }
        #[allow(clippy::float_cmp, reason = "exactly one is no scale")]
        if s.iter().any(|&c| c != 1.0) {
            node["scale"] = cleans(&n.scl[0].value);
        }
        let w = world[i].unwrap_or(IDENTITY);
        if let Some(o) = obj
            && matches!(objects[o].body, Body::Mesh(_))
        {
            // Back through the mesh matrix and the pivot, as lib3ds does, unless the object's first node isn't then
            // where the editor has it, at rest or at any of its keys: then its rest pose decides.
            let m = match &objects[o].body {
                Body::Mesh(ts) => ts.iter().find_map(|t| t.matrix).map_or(IDENTITY, |m| mesh_matrix(&m)),
                _ => IDENTITY,
            };
            let pivot = xform::translate(n.pivot.map(|c| -f64::from(c)));
            let lib = (xform::det3(&m).abs() > 1e-12).then(|| xform::mul(&pivot, &xform::inverse(&m)));
            let by_rest = xform::inverse(&w);
            let size = m[0][3].abs().max(m[1][3].abs()).max(m[2][3].abs());
            let above = up(i).and_then(|p| world[p]);
            let into = match lib {
                Some(l) if placed_once[o] || near_identity(&xform::mul(&w, &l), size) => l,
                Some(l) if stands_at_a_key(n, above.as_ref(), &l, size) => l,
                _ => by_rest,
            };
            placed_once[o] = true;
            if let Some(mesh) = meshes.get(&mut b, o, &into) {
                node["mesh"] = json!(mesh);
            }
        }
        if let Some(o) = obj.map(|o| &objects[o]) {
            match (n.kind, &o.body) {
                (Kind::Camera, Body::Camera(c)) if keep.cameras => {
                    cameras.push(camera_json(c, &o.name, keep.extras));
                    node["camera"] = json!(cameras.len() - 1);
                }
                (Kind::Light | Kind::Spot, Body::Light(l)) if keep.lights => {
                    lights.push(light_json(l, &o.name, keep.extras));
                    node["extensions"] = json!({ "KHR_lights_punctual": { "light": lights.len() - 1 } });
                }
                _ => {}
            }
        }
        if keep.extras {
            let mut e = Map::new();
            e.insert("nodeId".into(), json!(n.id));
            if !n.instance.is_empty() {
                e.insert("object".into(), json!(n.name));
            }
            if n.pivot.iter().any(|&c| c != 0.0) {
                e.insert("pivot".into(), cleans(&n.pivot));
            }
            if let Some(o) = obj {
                object_extras(&objects[o], &mut e);
            }
            node["extras"] = Value::Object(e);
        }
        nodes.push(node);
    }
    for i in 0..kf.nodes.len() {
        match up(i) {
            Some(p) => {
                let children = nodes[first + p]
                    .as_object_mut()
                    .map(|o| o.entry("children").or_insert_with(|| json!([])));
                if let Some(Value::Array(c)) = children {
                    c.push(json!(first + i));
                }
            }
            None => roots.push(first + i),
        }
    }

    if keep.animations {
        // The keyframer's tracks as one animation, with no name (the file gives it none), starting at time 0 even
        // when its first key is at a negative frame or a late one.
        let mut tracks: Vec<Track> = Vec::new();
        for (i, n) in kf.nodes.iter().enumerate() {
            let node = first + i;
            let mut add = |path: keys::Path, (times, values): (Vec<f32>, Vec<f32>), interp: Interp| {
                tracks.push(Track {
                    interp,
                    ..Track::linear(node, path, times, values)
                });
            };
            if n.pos.len() > 1 {
                add(keys::Path::Translation, spline(&n.pos), Interp::Cubic);
            }
            if n.rot.len() > 1 {
                let turns = rotations(&n.rot);
                let keys: Vec<(f32, [f64; 4])> =
                    rising(n.rot.iter().zip(turns).map(|(k, q)| (k.frame, (seconds(k.frame), q))));
                // Each quaternion on the same side as the last, so slerp takes the short way.
                let mut last = [0.0, 0.0, 0.0, 1.0];
                let mut values = Vec::with_capacity(keys.len() * 4);
                for &(_, mut q) in &keys {
                    if (0..4).map(|k| q[k] * last[k]).sum::<f64>() < 0.0 {
                        q = q.map(|c| -c);
                    }
                    last = q;
                    #[allow(clippy::cast_possible_truncation, reason = "accessor floats")]
                    values.extend(q.map(|c| c as f32));
                }
                let times = keys.iter().map(|&(t, _)| t).collect();
                add(keys::Path::Rotation, (times, values), Interp::Linear);
            }
            if let Some(aim) = aims[i] {
                // A camera or spotlight turns as it, its target or its roll moves: its rotation on each frame of
                // those tracks, the nodes above the two standing as they do at rest.
                let (own, roll) = (Curve::new(&n.pos), Curve::new(&n.roll));
                let to = match aim {
                    Aim::Node(t) => Some((Curve::new(&kf.nodes[t].pos), up(t).and_then(|p| world[p]))),
                    Aim::Point(_) => None,
                };
                let spans = [own.span(), roll.span(), to.as_ref().and_then(|(c, _)| c.span())];
                let span = spans.into_iter().flatten().reduce(|a, b| (a.0.min(b.0), a.1.max(b.1)));
                if let Some((lo, hi)) = span {
                    let above = up(i).and_then(|p| world[p]);
                    // Every frame, or of a very long span every few.
                    let step = usize_of(u64::from(hi.abs_diff(lo)).div_ceil(4096).max(1));
                    let mut frames: Vec<i32> = (lo..hi).step_by(step).collect();
                    frames.push(hi);
                    let mut last = rests[i].1;
                    let mut values = Vec::with_capacity(frames.len() * 4);
                    for &frame in &frames {
                        let f = f64::from(frame);
                        let target = match (&to, aim) {
                            (Some((curve, over)), _) => curve.at(f).map(|p| over.map_or(p, |m| point(&m, p))),
                            (None, Aim::Point(p)) => Some(p),
                            (None, Aim::Node(_)) => None,
                        };
                        let turn = own
                            .at(f)
                            .zip(target)
                            .and_then(|(from, to)| aimed(above.as_ref(), from, to, roll.at(f).map_or(0.0, |r| r[0])));
                        let mut q = turn.unwrap_or(last);
                        if (0..4).map(|k| q[k] * last[k]).sum::<f64>() < 0.0 {
                            q = q.map(|c| -c);
                        }
                        last = q;
                        #[allow(clippy::cast_possible_truncation, reason = "accessor floats")]
                        values.extend(q.map(|c| c as f32));
                    }
                    let times = frames.iter().map(|&f| seconds(f)).collect();
                    add(keys::Path::Rotation, (times, values), Interp::Linear);
                }
            }
            if n.scl.len() > 1 {
                add(keys::Path::Scale, spline(&n.scl), Interp::Cubic);
            }
        }
        let mut writer = keys::Writer::new(keep.extras);
        writer.animation(&mut b, None, None, tracks);
        writer.finish(&mut b);
    }
    let animated = !kf.nodes.is_empty() || kf.revision.is_some();
    if animated {
        let mut k = Map::new();
        if !kf.name.is_empty() {
            k.insert("name".into(), json!(kf.name));
        }
        if let Some(r) = kf.revision {
            k.insert("revision".into(), json!(r));
        }
        if let Some(l) = kf.length {
            k.insert("length".into(), json!(l));
        }
        if let Some(s) = kf.segment {
            k.insert("segment".into(), json!(s));
        }
        source.insert("keyframer".into(), Value::Object(k));
    }
    // The master scale multiplies every coordinate (see the module's notes); it names no unit.
    let master = source
        .get("masterScale")
        .and_then(Value::as_f64)
        .filter(|s| s.is_finite() && *s > 0.0)
        .unwrap_or(1.0);
    let info = SourceInfo {
        format: Some("3DS".into()),
        version: source.get("version").map(ToString::to_string),
        up_axis: Fact::Declared(Axis::PosZ),
        handedness: Fact::Declared(Handedness::Right),
        frame_rate: if animated {
            Fact::Assumed(f64::from(FRAMES_PER_SECOND))
        } else {
            Fact::Unknown
        },
        ..SourceInfo::default()
    };
    info.write(&mut source);
    // What a camera sees and a light reaches are lengths of the scene, scaled as it is drawn.
    for c in &mut cameras {
        for key in ["znear", "zfar"] {
            if let Some(v) = c.pointer_mut(&format!("/perspective/{key}"))
                && let Some(x) = v.as_f64()
            {
                *v = json!(x * master);
            }
        }
    }
    for l in &mut lights {
        if let Some(v) = l.get_mut("range")
            && let Some(x) = v.as_f64()
        {
            *v = json!(x * master);
        }
    }

    let mut json = Map::new();
    json.insert("asset".into(), json!({ "extras": { "source": source } }));
    json.insert("scene".into(), json!(0));
    json.insert("scenes".into(), json!([{ "nodes": roots }]));
    json.insert("nodes".into(), Value::Array(nodes));
    json.insert("meshes".into(), Value::Array(meshes.list));
    if !cameras.is_empty() {
        json.insert("cameras".into(), Value::Array(cameras));
    }
    if !lights.is_empty() {
        json.insert("extensionsUsed".into(), json!(["KHR_lights_punctual"]));
        json.insert(
            "extensions".into(),
            json!({ "KHR_lights_punctual": { "lights": lights } }),
        );
    }
    let fulls = materials
        .iter()
        .enumerate()
        .map(|(i, m)| looks.get(i).map_or_else(|| Full::from(m), |l| l.full(m)));
    b.materials(fulls, images.list, &mut json);
    if keep.extras
        && let Some(Value::Array(list)) = json.get_mut("materials")
    {
        for (mat, raw) in list.iter_mut().zip(raws) {
            if !raw.is_empty() {
                mat["extras"] = json!({ "3ds": raw });
            }
        }
    }
    // `read` counts the triangles drawn, from the document.
    let mut doc = b.finish(json, Map::new());
    // Z-up to Y-up (a quarter turn about X), and the file's master scale.
    frame::root_by_factor(&mut doc, Frame::z_up().scaled(master));
    Ok(doc)
}

/// A trimesh's faces, into the prims of their materials. A corner's normal averages the faces around its vertex that
/// share a smoothing bit with its own face, each weighed by its angle there (so the triangulation doesn't matter); a
/// face in no group, or in a material shaded flat, is flat. Vertices at one position are one corner to smoothing.
/// Corners share a vertex when material, vertex and normal agree. Missing texture coordinates are zero.
fn add_faces(
    t: &Trimesh,
    face_mat: &[Option<usize>],
    flat: &[bool],
    prims: &mut HashMap<usize, Prim>,
    materials: &mut Vec<Material>,
) {
    let pos = &t.vertices;
    let has_uvs = !t.uvs.is_empty();
    let n = pos.len();
    let whole = |f: &[u16; 3]| f.iter().all(|&i| usize::from(i) < n);
    let group = |f: usize| {
        let flat = face_mat
            .get(f)
            .copied()
            .flatten()
            .is_some_and(|m| flat.get(m) == Some(&true));
        if flat {
            0
        } else {
            t.smoothing.get(f).copied().unwrap_or(0)
        }
    };
    // A mirroring mesh matrix leaves the faces inside out in the world space the vertices are in.
    let faces: Cow<'_, [[u16; 3]]> = if t.matrix.is_some_and(|m| xform::det3(&mesh_matrix(&m)) < 0.0) {
        t.faces.iter().map(|&[a, b, c]| [a, c, b]).collect()
    } else {
        Cow::Borrowed(&t.faces)
    };

    // Each face's unit normal, and its angle at each corner when some face is smoothed (the
    // angles weight the normals smoothing averages).
    let smoothed = faces.iter().enumerate().any(|(f, face)| whole(face) && group(f) != 0);
    let mut unit = vec![[0.0f32; 3]; faces.len()];
    let mut angle = vec![[0.0f32; 3]; if smoothed { faces.len() } else { 0 }];
    for (f, face) in faces.iter().enumerate() {
        if !whole(face) {
            continue;
        }
        let p = face.map(|i| pos[usize::from(i)]);
        let len = |v: [f32; 3]| (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
        let fnrm = face_normal(p[0], p[1], p[2]);
        if len(fnrm) > 0.0 {
            unit[f] = fnrm.map(|c| c / len(fnrm));
        }
        if !smoothed {
            continue;
        }
        for k in 0..3 {
            let (a, b, c) = (p[k], p[(k + 1) % 3], p[(k + 2) % 3]);
            let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
            let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
            let dot = u[0] * v[0] + u[1] * v[1] + u[2] * v[2];
            angle[f][k] = len(face_normal(a, b, c)).atan2(dot);
        }
    }

    // The faces around each position, as (face, corner), in compressed rows, the position named by its first vertex
    // (a texture seam splits a vertex where the surface is smooth); only built when some face is smoothed.
    let mut start = vec![0u32; n + 1];
    let mut around: Vec<(u32, u8)> = Vec::new();
    let mut canon: Vec<u32> = Vec::new();
    if smoothed {
        let mut first: FastMap<[u32; 3], u32> = FastMap::default();
        first.reserve(n);
        canon = (pos.iter().enumerate())
            .map(|(i, p)| *first.entry(p.map(|c| (c + 0.0).to_bits())).or_insert(u32_of(i)))
            .collect();
        for face in faces.iter().filter(|f| whole(f)) {
            for &i in face {
                start[canon[usize::from(i)] as usize + 1] += 1;
            }
        }
        for i in 0..n {
            start[i + 1] += start[i];
        }
        let mut fill = start.clone();
        around = vec![(0, 0); start[n] as usize];
        for (f, face) in faces.iter().enumerate().filter(|(_, f)| whole(f)) {
            for (k, &i) in face.iter().enumerate() {
                let slot = &mut fill[canon[usize::from(i)] as usize];
                #[allow(
                    clippy::cast_possible_truncation,
                    reason = "3DS has at most 65535 faces of 3 corners"
                )]
                let entry = (f as u32, k as u8);
                around[*slot as usize] = entry;
                *slot += 1;
            }
        }
    }

    let mut seen: FastMap<(usize, u16, [u32; 3]), u32> = FastMap::default();
    seen.reserve(n);
    // The primitive of the material faces are using, out of `prims` while it is: faces come in
    // runs of one material.
    let mut cur = (usize::MAX, Prim::default());
    for (f, face) in faces.iter().enumerate() {
        if !whole(face) {
            continue;
        }
        let mat = face_mat[f].unwrap_or_else(|| {
            if materials.last().is_none_or(|m| m.name != "default") {
                materials.push(legacy_material::default_material(false));
            }
            materials.len() - 1
        });
        if cur.0 != mat {
            let next = prims.remove(&mat).unwrap_or_else(|| Prim {
                material: mat,
                ..Prim::default()
            });
            let (m, done) = std::mem::replace(&mut cur, (mat, next));
            if m != usize::MAX {
                prims.insert(m, done);
            }
        }
        let prim = &mut cur.1;
        let g = group(f);
        for &vi in face {
            let mut nrm = unit[f];
            if g != 0 {
                let v = canon[usize::from(vi)] as usize;
                let mut sum = [0.0f32; 3];
                for &(o, k) in &around[start[v] as usize..start[v + 1] as usize] {
                    let o = o as usize;
                    if o == f || group(o) & g != 0 {
                        let w = angle[o][usize::from(k)];
                        for c in 0..3 {
                            sum[c] += unit[o][c] * w;
                        }
                    }
                }
                let len = (sum[0] * sum[0] + sum[1] * sum[1] + sum[2] * sum[2]).sqrt();
                if len > 0.0 {
                    nrm = sum.map(|c| c / len);
                }
            }
            // Still zero when no face in the group gave a normal: the vertex then takes the one every format's
            // does, as the primitive is written.
            // -0.0 + 0.0 is 0.0: one key for both zeros.
            let nrm = nrm.map(|c| c + 0.0);
            let idx = *seen.entry((mat, vi, nrm.map(f32::to_bits))).or_insert_with(|| {
                prim.positions.push(pos[usize::from(vi)]);
                prim.normals.push(nrm);
                if has_uvs {
                    let [s, tv] = t.uvs.get(usize::from(vi)).copied().unwrap_or_default();
                    prim.uvs.push([s, 1.0 - tv]);
                }
                u32_of(prim.positions.len() - 1)
            });
            prim.indices.push(idx);
        }
    }
    if cur.0 != usize::MAX {
        prims.insert(cur.0, cur.1);
    }
}

#[cfg(all(test, feature = "fs"))]
mod tests {
    use super::*;
    use crate::document::Pose;

    fn chunk(id: u16, body: &[u8]) -> Vec<u8> {
        let mut out = id.to_le_bytes().to_vec();
        out.extend(u32::try_from(body.len() + 6).unwrap().to_le_bytes());
        out.extend(body);
        out
    }

    fn f32s(xs: &[f32]) -> Vec<u8> {
        xs.iter().flat_map(|x| x.to_le_bytes()).collect()
    }

    fn u16s(xs: &[u16]) -> Vec<u8> {
        xs.iter().flat_map(|x| x.to_le_bytes()).collect()
    }

    /// A trimesh of `verts` and `faces`, with a mesh matrix moving it to `origin` when there is one.
    fn trimesh(verts: &[[f32; 3]], faces: &[[u16; 3]], origin: Option<[f32; 3]>) -> Vec<u8> {
        let mut v = u16::try_from(verts.len()).unwrap().to_le_bytes().to_vec();
        v.extend(f32s(verts.as_flattened()));
        let mut f = u16::try_from(faces.len()).unwrap().to_le_bytes().to_vec();
        for face in faces {
            f.extend(u16s(&[face[0], face[1], face[2], 0]));
        }
        let mut t = chunk(VERTICES, &v);
        if let Some(o) = origin {
            t.extend(chunk(
                MESH_MATRIX,
                &f32s(&[1., 0., 0., 0., 1., 0., 0., 0., 1., o[0], o[1], o[2]]),
            ));
        }
        t.extend(chunk(FACES, &f));
        t
    }

    fn object(name: &str, body: &[u8]) -> Vec<u8> {
        let mut o = name.as_bytes().to_vec();
        o.push(0);
        o.extend(body);
        chunk(OBJECT, &o)
    }

    /// A square on the ground (Z up) of two triangles in one smoothing group, red, and a lone triangle standing up
    /// in no material.
    fn square() -> Vec<u8> {
        let mut mat = chunk(MAT_NAME, b"Red\0");
        mat.extend(chunk(MAT_DIFFUSE, &chunk(COLOR_U8, &[255, 0, 0])));
        mat.extend(chunk(MAT_TRANSPARENCY, &chunk(PERCENT_U16, &25u16.to_le_bytes())));
        let mut map = chunk(MAP_FILE, b"red.png\0");
        map.extend(chunk(MAP_USCALE, &f32s(&[2.0])));
        mat.extend(chunk(MAT_BUMPMAP, &map));

        let mut verts = 4u16.to_le_bytes().to_vec();
        verts.extend(f32s(&[0., 0., 0., 2., 0., 0., 2., 2., 0., 0., 2., 0.]));
        let mut uvs = 4u16.to_le_bytes().to_vec();
        uvs.extend(f32s(&[0., 0., 1., 0., 1., 1., 0., 1.]));
        let mut faces = 2u16.to_le_bytes().to_vec();
        for f in [[0u16, 1, 2, 7], [0, 2, 3, 7]] {
            faces.extend(u16s(&f));
        }
        let mut fm = b"Red\0".to_vec();
        fm.extend(2u16.to_le_bytes());
        fm.extend(u16s(&[0, 1]));
        faces.extend(chunk(FACE_MATERIAL, &fm));
        faces.extend(chunk(
            SMOOTHING,
            &[1u32, 1].iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<_>>(),
        ));
        let mut tri = chunk(VERTICES, &verts);
        tri.extend(chunk(UVS, &uvs));
        tri.extend(chunk(FACES, &faces));

        let mut editor = chunk(MATERIAL, &mat);
        editor.extend(object("Floor", &chunk(TRIMESH, &tri)));
        editor.extend(object(
            "Wall",
            &chunk(
                TRIMESH,
                &trimesh(&[[0., 0., 0.], [1., 0., 0.], [0., 0., 1.]], &[[0, 1, 2]], None),
            ),
        ));
        chunk(MAIN, &chunk(EDITOR, &editor))
    }

    fn read(name: &str, data: &[u8]) -> Result<Document> {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join(name);
        std::fs::write(&p, data).unwrap();
        load(
            crate::formats::Input::file(&p),
            &crate::assets::Folder::new(dir.path()),
            Keep::ALL,
        )
    }

    /// What the root node scales these files by: their master scale, 1 (or none).
    const UNIT: f32 = 1.0;

    fn close(a: [f32; 3], b: [f32; 3]) -> bool {
        (0..3).all(|k| (a[k] - b[k]).abs() < 1e-4)
    }

    #[test]
    fn the_triangle_limit_refuses_bigger_models() {
        let read = |max_triangles| {
            let keep = Keep::ALL.with_max_triangles(max_triangles);
            crate::formats::load_bytes(&square(), "s.3ds", "3ds", &crate::assets::Memory::new(), keep)
                .map(|d| d.flatten(crate::document::Pose::Rest).unwrap().unwrap().triangles())
        };
        let err = read(2).unwrap_err();
        assert!(format!("{err:#}").contains("more than 2 triangles"), "{err:#}");
        assert_eq!(read(3).unwrap(), 3);
    }

    #[test]
    fn meshes_materials_and_smoothing() {
        let doc = read("floor.3ds", &square()).unwrap();
        let names: Vec<&str> = doc.json()["nodes"]
            .as_array()
            .unwrap()
            .iter()
            .map(|n| n["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, ["Floor", "Wall", "RootNode"]);
        let info = doc.source_info();
        assert_eq!(info.format.as_deref(), Some("3DS"));
        assert_eq!(info.up_axis, Fact::Declared(Axis::PosZ));
        assert_eq!(info.handedness, Fact::Declared(Handedness::Right));
        // 3DS names no unit, and with no master scale nothing is scaled.
        assert_eq!(info.meters_per_unit, Fact::Unknown);
        assert_eq!(info.frame_rate, Fact::Unknown, "no keyframer");
        assert!(info.converted.up_axis && !info.converted.units);
        assert!(doc.json()["nodes"][2].get("scale").is_none());
        let red = &doc.json()["materials"][0]["extras"]["3ds"];
        assert_eq!(red["diffuse"], json!([255, 0, 0]));
        assert_eq!(red["transparency"], json!(25.0));
        assert_eq!(red["maps"]["bump"], json!({ "file": "red.png", "uScale": 2.0 }));

        let mesh = doc.flatten(Pose::Rest).unwrap().unwrap();
        assert_eq!(mesh.triangles(), 3);
        assert_eq!(mesh.prims.len(), 2);
        let floor = &mesh.prims[0];
        let red = &mesh.materials[floor.material];
        assert_eq!(red.name, "Red");
        assert_eq!(red.color, [1.0, 0.0, 0.0, 0.75]);
        // One smoothing group: the shared corners are shared vertices.
        assert_eq!(floor.positions.len(), 4);
        assert!(
            floor.positions.iter().all(|p| p[1].abs() < 1e-6),
            "Z up became Y up: {:?}",
            floor.positions
        );
        assert!(
            floor
                .positions
                .iter()
                .any(|&p| close(p.map(|c| c / UNIT), [2.0, 0.0, -2.0]))
        );
        assert!(floor.normals.iter().all(|n| n[1] > 0.99), "{:?}", floor.normals);
        assert!(floor.uvs.contains(&[0.0, 1.0]), "V flipped to glTF's origin");
        let wall = &mesh.prims[1];
        assert_eq!(mesh.materials[wall.material].name, "default");
        assert_eq!(wall.positions.len(), 3);
        assert!(wall.normals.iter().all(|n| n[2].abs() > 0.99), "{:?}", wall.normals);
        assert!(mesh.to_glb().unwrap().starts_with(b"glTF"));
    }

    fn track(id: u16, keys: &[(u32, &[f32])]) -> Vec<u8> {
        let mut t = u16s(&[0, 0, 0, 0, 0]);
        t.extend(u32::try_from(keys.len()).unwrap().to_le_bytes());
        for (frame, v) in keys {
            t.extend(frame.to_le_bytes());
            t.extend(0u16.to_le_bytes());
            t.extend(f32s(v));
        }
        chunk(id, &t)
    }

    fn node(id: u16, name: &str, parent: u16, pivot: [f32; 3], tracks: &[Vec<u8>]) -> Vec<u8> {
        let mut hdr = name.as_bytes().to_vec();
        hdr.push(0);
        hdr.extend(u16s(&[0, 0, parent]));
        let mut n = chunk(NODE_ID, &id.to_le_bytes());
        n.extend(chunk(NODE_HDR, &hdr));
        n.extend(chunk(PIVOT, &f32s(&pivot)));
        for t in tracks {
            n.extend(t);
        }
        chunk(OBJECT_NODE_TAG, &n)
    }

    /// A unit triangle moved to `p`.
    fn at(p: [f32; 3]) -> Vec<[f32; 3]> {
        [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]]
            .iter()
            .map(|v| [v[0] + p[0], v[1] + p[1], v[2] + p[2]])
            .collect()
    }

    #[test]
    fn the_keyframer_places_and_animates() {
        let base = trimesh(&at([5., 0., 0.]), &[[0, 1, 2]], Some([5., 0., 0.]));
        let arm = trimesh(&at([5., 3., 0.]), &[[0, 1, 2]], Some([5., 3., 0.]));
        let mut editor = object("Base", &chunk(TRIMESH, &base));
        editor.extend(object("Arm", &chunk(TRIMESH, &arm)));
        let quarter = std::f32::consts::FRAC_PI_2;
        let mut kf = node(
            0,
            "Base",
            u16::MAX,
            [0.; 3],
            &[track(POS_TRACK, &[(0, &[5., 0., 0.]), (30, &[5., 0., 2.])])],
        );
        kf.extend(node(
            1,
            "Arm",
            0,
            [0.5, 0.5, 0.],
            &[
                track(POS_TRACK, &[(0, &[0.5, 3.5, 0.])]),
                track(ROT_TRACK, &[(0, &[0., 0., 0., 1.]), (30, &[quarter, 0., 0., 1.])]),
            ],
        ));
        let mut main = chunk(EDITOR, &editor);
        main.extend(chunk(KEYFRAMER, &kf));
        let doc = read("arm.3ds", &chunk(MAIN, &main)).unwrap();
        assert_eq!(doc.json()["nodes"][1]["name"], "Arm");
        assert_eq!(doc.json()["nodes"][0]["children"], json!([1]));
        assert_eq!(doc.json()["animations"][0]["channels"].as_array().unwrap().len(), 2);
        assert_eq!(doc.source_info().frame_rate, Fact::Assumed(30.0));

        // At rest, everything is where the editor has it (turned Y up).
        let mesh = doc.flatten(Pose::Rest).unwrap().unwrap();
        let mut got: Vec<[f32; 3]> = mesh.prims.iter().flat_map(|p| p.positions.clone()).collect();
        let mut want: Vec<[f32; 3]> = at([5., 0., 0.])
            .into_iter()
            .chain(at([5., 3., 0.]))
            .map(|[x, y, z]| [x, z, -y].map(|c| c * UNIT))
            .collect();
        #[allow(clippy::cast_possible_truncation, reason = "small test values")]
        let key = |p: &[f32; 3]| p.map(|c| (c * 100_000.0).round() as i64);
        got.sort_by_key(key);
        want.sort_by_key(key);
        assert!(got.iter().zip(&want).all(|(a, b)| close(*a, *b)), "{got:?} != {want:?}");
    }

    #[test]
    fn keys_that_are_not_numbers_are_left_out() {
        let tri = trimesh(&at([0., 0., 0.]), &[[0, 1, 2]], None);
        let editor = object("Tri", &chunk(TRIMESH, &tri));
        let kf = node(
            0,
            "Tri",
            u16::MAX,
            [0.; 3],
            &[
                track(
                    POS_TRACK,
                    &[
                        (0, &[f32::NAN, 0., 0.]),
                        (10, &[1., 2., 3.]),
                        (20, &[4., f32::INFINITY, 6.]),
                    ],
                ),
                track(ROT_TRACK, &[(0, &[f32::NAN, 0., 0., 1.])]),
                track(SCL_TRACK, &[(0, &[f32::NAN, f32::NAN, f32::NAN]), (10, &[2., 2., 2.])]),
            ],
        );
        let mut main = chunk(EDITOR, &editor);
        main.extend(chunk(KEYFRAMER, &kf));
        let doc = read("nan.3ds", &chunk(MAIN, &main)).unwrap();
        // The first key that is a number is the rest pose (Z up turned Y up at the root above).
        let node = doc.json()["nodes"]
            .as_array()
            .unwrap()
            .iter()
            .find(|n| n["name"] == "Tri")
            .unwrap();
        assert_eq!(node["translation"], json!([1.0, 2.0, 3.0]));
        assert_eq!(node["scale"], json!([2.0, 2.0, 2.0]));
        assert!(node.get("rotation").is_none());
        let text = serde_json::to_string(doc.json()).unwrap();
        assert!(!text.contains("null"), "{text}");
        assert!(doc.flatten(Pose::Rest).unwrap().is_some());
    }

    #[test]
    fn a_mesh_saved_on_a_later_frame_follows_its_mesh_matrix() {
        // A triangle that turns a quarter (clockwise, as 3DS turns) about Z by frame 30, saved on frame 30: its
        // vertices and mesh matrix are that frame's.
        let quarter = std::f32::consts::FRAC_PI_2;
        let saved = [[5., 0., 0.], [5., -1., 0.], [6., 0., 0.]];
        let mut mesh = trimesh(&saved, &[[0, 1, 2]], None);
        mesh.extend(chunk(
            MESH_MATRIX,
            &f32s(&[0., -1., 0., 1., 0., 0., 0., 0., 1., 5., 0., 0.]),
        ));
        let editor = object("Spinner", &chunk(TRIMESH, &mesh));
        let kf = node(
            0,
            "Spinner",
            u16::MAX,
            [0.; 3],
            &[
                track(POS_TRACK, &[(0, &[5., 0., 0.])]),
                track(ROT_TRACK, &[(0, &[0., 0., 0., 1.]), (30, &[quarter, 0., 0., 1.])]),
            ],
        );
        let mut main = chunk(EDITOR, &editor);
        main.extend(chunk(KEYFRAMER, &kf));
        let doc = read("spinner.3ds", &chunk(MAIN, &main)).unwrap();
        let drawn = |pose| -> Vec<[f32; 3]> {
            let mesh = doc.flatten(pose).unwrap().unwrap();
            mesh.prims.iter().flat_map(|p| p.positions.clone()).collect()
        };
        let y_up =
            |v: &[[f32; 3]]| -> Vec<[f32; 3]> { v.iter().map(|&[x, y, z]| [x, z, -y].map(|c| c * UNIT)).collect() };
        let same = |got: &[[f32; 3]], want: &[[f32; 3]]| want.iter().all(|w| got.iter().any(|g| close(*g, *w)));
        // On frame 30 it is where the file has it.
        let then = drawn(Pose::Animation { index: 0, time: 1.0 });
        assert!(same(&then, &y_up(&saved)), "{then:?}");
        // At rest, the first key, it hasn't turned yet.
        let rest = drawn(Pose::Rest);
        assert!(same(&rest, &y_up(&at([5., 0., 0.]))), "{rest:?}");
    }

    #[test]
    fn cameras_and_lights() {
        let mut cam = f32s(&[0., -10., 0., 0., 0., 0., 0., 50.]);
        cam.extend(chunk(CAM_RANGES, &f32s(&[1., 100.])));
        let mut spot = f32s(&[0., 0., 10.]);
        spot.extend(chunk(COLOR_U8, &[255, 255, 255]));
        spot.extend(chunk(DL_SPOTLIGHT, &f32s(&[0., 0., 0., 30., 60.])));
        let mut editor = object("Tri", &chunk(TRIMESH, &trimesh(&at([0.; 3]), &[[0, 1, 2]], None)));
        editor.extend(object("Cam", &chunk(CAMERA, &cam)));
        editor.extend(object("Spot", &chunk(LIGHT, &spot)));
        let doc = read("lit.3ds", &chunk(MAIN, &chunk(EDITOR, &editor))).unwrap();
        let p = &doc.json()["cameras"][0]["perspective"];
        assert_eq!(p["znear"], json!(1.0));
        assert_eq!(p["zfar"], json!(100.0));
        let light = &doc.json()["extensions"]["KHR_lights_punctual"]["lights"][0];
        assert_eq!(light["type"], "spot");
        let outer = light["spot"]["outerConeAngle"].as_f64().unwrap();
        assert!((outer - 30f64.to_radians()).abs() < 1e-9);
        // The camera looks along +Y: its -Z turned onto +Y is a quarter turn about +X.
        let q: Vec<f64> = doc.json()["nodes"][1]["rotation"]
            .as_array()
            .unwrap()
            .iter()
            .map(|c| c.as_f64().unwrap())
            .collect();
        let h = std::f64::consts::FRAC_1_SQRT_2;
        assert!((q[0] - h).abs() < 1e-6 && (q[3] - h).abs() < 1e-6, "{q:?}");
        // The spot looks straight down: -Z already.
        let q = doc.json()["nodes"][2]["rotation"].as_array().unwrap();
        assert!((q[3].as_f64().unwrap().abs() - 1.0).abs() < 1e-6, "{q:?}");
    }

    /// A keyframer node that isn't an object's (`tag` says whose: a camera's, a light's, a target's), named as the
    /// camera or light is.
    fn other(tag: u16, id: u16, name: &str, parent: u16, tracks: &[Vec<u8>]) -> Vec<u8> {
        let mut hdr = name.as_bytes().to_vec();
        hdr.push(0);
        hdr.extend(u16s(&[0, 0, parent]));
        let mut n = chunk(NODE_ID, &id.to_le_bytes());
        n.extend(chunk(NODE_HDR, &hdr));
        for t in tracks {
            n.extend(t);
        }
        chunk(tag, &n)
    }

    /// What is drawn in `pose`, Z up as the file has it.
    fn drawn(doc: &Document, pose: Pose) -> Vec<[f32; 3]> {
        let mesh = doc.flatten(pose).unwrap().unwrap();
        let points = mesh.prims.iter().flat_map(|p| p.positions.clone());
        // Back in the file's Z up and units: the root node's turn and scale taken off.
        points.map(|[x, y, z]| [x, -z, y].map(|c| c / UNIT)).collect()
    }

    fn same(got: &[[f32; 3]], want: &[[f32; 3]]) -> bool {
        got.len() == want.len() && want.iter().all(|w| got.iter().any(|g| close(*g, *w)))
    }

    /// A camera at (0, -10, 0) looking along +Y at its target, and a triangle whose node is at (1, 2, -10) in the
    /// frame of its parent. `cam` and `target` are the tracks of the camera's two nodes.
    fn beside_a_camera(parent: u16, cam: &[Vec<u8>], target: &[Vec<u8>]) -> Document {
        // Looking along +Y with Z up, the camera's X is the world's, its Y the world's Z and its Z the world's -Y:
        // (1, 2, -10) from the camera is (1, 0, 2) in the world.
        let saved = [[1., 0., 2.], [2., 0., 2.], [1., 0., 3.]];
        let mut mesh = trimesh(&saved, &[[0, 1, 2]], None);
        mesh.extend(chunk(
            MESH_MATRIX,
            &f32s(&[1., 0., 0., 0., 0., 1., 0., -1., 0., 1., 0., 2.]),
        ));
        let mut editor = object("Tri", &chunk(TRIMESH, &mesh));
        editor.extend(object(
            "Cam",
            &chunk(CAMERA, &f32s(&[0., -10., 0., 0., 0., 0., 0., 50.])),
        ));
        let mut kf = other(CAMERA_NODE_TAG, 0, "Cam", u16::MAX, cam);
        kf.extend(node(
            1,
            "Tri",
            parent,
            [0.; 3],
            &[track(POS_TRACK, &[(0, &[1., 2., -10.])])],
        ));
        kf.extend(other(TARGET_NODE_TAG, 2, "Cam", u16::MAX, target));
        let mut main = chunk(EDITOR, &editor);
        main.extend(chunk(KEYFRAMER, &kf));
        read("cam.3ds", &chunk(MAIN, &main)).unwrap()
    }

    /// How many keys the rotation channel of `node` has.
    fn rotation_keys(doc: &Document, node: usize) -> Option<u64> {
        let anim = &doc.json()["animations"][0];
        let channel = anim["channels"]
            .as_array()?
            .iter()
            .find(|c| c["target"]["node"] == json!(node) && c["target"]["path"] == "rotation")?;
        let input = anim["samplers"][usize_of(channel["sampler"].as_u64()?)]["input"].as_u64()?;
        doc.json()["accessors"][usize_of(input)]["count"].as_u64()
    }

    #[test]
    fn a_child_of_a_camera_is_in_the_frame_the_camera_aims() {
        let doc = beside_a_camera(
            0,
            &[track(POS_TRACK, &[(0, &[0., -10., 0.])])],
            &[track(POS_TRACK, &[(0, &[0., 0., 0.]), (30, &[10., -10., 0.])])],
        );
        let nodes = &doc.json()["nodes"];
        assert_eq!(nodes[0]["name"], "Cam");
        assert_eq!(nodes[0]["camera"], json!(0));
        assert_eq!(nodes[0]["children"], json!([1]));
        assert_eq!(nodes[1]["name"], "Tri");
        assert_eq!(nodes[2]["name"], "Cam.Target");
        assert_eq!(nodes[3]["children"], json!([0, 2]));
        assert_eq!(doc.json()["cameras"].as_array().unwrap().len(), 1);
        // Looking along +Y: glTF's camera, looking down its -Z, turned a quarter about X.
        let q: Vec<f64> = nodes[0]["rotation"]
            .as_array()
            .unwrap()
            .iter()
            .map(|c| c.as_f64().unwrap())
            .collect();
        let h = std::f64::consts::FRAC_1_SQRT_2;
        assert!((q[0] - h).abs() < 1e-9 && (q[3] - h).abs() < 1e-9, "{q:?}");
        // At rest the triangle is where the editor has it.
        let rest = drawn(&doc, Pose::Rest);
        assert!(same(&rest, &[[1., 0., 2.], [2., 0., 2.], [1., 0., 3.]]), "{rest:?}");
        // On frame 30 the target is at (10, -10, 0) and the camera looks along +X: its X is the world's -Y, its Y
        // the world's Z, its Z the world's -X. The triangle has swung round with it.
        let then = drawn(&doc, Pose::Animation { index: 0, time: 1.0 });
        assert!(
            same(&then, &[[10., -11., 2.], [10., -12., 2.], [10., -11., 3.]]),
            "{then:?}"
        );
        // The camera's turn is sampled on every frame of the target's track.
        assert_eq!(rotation_keys(&doc, 0), Some(31));
    }

    #[test]
    fn a_cameras_roll_turns_its_children() {
        let doc = beside_a_camera(
            0,
            &[
                track(POS_TRACK, &[(0, &[0., -10., 0.])]),
                track(ROLL_TRACK, &[(0, &[0.]), (30, &[90.])]),
            ],
            &[track(POS_TRACK, &[(0, &[0., 0., 0.])])],
        );
        let rest = drawn(&doc, Pose::Rest);
        assert!(same(&rest, &[[1., 0., 2.], [2., 0., 2.], [1., 0., 3.]]), "{rest:?}");
        // Rolled a quarter, the camera's X is the world's Z and its Y the world's -X (its Z still the world's -Y),
        // the way the editor's cameras roll here.
        let then = drawn(&doc, Pose::Animation { index: 0, time: 1.0 });
        assert!(same(&then, &[[-2., 0., 1.], [-2., 0., 2.], [-3., 0., 1.]]), "{then:?}");
        assert_eq!(rotation_keys(&doc, 0), Some(31));
    }

    #[test]
    fn a_camera_with_nothing_under_it_stays_where_the_editor_has_it() {
        let doc = beside_a_camera(
            u16::MAX,
            &[
                track(POS_TRACK, &[(0, &[0., -10., 0.])]),
                track(ROLL_TRACK, &[(0, &[0.]), (30, &[90.])]),
            ],
            &[track(POS_TRACK, &[(0, &[0., 0., 0.]), (30, &[10., -10., 0.])])],
        );
        let nodes = doc.json()["nodes"].as_array().unwrap();
        let names: Vec<&str> = nodes.iter().map(|n| n["name"].as_str().unwrap()).collect();
        assert_eq!(names, ["Cam", "Tri", "RootNode"]);
        assert_eq!(nodes[0]["camera"], json!(0));
        assert_eq!(nodes[0]["translation"], json!([0.0, -10.0, 0.0]));
        assert!(nodes[0].get("extras").is_none(), "{}", nodes[0]);
        assert!(doc.json().get("animations").is_none());
    }

    #[test]
    fn children_of_lights_and_of_targets() {
        // A triangle under a light that rises, and another under the target of a spotlight shining straight down,
        // which rises too.
        let a = trimesh(&at([1., 0., 5.]), &[[0, 1, 2]], Some([1., 0., 5.]));
        let b = trimesh(&at([3., 1., 0.]), &[[0, 1, 2]], Some([3., 1., 0.]));
        let mut omni = f32s(&[0., 0., 5.]);
        omni.extend(chunk(COLOR_U8, &[255, 255, 255]));
        let mut spot = f32s(&[3., 0., 10.]);
        spot.extend(chunk(COLOR_U8, &[255, 255, 255]));
        spot.extend(chunk(DL_SPOTLIGHT, &f32s(&[3., 0., 0., 30., 60.])));
        let mut editor = object("A", &chunk(TRIMESH, &a));
        editor.extend(object("B", &chunk(TRIMESH, &b)));
        editor.extend(object("Omni", &chunk(LIGHT, &omni)));
        editor.extend(object("Spot", &chunk(LIGHT, &spot)));
        let mut kf = other(
            LIGHT_NODE_TAG,
            0,
            "Omni",
            u16::MAX,
            &[track(POS_TRACK, &[(0, &[0., 0., 5.]), (30, &[0., 0., 7.])])],
        );
        kf.extend(node(1, "A", 0, [0.; 3], &[track(POS_TRACK, &[(0, &[1., 0., 0.])])]));
        kf.extend(other(
            L_TARGET_NODE_TAG,
            2,
            "Spot",
            u16::MAX,
            &[track(POS_TRACK, &[(0, &[3., 0., 0.]), (30, &[3., 0., 4.])])],
        ));
        kf.extend(node(3, "B", 2, [0.; 3], &[track(POS_TRACK, &[(0, &[0., 1., 0.])])]));
        kf.extend(other(
            SPOTLIGHT_NODE_TAG,
            4,
            "Spot",
            u16::MAX,
            &[track(POS_TRACK, &[(0, &[3., 0., 10.])])],
        ));
        let mut main = chunk(EDITOR, &editor);
        main.extend(chunk(KEYFRAMER, &kf));
        let doc = read("lights.3ds", &chunk(MAIN, &main)).unwrap();
        let nodes = doc.json()["nodes"].as_array().unwrap();
        let names: Vec<&str> = nodes.iter().map(|n| n["name"].as_str().unwrap()).collect();
        assert_eq!(names, ["Omni", "A", "Spot.Target", "B", "Spot", "RootNode"]);
        assert_eq!(nodes[0]["children"], json!([1]));
        assert_eq!(nodes[2]["children"], json!([3]));
        let light = |n: &Value| n["extensions"]["KHR_lights_punctual"]["light"].clone();
        assert_eq!(light(&nodes[0]), json!(0));
        assert_eq!(light(&nodes[4]), json!(1));
        assert_eq!(nodes[4]["translation"], json!([3.0, 0.0, 10.0]));
        // Straight down is the way a glTF spotlight shines already.
        assert!(nodes[4].get("rotation").is_none(), "{}", nodes[4]);
        let lights = &doc.json()["extensions"]["KHR_lights_punctual"]["lights"];
        assert_eq!(lights[0]["type"], "point");
        assert_eq!(lights[1]["type"], "spot");

        let both = |a: [f32; 3], b: [f32; 3]| -> Vec<[f32; 3]> { at(a).into_iter().chain(at(b)).collect() };
        let rest = drawn(&doc, Pose::Rest);
        assert!(same(&rest, &both([1., 0., 5.], [3., 1., 0.])), "{rest:?}");
        let then = drawn(&doc, Pose::Animation { index: 0, time: 1.0 });
        assert!(same(&then, &both([1., 0., 7.], [3., 1., 4.])), "{then:?}");
    }

    #[test]
    fn nodes_of_every_kind_count_toward_ids_a_file_leaves_out() {
        // No node has an id: each is numbered by where it comes, the camera's nodes too, so parent 2 is the third
        // node, the camera.
        let unnumbered = |tag: u16, name: &str, parent: u16, at: [f32; 3]| {
            let mut hdr = name.as_bytes().to_vec();
            hdr.push(0);
            hdr.extend(u16s(&[0, 0, parent]));
            let mut n = chunk(NODE_HDR, &hdr);
            n.extend(track(POS_TRACK, &[(0, &at)]));
            chunk(tag, &n)
        };
        let mut editor = object("Tri", &chunk(TRIMESH, &trimesh(&at([0.; 3]), &[[0, 1, 2]], None)));
        editor.extend(object(
            "Cam",
            &chunk(CAMERA, &f32s(&[0., -10., 0., 0., 0., 0., 0., 50.])),
        ));
        let mut kf = unnumbered(OBJECT_NODE_TAG, "$$$DUMMY", u16::MAX, [0.; 3]);
        kf.extend(unnumbered(TARGET_NODE_TAG, "Cam", u16::MAX, [0.; 3]));
        kf.extend(unnumbered(CAMERA_NODE_TAG, "Cam", u16::MAX, [0., -10., 0.]));
        kf.extend(unnumbered(OBJECT_NODE_TAG, "Tri", 2, [0., 0., -10.]));
        let mut main = chunk(EDITOR, &editor);
        main.extend(chunk(KEYFRAMER, &kf));
        let doc = read("old.3ds", &chunk(MAIN, &main)).unwrap();
        let nodes = &doc.json()["nodes"];
        assert_eq!(nodes[2]["name"], "Cam");
        assert_eq!(nodes[2]["children"], json!([3]));
        assert_eq!(nodes[3]["name"], "Tri");
    }

    /// The flattened mesh's triangles, each as its winding's normal and its corners' normals.
    fn windings(mesh: &crate::mesh::Mesh) -> Vec<([f32; 3], Vec<[f32; 3]>)> {
        let mut out = Vec::new();
        for p in &mesh.prims {
            for t in p.indices.chunks_exact(3) {
                let [a, b, c] = [0, 1, 2].map(|k| p.positions[t[k] as usize]);
                let n = face_normal(a, b, c);
                let len = n.iter().map(|v| v * v).sum::<f32>().sqrt();
                out.push((n.map(|v| v / len), t.iter().map(|&i| p.normals[i as usize]).collect()));
            }
        }
        out
    }

    #[test]
    fn a_mirroring_mesh_matrix_doesnt_turn_faces_inside_out() {
        // Made facing +Z, then mirrored in X: the vertices are written mirrored, the faces as made.
        let mirrored = |origin: [f32; 3]| {
            let verts: Vec<[f32; 3]> = at([0.; 3]).iter().map(|v| [origin[0] - v[0], v[1], v[2]]).collect();
            let mut t = chunk(VERTICES, &{
                let mut v = 3u16.to_le_bytes().to_vec();
                v.extend(f32s(verts.as_flattened()));
                v
            });
            t.extend(chunk(
                MESH_MATRIX,
                &f32s(&[-1., 0., 0., 0., 1., 0., 0., 0., 1., origin[0], origin[1], origin[2]]),
            ));
            t.extend(chunk(FACES, &u16s(&[1, 0, 1, 2, 0])));
            chunk(TRIMESH, &t)
        };
        // Where the editor has it, and placed by the keyframer through a mirroring node.
        let alone = chunk(MAIN, &chunk(EDITOR, &object("Alone", &mirrored([0.; 3]))));
        let mut main = chunk(EDITOR, &object("Placed", &mirrored([4., 0., 0.])));
        main.extend(chunk(
            KEYFRAMER,
            &node(
                0,
                "Placed",
                u16::MAX,
                [0.; 3],
                &[
                    track(POS_TRACK, &[(0, &[4., 0., 0.])]),
                    track(SCL_TRACK, &[(0, &[-1., 1., 1.])]),
                ],
            ),
        ));
        for file in [alone, chunk(MAIN, &main)] {
            let mesh = read("m.3ds", &file).unwrap().flatten(Pose::Rest).unwrap().unwrap();
            let w = windings(&mesh);
            assert_eq!(w.len(), 1);
            // Z up is Y up.
            assert!(close(w[0].0, [0.0, 1.0, 0.0]), "{w:?}");
            assert!(w[0].1.iter().all(|&n| close(n, [0.0, 1.0, 0.0])), "{w:?}");
        }
    }

    #[test]
    fn smoothing_spans_texture_seams_and_flat_materials_ignore_it() {
        // A fold of two faces in one group, their shared edge's vertices written twice (as a texture seam does).
        let tri = |shading: Option<u16>| {
            let verts = [
                [0., 0., 0.],
                [1., 0., 0.],
                [0., 1., 0.],
                [0., 0., 0.],
                [1., 0., 0.],
                [0., 0., 1.],
            ];
            let mut faces = 2u16.to_le_bytes().to_vec();
            faces.extend(u16s(&[0, 1, 2, 0, 3, 5, 4, 0]));
            let mut fm = b"M\0".to_vec();
            fm.extend(u16s(&[2, 0, 1]));
            faces.extend(chunk(FACE_MATERIAL, &fm));
            faces.extend(chunk(
                SMOOTHING,
                &[1u32, 1].iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<_>>(),
            ));
            let mut v = 6u16.to_le_bytes().to_vec();
            v.extend(f32s(verts.as_flattened()));
            let mut t = chunk(VERTICES, &v);
            // Too few texture coordinates: the rest are zero.
            let mut uv = 2u16.to_le_bytes().to_vec();
            uv.extend(f32s(&[0., 0., 1., 0.]));
            t.extend(chunk(UVS, &uv));
            t.extend(chunk(FACES, &faces));
            let mut mat = chunk(MAT_NAME, b"M\0");
            if let Some(s) = shading {
                mat.extend(chunk(MAT_SHADING, &s.to_le_bytes()));
            }
            let mut editor = chunk(MATERIAL, &mat);
            editor.extend(object("Fold", &chunk(TRIMESH, &t)));
            chunk(MAIN, &chunk(EDITOR, &editor))
        };
        let h = std::f32::consts::FRAC_1_SQRT_2;
        let mesh = read("s.3ds", &tri(Some(3)))
            .unwrap()
            .flatten(Pose::Rest)
            .unwrap()
            .unwrap();
        let p = &mesh.prims[0];
        assert_eq!(p.uvs.len(), p.positions.len());
        // The fold's edge: (0, 0, 0) and (1, 0, 0), Z up turned Y up, all four of its vertices one normal.
        let edge: Vec<_> = (p.positions.iter().zip(&p.normals))
            .filter(|(q, _)| q[1].abs() < 1e-6 && q[2].abs() < 1e-6)
            .collect();
        assert_eq!(edge.len(), 4, "{p:?}");
        assert!(edge.iter().all(|(_, n)| close(**n, [0.0, h, -h])), "{edge:?}");
        // Shaded flat: each face its own normal.
        let mesh = read("s.3ds", &tri(Some(1)))
            .unwrap()
            .flatten(Pose::Rest)
            .unwrap()
            .unwrap();
        for (face, normals) in windings(&mesh) {
            assert!(normals.iter().all(|&n| close(n, face)), "{face:?} {normals:?}");
        }
    }

    #[test]
    fn an_opacity_map_that_is_the_color_map_cuts_by_its_alpha() {
        let mut mat = chunk(MAT_NAME, b"Leaf\0");
        mat.extend(chunk(MAT_TEXTURE, &chunk(MAP_FILE, b"leaf.png\0")));
        mat.extend(chunk(MAT_OPACMAP, &chunk(MAP_FILE, b"LEAF.PNG\0")));
        let mut t = trimesh(&at([0.; 3]), &[], None);
        let mut faces = 1u16.to_le_bytes().to_vec();
        faces.extend(u16s(&[0, 1, 2, 0]));
        let mut fm = b"Leaf\0".to_vec();
        fm.extend(u16s(&[1, 0]));
        faces.extend(chunk(FACE_MATERIAL, &fm));
        let mut uv = 3u16.to_le_bytes().to_vec();
        uv.extend(f32s(&[0., 0., 1., 0., 0., 1.]));
        t.extend(chunk(UVS, &uv));
        t.extend(chunk(FACES, &faces));
        let mut editor = chunk(MATERIAL, &mat);
        editor.extend(object("Leaf", &chunk(TRIMESH, &t)));
        let mut png = Vec::new();
        image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 200, 0, 100]))
            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
            .unwrap();
        let assets = crate::assets::Memory::new().with("leaf.png", png);
        let file = chunk(MAIN, &chunk(EDITOR, &editor));
        let doc = crate::formats::load_bytes(&file, "l.3ds", "3ds", &assets, Keep::ALL).unwrap();
        let leaf = &doc.json()["materials"][0];
        assert!(leaf["pbrMetallicRoughness"]["baseColorTexture"].is_object(), "{leaf}");
        assert_eq!(leaf["alphaMode"], "BLEND", "{leaf}");
    }

    /// A PNG of `w` × `h` RGB pixels made by `f`.
    fn rgb_png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 3]) -> Vec<u8> {
        let mut png = Vec::new();
        image::RgbImage::from_fn(w, h, |x, y| image::Rgb(f(x, y)))
            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
            .unwrap();
        png
    }

    /// A tangent-space normal map's pixels: bumps leaning every way around +Z.
    fn bumps(x: u32, y: u32) -> [u8; 3] {
        #[allow(clippy::cast_precision_loss, reason = "small test values")]
        let (a, b) = ((x as f32 * 0.7).sin() * 0.4, (y as f32 * 0.9).cos() * 0.4);
        let z = (1.0 - a * a - b * b).sqrt();
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "0 to 255")]
        [a, b, z].map(|c| ((c + 1.0) * 127.5).round() as u8)
    }

    /// The start of a JPEG: its markers up to a baseline frame header with `components`.
    fn jpeg(components: u8) -> Vec<u8> {
        let mut j = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 16];
        j.extend(b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0");
        j.extend([0xFF, 0xFF, 0xC0, 0, 8 + 3 * components, 8, 0, 4, 0, 4, components]);
        for c in 0..components {
            j.extend([c + 1, 0x11, 0]);
        }
        j
    }

    /// A model of one textured triangle per material, each material only a bump map (`file`, at `percent`).
    fn bumped(maps: &[(&str, &str, Option<u16>)]) -> Vec<u8> {
        let mut editor = Vec::new();
        let mut t = trimesh(&at([0.; 3]), &[], None);
        let mut faces = u16::try_from(maps.len()).unwrap().to_le_bytes().to_vec();
        for _ in maps {
            faces.extend(u16s(&[0, 1, 2, 0]));
        }
        for (i, (name, file, percent)) in maps.iter().enumerate() {
            let mut mat = chunk(MAT_NAME, format!("{name}\0").as_bytes());
            let mut map = chunk(MAP_FILE, format!("{file}\0").as_bytes());
            if let Some(p) = percent {
                map.extend(chunk(PERCENT_U16, &p.to_le_bytes()));
            }
            mat.extend(chunk(MAT_BUMPMAP, &map));
            editor.extend(chunk(MATERIAL, &mat));
            let mut fm = format!("{name}\0").into_bytes();
            fm.extend(u16s(&[1, u16::try_from(i).unwrap()]));
            faces.extend(chunk(FACE_MATERIAL, &fm));
        }
        let mut uv = 3u16.to_le_bytes().to_vec();
        uv.extend(f32s(&[0., 0., 1., 0., 0., 1.]));
        t.extend(chunk(UVS, &uv));
        t.extend(chunk(FACES, &faces));
        editor.extend(object("Wall", &chunk(TRIMESH, &t)));
        chunk(MAIN, &chunk(EDITOR, &editor))
    }

    #[test]
    fn a_bump_map_is_the_normal_map_when_its_image_is_one() {
        // Whether this build reads a PNG's pixels.
        let decodes = cfg!(any(
            feature = "webp",
            feature = "skp",
            feature = "tga",
            feature = "bmp",
            feature = "gif",
            feature = "tiff",
            feature = "psd",
            feature = "dds"
        ));
        let mut gray = Vec::new();
        image::GrayImage::from_fn(8, 8, |x, y| image::Luma([u8::try_from(x * 30 + y).unwrap()]))
            .write_to(&mut std::io::Cursor::new(&mut gray), image::ImageFormat::Png)
            .unwrap();
        let assets = crate::assets::Memory::new()
            .with("bricks.png", rgb_png(40, 30, bumps))
            .with(
                "height.png",
                rgb_png(40, 30, |x, y| [u8::try_from((x * 6 + y) % 256).unwrap(); 3]),
            )
            .with("gray_normal.png", gray)
            .with("wall_n.jpg", jpeg(3))
            .with("rough.jpg", jpeg(3))
            .with("mono_nrm.jpg", jpeg(1));
        let file = bumped(&[
            ("Pixels", "bricks.png", Some(50)),
            ("Height", "height.png", None),
            ("Gray", "gray_normal.png", None),
            ("Named", "maps\\wall_n.jpg", None),
            ("Plain", "rough.jpg", None),
            ("Mono", "mono_nrm.jpg", None),
            ("Missing", "gone_normal.png", None),
        ]);
        let doc = crate::formats::load_bytes(&file, "b.3ds", "3ds", &assets, Keep::ALL).unwrap();
        let normal = |name: &str| {
            let m = doc.json()["materials"]
                .as_array()
                .unwrap()
                .iter()
                .find(|m| m["name"] == name)
                .unwrap();
            // Every bump map stays in extras.
            assert!(m["extras"]["3ds"]["maps"]["bump"]["file"].is_string(), "{m}");
            m.get("normalTexture").cloned()
        };
        let pixels = normal("Pixels");
        assert_eq!(pixels.is_some(), decodes);
        if decodes {
            assert_eq!(pixels.unwrap()["scale"], json!(0.5));
        }
        assert!(normal("Height").is_none());
        assert!(normal("Gray").is_none());
        assert_eq!(normal("Named").unwrap().get("scale"), None);
        assert!(normal("Plain").is_none());
        assert!(normal("Mono").is_none());
        assert!(normal("Missing").is_none());
        let mesh = doc.flatten(Pose::Rest).unwrap().unwrap();
        assert_eq!(
            mesh.materials.iter().filter(|m| m.normal_image.is_some()).count(),
            1 + usize::from(decodes)
        );

        // Images cut short or damaged: never a panic.
        let png = rgb_png(40, 30, bumps);
        for len in (0..png.len()).step_by(3) {
            let mut bad = png.clone();
            bad.truncate(len);
            let assets = crate::assets::Memory::new().with("bricks.png", bad);
            let file = bumped(&[("Pixels", "bricks.png", None)]);
            let _ = crate::formats::load_bytes(&file, "b.3ds", "3ds", &assets, Keep::ALL);
        }
        let mut flipped = png;
        for i in (8..flipped.len()).step_by(5) {
            flipped[i] ^= 0x5A;
        }
        let assets = crate::assets::Memory::new().with("bricks.png", flipped);
        let file = bumped(&[("Pixels", "bricks.png", None)]);
        let _ = crate::formats::load_bytes(&file, "b.3ds", "3ds", &assets, Keep::ALL);
        for len in 0..file.len() {
            let _ = crate::formats::load_bytes(&file[..len], "b.3ds", "3ds", &assets, Keep::ALL);
        }
    }

    #[test]
    fn normal_maps_by_pixels_header_and_name() {
        let flat = vec![[128, 128, 255]; 10];
        assert!(normal_pixels(&flat));
        let mut some_gray = flat.clone();
        some_gray.extend([[200, 200, 200]; 3]);
        assert!(normal_pixels(&some_gray));
        assert!(!normal_pixels(&[[201, 201, 201]; 10]));
        assert!(!normal_pixels(&[[54, 54, 54]; 10]));
        assert!(!normal_pixels(&[[40, 40, 255]; 10]));
        assert!(!normal_pixels(&[]));
        assert_eq!(jpeg_components(&jpeg(1)), Some(1));
        assert_eq!(jpeg_components(&jpeg(3)), Some(3));
        let j = jpeg(3);
        for len in 0..j.len() {
            let _ = jpeg_components(&j[..len]);
        }
        assert_eq!(jpeg_components(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]), None);
        for name in [
            "brick_n.png",
            "Brick_Normal.tga",
            "C:\\maps\\wall_NRM.jpg",
            "rock-n.png",
            "x_ddn.tga",
            "a_nor.png",
        ] {
            assert!(named_normal_map(name), "{name}");
        }
        for name in ["bump.png", "brick_b.jpg", "n.png", "normalmaps/brick.png", "tin.png"] {
            assert!(!named_normal_map(name), "{name}");
        }
    }

    #[test]
    fn not_3ds_is_refused() {
        assert!(read("x.3ds", b"hello").is_err());
    }

    #[test]
    fn a_spotlight_with_nan_cones_is_read_not_a_panic() {
        let mut spot = f32s(&[0., 0., 10.]);
        spot.extend(chunk(DL_SPOTLIGHT, &f32s(&[0., 0., 0., f32::NAN, f32::NAN])));
        let mut editor = object("Tri", &chunk(TRIMESH, &trimesh(&at([0.; 3]), &[[0, 1, 2]], None)));
        editor.extend(object("Spot", &chunk(LIGHT, &spot)));
        let doc = read("nan.3ds", &chunk(MAIN, &chunk(EDITOR, &editor))).unwrap();
        let cone = &doc.json()["extensions"]["KHR_lights_punctual"]["lights"][0]["spot"];
        let outer = cone["outerConeAngle"].as_f64().unwrap();
        let inner = cone["innerConeAngle"].as_f64().unwrap();
        assert!((outer - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{cone}");
        assert!(inner < outer, "{cone}");
    }

    #[test]
    fn counts_and_lengths_past_the_end_take_only_what_is_there() {
        // Vertex, UV and face counts of 65535 over a few records, and a chunk claiming 4 GiB.
        let mut verts = u16s(&[u16::MAX]);
        verts.extend(f32s(&[0., 0., 0., 1., 0., 0., 0., 1., 0., 9.]));
        let mut uvs = u16s(&[u16::MAX]);
        uvs.extend(f32s(&[0., 0., 1.]));
        let mut tri = chunk(VERTICES, &verts);
        tri.extend(chunk(UVS, &uvs));
        tri.extend(chunk(FACES, &u16s(&[u16::MAX, 0, 1, 2, 0, 7])));
        let t = super::trimesh(&tri);
        assert_eq!((t.vertices.len(), t.uvs.len(), t.faces.len()), (3, 1, 1));
        // A face material list counting 65535 faces over one.
        let mut faces = u16s(&[1, 0, 1, 2, 0]);
        let mut fm = b"M\0".to_vec();
        fm.extend(u16s(&[u16::MAX, 0]));
        faces.extend(chunk(FACE_MATERIAL, &fm));
        let t = super::trimesh(&chunk(FACES, &faces));
        assert_eq!(t.materials, [("M".to_owned(), vec![0])]);
        let mut file = chunk(MAIN, &[]);
        file.extend([0x00, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 1, 2, 3]);
        let all: Vec<_> = chunks(&file).collect();
        assert_eq!(all, [(MAIN, &[][..]), (0x4000, &[1, 2, 3][..])]);
        assert_eq!(jpeg_components(&[0xFF, 0xD8, 0xFF, 0xE0, 0xFF, 0xFF]), None);
    }
}