threers 0.0.7

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
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
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
#![allow(dead_code)]
// Every type here is constructed from JavaScript through
// `#[wasm_bindgen(constructor)]`, which is what `new()` is for. A `Default`
// impl would be unreachable from that side and meaningless on this one, so the
// bindings are exempt rather than carrying two dozen impls nobody calls.
#![allow(clippy::new_without_default)]
// The JS side has no keyword arguments and no struct literals, so a binding
// that configures a dozen things takes a dozen positional parameters. Bundling
// them into a Rust struct would only move the problem: the shim would have to
// unpack it again on the way in.
#![allow(clippy::too_many_arguments)]
//! The [`web/threejs-shim.js`](../../web/threejs-shim.js) companion maps these
//! types onto three.js r165-style `THREE.*` symbols so existing examples can run
//! against wasm/WebGPU with minimal changes.
//!
//! Bindings cover the renderer, scene graph, geometries, materials, lights,
//! textures, controls, loaders, post-processing passes, PMREM, and helpers.
//! Gaps shrink over time — see `tests/parity/` for coverage tracking.

use std::sync::Arc;
use wasm_bindgen::prelude::*;

use crate::core::ObjectId;

// Bindings that live in their own files under `src/wasm/`: shapes, paths,
// extrusion and text; the other geometry generators; the exporters; and
// helpers, loaders and noise. Child modules, so they see these types' fields.
// TransformControls, FlyControls, MapControls' screen-space panning.
mod controls;
// The shim's Curve classes (three.js r165 curves, arc length, Frenet frames).
mod curves;
// AnimationClip, KeyframeTracks, Interpolants, AnimationMixer and its actions,
// AnimationObjectGroup: three.js r165's animation system, run in Rust.
mod animation;
mod exporters;
mod extras;
mod generators;
// GLTFLoader: the three.js r165 parser in `crate::loaders::gltf`, building the
// scene graph's nodes directly; the shim wraps them.
mod gltf;
// Scene data behind the shim's Box3 / Sphere / Frustum: geometry and vertex bounds.
mod math;
mod mesh_state;
// The shim's scene-graph mirror: nodes, structure, raycasting, DragControls.
mod scene_graph;
mod shapes;
// Post-processing: the composer and its passes.
mod postfx;
pub use postfx::{WebEffectComposer, WebPass};

/// Top-level WebGPU renderer bound to a canvas element. The constructor is
/// async because adapter/device acquisition is async on the web.
#[wasm_bindgen]
pub struct WebRenderer {
    renderer: crate::Renderer,
    surface: wgpu::Surface<'static>,
    config: wgpu::SurfaceConfiguration,
    device: Arc<wgpu::Device>,
    width: u32,
    height: u32,
    // When non-null, render() draws into this render target instead of the surface.
    current_target_id: Option<u32>,
    /// True on wgpu's WebGL2 backend. See [`WebRenderer::gl_back_buffer`].
    is_gl: bool,
    /// Set once a page uses viewport / scissor / auto-clear off / `clear()` on
    /// the canvas; from then on canvas draws on WebGL2 go through `gl_back`.
    multi_view: bool,
    /// Canvas-sized offscreen colour buffer that WebGL2 canvas draws accumulate
    /// in, copied to the canvas after each draw.
    gl_back: Option<(u32, Arc<crate::renderer::RenderTarget>)>,
}

// Thread-local registry mapping render-target IDs to live Arcs. We use this
// to look up the target from setRenderTarget() because wasm-bindgen's
// `Option<&WebRenderTarget>` can't safely hold an Arc across the JS boundary.
thread_local! {
    static ACTIVE_TARGETS: std::cell::RefCell<std::collections::HashMap<u32, std::sync::Arc<crate::renderer::RenderTarget>>>
        = std::cell::RefCell::new(std::collections::HashMap::new());
    static ACTIVE_CUBE_TARGETS: std::cell::RefCell<std::collections::HashMap<u32, std::sync::Arc<crate::renderer::CubeRenderTarget>>>
        = std::cell::RefCell::new(std::collections::HashMap::new());
    // Targets reallocated by `setSize` since the last render: the renderer's
    // sample views of them are stale until registered again.
    static RESIZED_TARGETS: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
}

/// GPU readback of a render-target region into a tight byte vec.
/// Hand control back to the browser for one turn of the event loop.
async fn yield_to_event_loop() {
    if let Some(window) = web_sys::window() {
        let promise = js_sys::Promise::new(&mut |resolve, _reject| {
            let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, 0);
        });
        let _ = wasm_bindgen_futures::JsFuture::from(promise).await;
    }
}

/// Wait for a buffer mapping to complete without blocking the event loop.
///
/// `PollType::wait_indefinitely()` blocks the calling thread, and in a browser
/// that is the same thread which would deliver the mapping callback — so the
/// wait can never end. It went unnoticed because WebGPU's wgpu backend makes
/// `poll` a no-op and resolves the mapping through a JS promise; on the WebGL2
/// backend, which goes through wgpu-core, polling really does wait and a
/// read-back hung the page.
///
/// So: poll without blocking, yield, and let the browser deliver the callback.
/// The cap is a liveness bound rather than a deadline — it is set well past any
/// plausible read-back so that a loaded machine cannot turn a slow frame into a
/// spurious failure, while a mapping that genuinely never completes still ends.
async fn await_buffer_mapping(
    device: &wgpu::Device,
    mut rx: futures_channel::oneshot::Receiver<Result<(), wgpu::BufferAsyncError>>,
) -> Result<(), String> {
    for _ in 0..20_000 {
        let _ = device.poll(wgpu::PollType::Poll);
        if let Ok(Some(res)) = rx.try_recv() {
            return res.map_err(|e| format!("buffer map failed: {e:?}"));
        }
        yield_to_event_loop().await;
    }
    Err("buffer mapping never completed".to_string())
}

async fn read_texture_region(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    texture: &wgpu::Texture,
    format: wgpu::TextureFormat,
    x: u32,
    y: u32,
    w: u32,
    h: u32,
) -> Result<Vec<u8>, String> {
    let bytes_per_pixel = match format {
        wgpu::TextureFormat::Rgba16Float => 8u32,
        _ => 4u32,
    };
    const ALIGN: u32 = 256;
    let unpadded = w * bytes_per_pixel;
    let padded = unpadded.div_ceil(ALIGN) * ALIGN;
    let buf_size = (padded * h) as u64;
    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("threers readback buffer sync"),
        size: buf_size,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });
    {
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("threers readback encoder sync"),
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d { x, y, z: 0 },
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(padded),
                    rows_per_image: Some(h),
                },
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(std::iter::once(encoder.finish()));
    }
    let buffer_slice = buffer.slice(..);
    let (tx, rx) = futures_channel::oneshot::channel();
    buffer_slice.map_async(wgpu::MapMode::Read, move |res| {
        let _ = tx.send(res);
    });
    await_buffer_mapping(device, rx).await?;
    let mapped = buffer_slice
        .get_mapped_range()
        .expect("buffer range is mapped");
    let mut out = Vec::with_capacity((w * h * bytes_per_pixel) as usize);
    for row in 0..h {
        let start = (row * padded) as usize;
        let end = start + (unpadded as usize);
        out.extend_from_slice(&mapped[start..end]);
    }
    drop(mapped);
    buffer.unmap();
    Ok(out)
}

fn postfx_camera_from(
    near: f32,
    far: f32,
    kernel_radius: f32,
    kernel_size: u32,
    proj: &[f32],
    inv_proj: &[f32],
) -> crate::renderer::PostFxCamera {
    let mut id = [0f32; 16];
    id[0] = 1.0;
    id[5] = 1.0;
    id[10] = 1.0;
    id[15] = 1.0;
    let mut p = id;
    let mut ip = id;
    if proj.len() >= 16 {
        p.copy_from_slice(&proj[..16]);
    }
    if inv_proj.len() >= 16 {
        ip.copy_from_slice(&inv_proj[..16]);
    }
    crate::renderer::PostFxCamera {
        near,
        far,
        kernel_radius,
        kernel_size,
        proj: p,
        inv_proj: ip,
    }
}

// Owns an offscreen render target. Reference-counted via Arc so multiple
// places (renderer + materials sampling the texture) can share it.
#[wasm_bindgen]
pub struct WebRenderTarget {
    pub(crate) inner: std::sync::Arc<crate::renderer::RenderTarget>,
    pub width: u32,
    pub height: u32,
    pub id: u32,
}

// A 6-face cube render target. Used by CubeCamera + scene.environment.
#[wasm_bindgen]
pub struct WebCubeRenderTarget {
    pub(crate) inner: std::sync::Arc<crate::renderer::CubeRenderTarget>,
    pub side: u32,
    pub id: u32,
}

#[wasm_bindgen]
impl WebCubeRenderTarget {
    #[wasm_bindgen(constructor)]
    pub fn new(renderer: &WebRenderer, side: u32) -> WebCubeRenderTarget {
        let rt =
            crate::renderer::RenderTarget::new_cube(&renderer.device, side, renderer.config.format);
        let arc = std::sync::Arc::new(rt);
        let id = NEXT_RT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        // Register so scene.environment_cube_rt can find this RT at render time.
        ACTIVE_CUBE_TARGETS.with(|m| m.borrow_mut().insert(id, arc.clone()));
        WebCubeRenderTarget {
            inner: arc,
            side,
            id,
        }
    }
}

static NEXT_RT_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);

// Reuse one WebGPU device/queue across renderer instances in the same tab.
// `requestAdapter` + `requestDevice` dominate cold-start cost; surfaces stay
// per-canvas. Thread-local because wasm's main thread is single-threaded and
// `wgpu::Device` is not `Sync`.
#[cfg(target_arch = "wasm32")]
thread_local! {
    static SHARED_BROWSER_GPU: std::cell::RefCell<Option<(Arc<wgpu::Device>, Arc<wgpu::Queue>)>> =
        const { std::cell::RefCell::new(None) };
    /// The instance every renderer in this tab shares.
    ///
    /// A `wgpu::Device` belongs to the instance that created it, so pairing a
    /// cached device with a surface from a *different* instance is invalid — it
    /// shows up as `Cannot get non-existent resource DeviceId`, which says
    /// nothing about the cause. The device is cached below and the backend
    /// discovery makes a fresh instance per attempt, so the instance that won
    /// has to be kept alongside it.
    static SHARED_BROWSER_INSTANCE: std::cell::RefCell<Option<wgpu::Instance>> =
        const { std::cell::RefCell::new(None) };
    /// Which backend the adapter turned out to be, for [`WebRenderer::backend`].
    ///
    /// Worth surfacing rather than inferring: on WebGL2 several effects switch
    /// themselves off, and without a way to ask, the only symptom is that bloom
    /// and ambient occlusion quietly do nothing.
    static SHARED_BROWSER_BACKEND: std::cell::RefCell<Option<wgpu::Backend>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(target_arch = "wasm32")]
/// Open a GPU context on `canvas`, preferring WebGPU and falling back to WebGL2.
///
/// Two things here are forced by the browser rather than chosen.
///
/// **One instance per backend.** On wasm, `wgpu::Instance::new` commits to a
/// single context implementation: ask for `BROWSER_WEBGPU` and you get the
/// WebGPU one, which contains no GL whatever the Cargo features say. So
/// `BROWSER_WEBGPU | GL` does not mean "try both" — it means WebGPU, and on a
/// browser without it the adapter request fails claiming
/// `gl support not compiled in`, which is not what has gone wrong.
///
/// **The canvas is not touched until a backend is settled.** A canvas hands out
/// exactly one kind of context for its whole life: once `getContext("webgpu")`
/// has been called, `getContext("webgl2")` on that same canvas returns null
/// forever. Creating a surface to test WebGPU therefore destroys the fallback it
/// was testing for — the GL attempt then fails with `canvas already in use`.
/// WebGPU can enumerate adapters with no surface at all, so it is asked first
/// and the surface is created only once an adapter has answered.
pub async fn open_browser_gpu(
    canvas: &web_sys::HtmlCanvasElement,
) -> Result<(wgpu::Instance, wgpu::Surface<'static>, wgpu::Adapter), JsValue> {
    // A second canvas reuses the instance that already won — but only on
    // WebGPU, where an adapter is not tied to a canvas.
    //
    // On WebGL2 it cannot: a WebGL2 context *belongs* to its canvas, so an
    // instance that has already made a surface for one canvas cannot serve
    // another. Reusing it gets as far as `Surface::configure` and fails there
    // with `Surface does not support the adapter's queue family`, which does not
    // mention canvases at all. So on that backend every canvas gets its own
    // instance, surface and device, and the sharing below is skipped.
    let shareable = !matches!(
        SHARED_BROWSER_BACKEND.with(|b| *b.borrow()),
        Some(wgpu::Backend::Gl)
    );
    if let Some(instance) =
        SHARED_BROWSER_INSTANCE.with(|i| if shareable { i.borrow().clone() } else { None })
    {
        let surface = instance
            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
            .map_err(|e| JsValue::from_str(&format!("surface: {e:?}")))?;
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::default(),
                compatible_surface: Some(&surface),
                force_fallback_adapter: false,
                apply_limit_buckets: false,
            })
            .await
            .map_err(|e| JsValue::from_str(&format!("no adapter: {e}")))?;
        return Ok((instance, surface, adapter));
    }

    let already = SHARED_BROWSER_BACKEND.with(|b| *b.borrow());
    let mut why = String::new();

    if !matches!(already, Some(wgpu::Backend::Gl)) {
        // wgpu 30 dropped `Default` here; the display handle is only consulted
        // by GLES/Wayland, not Vulkan, Metal or DX12.
        let mut d = wgpu::InstanceDescriptor::new_without_display_handle();
        d.backends = wgpu::Backends::BROWSER_WEBGPU;
        let instance = wgpu::Instance::new(d);
        match instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::default(),
                compatible_surface: None,
                force_fallback_adapter: false,
                apply_limit_buckets: false,
            })
            .await
        {
            Ok(adapter) => {
                let surface = instance
                    .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
                    .map_err(|e| JsValue::from_str(&format!("webgpu surface: {e:?}")))?;
                SHARED_BROWSER_BACKEND.with(|b| *b.borrow_mut() = Some(adapter.get_info().backend));
                SHARED_BROWSER_INSTANCE.with(|i| *i.borrow_mut() = Some(instance.clone()));
                return Ok((instance, surface, adapter));
            }
            Err(e) => why = format!("webgpu: {e}"),
        }
    }

    if cfg!(feature = "webgl") && !matches!(already, Some(wgpu::Backend::BrowserWebGpu)) {
        let mut d = wgpu::InstanceDescriptor::new_without_display_handle();
        d.backends = wgpu::Backends::GL;
        let instance = wgpu::Instance::new(d);
        // GL is the other way round: a WebGL2 context *is* the canvas, so the
        // surface has to exist before there is an adapter to ask about.
        let surface = instance
            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
            .map_err(|e| JsValue::from_str(&format!("{why}; webgl2 surface: {e:?}")))?;
        match instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::default(),
                compatible_surface: Some(&surface),
                force_fallback_adapter: false,
                apply_limit_buckets: false,
            })
            .await
        {
            Ok(adapter) => {
                // Deliberately not cached: see the note above about WebGL2
                // contexts belonging to their canvas.
                SHARED_BROWSER_BACKEND.with(|b| *b.borrow_mut() = Some(adapter.get_info().backend));
                return Ok((instance, surface, adapter));
            }
            Err(e) => why = format!("{why}; webgl2: {e}"),
        }
    }

    Err(JsValue::from_str(&format!("no adapter: {why}")))
}

#[cfg(target_arch = "wasm32")]
async fn acquire_browser_gpu(
    adapter: &wgpu::Adapter,
) -> Result<(Arc<wgpu::Device>, Arc<wgpu::Queue>), JsValue> {
    // Shared across canvases on WebGPU, where `requestAdapter` + `requestDevice`
    // dominate cold start. Not on WebGL2: the device belongs to an instance that
    // belongs to a canvas, so each canvas pays for its own.
    let shareable = adapter.get_info().backend != wgpu::Backend::Gl;
    if shareable {
        if let Some(pair) = SHARED_BROWSER_GPU.with(|g| g.borrow().clone()) {
            return Ok(pair);
        }
    }

    // Request what the adapter actually offers rather than a floor.
    //
    // `downlevel_webgl2_defaults` allows 16 sampled textures per shader stage,
    // and the standard fragment layout — material maps, shadow maps, the
    // environment cube, and the screen-space capture — needs more than that once
    // a scene uses shadows or glass. WebGPU rejects the pipeline for exceeding
    // the limit, and it does so *asynchronously*: nothing throws, no call fails,
    // the pipeline simply never draws. What that looks like from the outside is
    // a black canvas at a full frame rate, which is a great deal harder to
    // diagnose than an error would have been.
    let (device, queue) = adapter
        .request_device(&wgpu::DeviceDescriptor {
            label: Some("threers device"),
            required_features: wgpu::Features::empty(),
            required_limits: adapter.limits(),
            ..Default::default()
        })
        .await
        .map_err(|e| JsValue::from_str(&format!("device: {e:?}")))?;
    crate::gpu::report_uncaptured_errors(&device, "threers");

    let pair = (Arc::new(device), Arc::new(queue));
    if shareable {
        SHARED_BROWSER_GPU.with(|g| *g.borrow_mut() = Some(pair.clone()));
    }
    Ok(pair)
}

#[wasm_bindgen]
impl WebRenderTarget {
    #[wasm_bindgen(constructor)]
    pub fn new(renderer: &WebRenderer, width: u32, height: u32) -> WebRenderTarget {
        Self::alloc(renderer, width, height, renderer.config.format)
    }

    /// Half-float color RT for outline intermediates (matches three.js OutlinePass).
    #[wasm_bindgen(js_name = newHalfFloat)]
    pub fn new_half_float(renderer: &WebRenderer, width: u32, height: u32) -> WebRenderTarget {
        Self::alloc(renderer, width, height, wgpu::TextureFormat::Rgba16Float)
    }

    fn alloc(
        renderer: &WebRenderer,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
    ) -> WebRenderTarget {
        let rt = crate::renderer::RenderTarget::new(&renderer.device, width, height, format);
        // `readRenderTargetPixels` here returns what the target stores — the
        // encoded picture — unless told the target is linear: the three.js
        // layer sets each target's `texture.colorSpace` before reading.
        rt.set_srgb_color_space(true);
        let arc = std::sync::Arc::new(rt);
        let id = NEXT_RT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        ACTIVE_TARGETS.with(|m| m.borrow_mut().insert(id, arc.clone()));
        WebRenderTarget {
            inner: arc,
            width,
            height,
            id,
        }
    }

    /// three.js `renderTarget.setSize(width, height)`: reallocate at the new
    /// size, keeping the id — so every texture made from this target, and every
    /// material sampling it, carries on with the resized one — and its colour
    /// space. The contents start cleared, as three.js's do.
    #[wasm_bindgen(js_name = setSize)]
    pub fn set_size(&mut self, width: u32, height: u32) {
        let (width, height) = (width.max(1), height.max(1));
        if (width, height) == (self.width, self.height) {
            return;
        }
        self.inner = std::sync::Arc::new(self.inner.resized(width, height));
        (self.width, self.height) = (width, height);
        ACTIVE_TARGETS.with(|m| m.borrow_mut().insert(self.id, self.inner.clone()));
        RESIZED_TARGETS.with(|r| r.borrow_mut().push(self.id));
    }

    /// three.js `renderTarget.texture.colorSpace`: `true` for `SRGBColorSpace`,
    /// whose read-back is sRGB-encoded (this API's default, the stored
    /// bytes); `false` for three.js's default `NoColorSpace`, which reads back
    /// linear. See `RenderTarget::srgb_color_space`.
    #[wasm_bindgen(js_name = setSrgbColorSpace)]
    pub fn set_srgb_color_space(&self, srgb: bool) {
        self.inner.set_srgb_color_space(srgb);
    }

    /// three.js `renderTarget.samples`: above 1, drawn multisampled and
    /// resolved, colour and depth (see `RenderTarget::samples`). A half-float
    /// target stays single-sampled.
    #[wasm_bindgen(js_name = setSamples)]
    pub fn set_samples(&self, samples: u32) {
        self.inner.set_samples(samples);
    }

    #[wasm_bindgen(getter)]
    pub fn samples(&self) -> u32 {
        self.inner.samples()
    }
}

/// Prefer alpha compositing modes that preserve a transparent canvas.
fn pick_surface_alpha_mode(modes: &[wgpu::CompositeAlphaMode]) -> wgpu::CompositeAlphaMode {
    for preferred in [
        wgpu::CompositeAlphaMode::PreMultiplied,
        wgpu::CompositeAlphaMode::PostMultiplied,
        wgpu::CompositeAlphaMode::Inherit,
        wgpu::CompositeAlphaMode::Auto,
    ] {
        if modes.contains(&preferred) {
            return preferred;
        }
    }
    modes[0]
}

/// Forward `log` records to the browser console.
///
/// Without this, wgpu is silent in a browser: it reports a rejected pipeline
/// or a failed surface configuration through `log::error!`, and with no
/// logger installed those records go nowhere. The symptom is a canvas that
/// stays blank while the frame loop runs at sixty — which is indistinguishable
/// from a slow start until you can see the error.
///
/// Hand-rolled rather than `console_log`, which is a dependency for twenty
/// lines, and `web-sys`'s `console` is already here for the panic hook.
struct ConsoleLogger;

impl log::Log for ConsoleLogger {
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        metadata.level() <= log::Level::Warn
    }

    fn log(&self, record: &log::Record) {
        if !self.enabled(record.metadata()) {
            return;
        }
        let line = format!(
            "[{}] {}: {}",
            record.level(),
            record.target(),
            record.args()
        );
        let msg = wasm_bindgen::JsValue::from_str(&line);
        match record.level() {
            log::Level::Error => web_sys::console::error_1(&msg),
            _ => web_sys::console::warn_1(&msg),
        }
    }

    fn flush(&self) {}
}

/// Install [`ConsoleLogger`], once. Safe to call from every entry point.
pub fn install_console_logger() {
    use std::sync::Once;
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        // `set_logger` only fails if one is already installed, which is a
        // host that wanted its own — leave theirs alone.
        if log::set_logger(&ConsoleLogger).is_ok() {
            log::set_max_level(log::LevelFilter::Warn);
        }
    });
}

#[wasm_bindgen]
impl WebRenderer {
    /// Async factory. Pass an HTMLCanvasElement and the renderer attaches to it.
    pub async fn new(canvas: web_sys::HtmlCanvasElement) -> Result<WebRenderer, JsValue> {
        console_error_panic_hook::set_once();
        install_console_logger();

        let width = canvas.width().max(1);
        let height = canvas.height().max(1);

        // The instance is not kept: `Surface` and `Device` hold their own handles
        // to the context, and the WebGPU instance that wins is cached in
        // `SHARED_BROWSER_INSTANCE` for the next canvas. Bound rather than
        // discarded so it outlives the device creation below.
        let (_instance, surface, adapter) = open_browser_gpu(&canvas).await?;
        let (device, queue) = acquire_browser_gpu(&adapter).await?;

        let surface_caps = surface.get_capabilities(&adapter);
        let surface_format = surface_caps
            .formats
            .iter()
            .copied()
            .find(|f| f.is_srgb())
            .unwrap_or(surface_caps.formats[0]);
        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width,
            height,
            present_mode: wgpu::PresentMode::Fifo,
            alpha_mode: pick_surface_alpha_mode(&surface_caps.alpha_modes),
            view_formats: vec![],
            desired_maximum_frame_latency: 2,
            color_space: wgpu::SurfaceColorSpace::Srgb,
        };
        surface.configure(&device, &config);

        let renderer =
            crate::Renderer::new(device.clone(), queue.clone(), surface_format, width, height);
        // Continue construction below — see existing return statement.

        Ok(WebRenderer {
            renderer,
            surface,
            config,
            device,
            width,
            height,
            current_target_id: None,
            is_gl: adapter.get_info().backend == wgpu::Backend::Gl,
            multi_view: false,
            gl_back: None,
        })
    }

    #[wasm_bindgen(js_name = setSize)]
    pub fn set_size(&mut self, w: u32, h: u32) {
        self.width = w.max(1);
        self.height = h.max(1);
        self.config.width = self.width;
        self.config.height = self.height;
        self.surface.configure(&self.device, &self.config);
        self.renderer.resize(self.width, self.height);
        self.gl_back = None;
    }

    /// Enable hardware MSAA on the direct-to-canvas pass. `samples <= 1` = off,
    /// else 4×. Only the opaque forward pass is multisampled — render targets,
    /// shadows, and glass/OIT/refraction scenes stay single-sampled.
    /// three.js `renderer.toneMapping` / `renderer.toneMappingExposure`.
    ///
    /// Takes three.js's numeric constants: `0` NoToneMapping, `1` Linear,
    /// `4` ACESFilmic. Anything else falls back to linear, which is closer to
    /// the intent than clipping.
    #[wasm_bindgen(js_name = setToneMapping)]
    pub fn set_tone_mapping(&mut self, mode: u32, exposure: f32) {
        // three.js's constants: 0 NoToneMapping, 1 Linear, 4 ACESFilmic,
        // 6 AgX, 7 Neutral. 2 (Reinhard) and 3 (Cineon) have no curve here and
        // fall through to linear, as they always have.
        let mapping = match mode {
            0 => crate::ToneMapping::None,
            4 => crate::ToneMapping::AcesFilmic,
            6 => crate::ToneMapping::AgX,
            7 => crate::ToneMapping::Neutral,
            _ => crate::ToneMapping::Linear,
        };
        self.renderer.set_tone_mapping(mapping, exposure);
    }

    /// Reversed depth for the view — see
    /// [`Renderer::set_reversed_z`](crate::Renderer::set_reversed_z). For a
    /// globe or anything spanning kilometres with a near plane of metres; off
    /// by default.
    #[wasm_bindgen(js_name = setReversedZ)]
    pub fn set_reversed_z(&mut self, on: bool) {
        self.renderer.set_reversed_z(on);
    }

    /// Geometric specular antialiasing on Standard and Physical materials, in
    /// place of three.js's `geometryRoughness` — see
    /// [`Renderer::set_specular_antialiasing`](crate::Renderer::set_specular_antialiasing).
    /// Off by default, as three.js renders.
    #[wasm_bindgen(js_name = setSpecularAntialiasing)]
    pub fn set_specular_antialiasing(&mut self, on: bool) {
        self.renderer.set_specular_antialiasing(on);
    }

    /// threers's reflective transparency on Standard and Physical — see
    /// [`Renderer::set_reflective_transparency`](crate::Renderer::set_reflective_transparency).
    /// Off by default, as three.js renders.
    #[wasm_bindgen(js_name = setReflectiveTransparency)]
    pub fn set_reflective_transparency(&mut self, on: bool) {
        self.renderer.set_reflective_transparency(on);
    }

    #[wasm_bindgen(js_name = setMsaa)]
    pub fn set_msaa(&mut self, samples: u32) {
        self.renderer.set_msaa(samples);
    }

    /// three.js `renderer.shadowMap.type`: 0 `BasicShadowMap`, 1
    /// `PCFShadowMap` (the default), 2 `PCFSoftShadowMap`, 3 `VSMShadowMap` —
    /// drawn here as percentage-closer soft shadows, whose edge softens with
    /// distance from the caster as a variance map's does.
    #[wasm_bindgen(js_name = setShadowType)]
    pub fn set_shadow_type(&mut self, kind: u32) {
        self.renderer.set_shadow_type(shadow_type_of(kind));
    }

    /// The filter `setShadowType` set, as three.js's number.
    #[wasm_bindgen(getter, js_name = shadowType)]
    pub fn shadow_type(&self) -> u32 {
        self.renderer.shadow_type().code()
    }

    /// How many layers overlapping refraction glass composites in
    /// (`Renderer::set_refraction_layers`).
    #[wasm_bindgen(js_name = setRefractionLayers)]
    pub fn set_refraction_layers(&mut self, layers: u32) {
        self.renderer.set_refraction_layers(layers as usize);
    }

    /// Whether the last render was multisampled — MSAA asked for is not
    /// always delivered (see `Renderer::last_frame_multisampled`).
    #[wasm_bindgen(getter, js_name = lastFrameMultisampled)]
    pub fn last_frame_multisampled(&self) -> bool {
        self.renderer.last_frame_multisampled()
    }

    /// three.js `renderer.shadowMap.autoUpdate`: on (default), every render
    /// redraws the shadow maps; off, only a render after
    /// `shadowMapNeedsUpdate = true` does. See `renderer::ShadowMap`.
    #[wasm_bindgen(getter, js_name = shadowMapAutoUpdate)]
    pub fn shadow_map_auto_update(&self) -> bool {
        self.renderer.shadow_map().auto_update
    }
    #[wasm_bindgen(setter, js_name = shadowMapAutoUpdate)]
    pub fn set_shadow_map_auto_update(&mut self, on: bool) {
        self.renderer.shadow_map_mut().auto_update = on;
    }

    /// three.js `renderer.shadowMap.needsUpdate`, consumed by the next render
    /// that draws the maps.
    #[wasm_bindgen(getter, js_name = shadowMapNeedsUpdate)]
    pub fn shadow_map_needs_update(&self) -> bool {
        self.renderer.shadow_map().needs_update
    }
    #[wasm_bindgen(setter, js_name = shadowMapNeedsUpdate)]
    pub fn set_shadow_map_needs_update(&mut self, on: bool) {
        self.renderer.shadow_map_mut().needs_update = on;
    }

    /// three.js `setViewport(x, y, width, height)`: bottom-left origin, in
    /// pixels scaled by `setPixelRatio`. See `Renderer::set_viewport`.
    #[wasm_bindgen(js_name = setViewport)]
    pub fn set_viewport(&mut self, x: f32, y: f32, width: f32, height: f32) {
        self.multi_view = true;
        self.renderer.set_viewport(x, y, width, height);
    }

    /// Back to the whole canvas (or render target).
    #[wasm_bindgen(js_name = resetViewport)]
    pub fn reset_viewport(&mut self) {
        self.renderer.reset_viewport();
    }

    /// three.js `setScissor(x, y, width, height)`; same coordinates as
    /// `setViewport`, used while `setScissorTest(true)`.
    #[wasm_bindgen(js_name = setScissor)]
    pub fn set_scissor(&mut self, x: f32, y: f32, width: f32, height: f32) {
        self.renderer.set_scissor(x, y, width, height);
    }

    /// three.js `setScissorTest`. On, each render clears and draws only inside
    /// the scissor — several renders per animation frame then share the canvas
    /// (on WebGPU the canvas texture is the same for the whole frame; on
    /// WebGL2 the draws accumulate in an offscreen buffer — see
    /// `gl_back_buffer`).
    #[wasm_bindgen(js_name = setScissorTest)]
    pub fn set_scissor_test(&mut self, enabled: bool) {
        self.multi_view |= enabled;
        self.renderer.set_scissor_test(enabled);
    }

    /// Scale for viewport/scissor rectangles only (three.js `setPixelRatio`);
    /// `setSize` still takes device pixels.
    #[wasm_bindgen(js_name = setPixelRatio)]
    pub fn set_pixel_ratio(&mut self, ratio: f32) {
        self.renderer.set_pixel_ratio(ratio);
    }

    /// three.js `autoClear`: false keeps the colour already on the canvas.
    #[wasm_bindgen(js_name = setAutoClear)]
    pub fn set_auto_clear(&mut self, enabled: bool) {
        self.multi_view |= !enabled;
        self.renderer.set_auto_clear(enabled);
    }

    /// three.js `renderer.clear()` for colour — the same colour handling as
    /// `scene.setBackground` — only inside the scissor while the scissor test
    /// is on. Clears the active render target if one is set.
    pub fn clear(&mut self, color: &WebColor, alpha: f32) {
        let color = color.inner;
        let alpha = alpha.clamp(0.0, 1.0);
        if let Some(id) = self.current_target_id {
            if let Some(target) = ACTIVE_TARGETS.with(|m| m.borrow().get(&id).cloned()) {
                self.renderer.clear_render_target(&target, color, alpha);
                return;
            }
        }
        // A clear on the canvas is a frame being composed by hand.
        self.multi_view = true;
        if let Some((id, back)) = self.gl_back_buffer() {
            self.renderer.clear_render_target(&back, color, alpha);
            self.present_gl_back_buffer(id);
            return;
        }
        match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(frame)
            | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
                let view = frame
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());
                self.renderer.clear(&view, false, color, alpha);
                self.renderer.queue_arc().present(frame);
            }
            _ => self.surface.configure(&self.device, &self.config),
        }
    }

    /// The offscreen buffer canvas draws go to on WebGL2 once a page composes
    /// frames from several draws (viewport, scissor test, auto-clear off, or
    /// `clear()` on the canvas); `None` otherwise, and always on WebGPU.
    ///
    /// Why: wgpu's GL backend hands out the canvas as a *new* texture on
    /// every acquire, tracked as uninitialised, so a render pass that loads
    /// it — a pane drawn after another pane — gets it zero-filled first and
    /// the earlier pane is lost. (Browser WebGPU has no such tracking: the
    /// canvas texture is the same object for the whole frame.) Drawing into
    /// a persistent target and copying it to the canvas after each draw keeps
    /// every pane. The copy is a fullscreen pass, sRGB in and out, so it is
    /// exact. With MSAA on, these draws go through the multisampled path
    /// (`render_back`), which resolves a pane through its own pane-sized
    /// target — so the panes keep their anti-aliasing here too.
    fn gl_back_buffer(&mut self) -> Option<(u32, Arc<crate::renderer::RenderTarget>)> {
        if !(self.is_gl && self.multi_view) {
            return None;
        }
        let stale = match &self.gl_back {
            None => true,
            Some((_, rt)) => rt.width != self.width || rt.height != self.height,
        };
        if stale {
            if let Some((old, _)) = self.gl_back.take() {
                ACTIVE_TARGETS.with(|m| m.borrow_mut().remove(&old));
            }
            let rt = Arc::new(crate::renderer::RenderTarget::new(
                &self.device,
                self.width,
                self.height,
                self.config.format,
            ));
            // It stands in for the canvas, so it is tone-mapped like one.
            rt.set_presents(true);
            let id = NEXT_RT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            ACTIVE_TARGETS.with(|m| m.borrow_mut().insert(id, rt.clone()));
            self.gl_back = Some((id, rt));
        }
        let (id, rt) = self.gl_back.as_ref()?;
        self.renderer.register_render_target(*id, rt);
        Some((*id, rt.clone()))
    }

    /// Copy the WebGL2 back buffer over the whole canvas and present it.
    fn present_gl_back_buffer(&mut self, back_id: u32) {
        let frame = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(f)
            | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
            _ => {
                self.surface.configure(&self.device, &self.config);
                return;
            }
        };
        let view = frame
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        let identity = [
            1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
        ];
        let camera = postfx_camera_from(0.1, 100.0, 0.5, 16, &identity, &identity);
        // Kind 0, the byte copy: the buffer and the canvas are both sRGB on
        // WebGL2, and the pass re-encodes what its raw view decodes and
        // decodes what the canvas encodes (`postfx_flag`), so the bytes
        // arrive as they were.
        self.renderer.apply_postfx_by_id(
            back_id,
            0,
            &view,
            0,
            0,
            0,
            0.0,
            [0.0; 4],
            [0.0; 4],
            self.width,
            self.height,
            false,
            camera,
        );
        self.renderer.queue_arc().present(frame);
    }

    /// Set the active render target by id. When non-zero, `render()` draws
    /// into the target's offscreen texture; pass 0 to restore canvas rendering.
    /// We pass the id (not the WebRenderTarget instance) so the JS-side
    /// wrapper isn't moved into Rust ownership and remains usable for
    /// subsequent calls like `readRenderTargetPixels`.
    #[wasm_bindgen(js_name = setRenderTarget)]
    pub fn set_render_target(&mut self, target_id: u32) {
        if target_id == 0 {
            // Just clear the active-target pointer; leave the RT in ACTIVE_TARGETS
            // so subsequent calls like applyPostFx and readRenderTargetPixels
            // can still find it by id.
            self.current_target_id = None;
            return;
        }
        if let Some(target) = ACTIVE_TARGETS.with(|m| m.borrow().get(&target_id).cloned()) {
            self.current_target_id = Some(target_id);
            self.renderer.register_render_target(target_id, &target);
        }
    }

    /// Build a Texture that samples from the given render target's color view.
    /// Used to chain post-processing passes: render scene into RT, then use
    /// that RT as a material map on a fullscreen quad mesh.
    #[wasm_bindgen(js_name = renderTargetTexture)]
    pub fn render_target_texture(&mut self, rt: &WebRenderTarget) -> WebTexture {
        // Make sure the renderer is aware of this RT's view (in case the user
        // calls renderTargetTexture before ever setRenderTarget).
        self.renderer.register_render_target(rt.id, &rt.inner);
        // Whatever the surface format is, the RT was created with the same
        // format; on the crate side we treat it as sRGB (matches WebGL default).
        let t = crate::Texture::from_render_target(
            rt.id,
            rt.width,
            rt.height,
            crate::textures::TextureFormat::Rgba8UnormSrgb,
        );
        WebTexture {
            inner: std::sync::Arc::new(t),
        }
    }

    /// Read pixels from a render target. Returns a Promise<Uint8Array> of RGBA
    /// bytes in row-major order (4 bytes per pixel). The copy is encoded into
    /// a staging buffer; the buffer is mapped asynchronously and the bytes
    /// returned to JS once the GPU has finished.
    #[wasm_bindgen(js_name = readRenderTargetPixels)]
    pub fn read_render_target_pixels(
        &self,
        target_id: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> js_sys::Promise {
        let device = self.renderer.device_arc();
        let queue = self.renderer.queue_arc();
        let target = match ACTIVE_TARGETS.with(|m| m.borrow().get(&target_id).cloned()) {
            Some(t) => t,
            None => return js_sys::Promise::reject(&JsValue::from_str("unknown render target id")),
        };
        // wgpu requires the row byte count to be a multiple of 256.
        const ALIGN: u32 = 256;
        let bytes_per_pixel = 4u32;
        let unpadded = w * bytes_per_pixel;
        let padded = unpadded.div_ceil(ALIGN) * ALIGN;
        let buf_size = (padded * h) as u64;
        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("threers readback buffer"),
            size: buf_size,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        {
            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("threers readback encoder"),
            });
            encoder.copy_texture_to_buffer(
                wgpu::TexelCopyTextureInfo {
                    texture: &target.color_texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d { x, y, z: 0 },
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyBufferInfo {
                    buffer: &buffer,
                    layout: wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(padded),
                        rows_per_image: Some(h),
                    },
                },
                wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
            );
            queue.submit(std::iter::once(encoder.finish()));
        }
        // On WebGPU a target takes the canvas's format, `bgra8unorm` in
        // Chrome; three.js's `readRenderTargetPixels` returns RGBA whatever
        // the target, so BGRA is swizzled on the way out.
        let bgra = matches!(
            target.color_texture.format(),
            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
        );

        wasm_bindgen_futures::future_to_promise(async move {
            // Map the buffer for reading. wgpu uses a callback; bridge with a oneshot.
            let buffer_slice = buffer.slice(..);
            let (tx, rx) = futures_channel::oneshot::channel();
            buffer_slice.map_async(wgpu::MapMode::Read, move |res| {
                let _ = tx.send(res);
            });
            // Pump the device until the map completes, yielding between polls:
            // blocking here would starve the callback. See
            // `await_buffer_mapping`.
            await_buffer_mapping(&device, rx)
                .await
                .map_err(|e| JsValue::from_str(&e))?;
            // Copy the mapped (possibly padded) range into a tight RGBA byte vec.
            let mapped = buffer_slice
                .get_mapped_range()
                .expect("buffer range is mapped");
            let mut out = Vec::with_capacity((w * h * bytes_per_pixel) as usize);
            for row in 0..h {
                let start = (row * padded) as usize;
                let end = start + (unpadded as usize);
                out.extend_from_slice(&mapped[start..end]);
            }
            drop(mapped);
            buffer.unmap();
            if bgra {
                for px in out.chunks_exact_mut(4) {
                    px.swap(0, 2);
                }
            }
            // What three.js returns for the target's colour space.
            target.bytes_as_color_space(&mut out);
            let u8arr = js_sys::Uint8Array::new_with_length(out.len() as u32);
            u8arr.copy_from(&out);
            Ok(JsValue::from(u8arr))
        })
    }

    /// Apply a post-fx pass: read input render target, write to canvas.
    /// `kind`: 0=copy … 11=ssao, 12=ssr, 13=ssao-blur, 14=ssao-composite.
    /// `depth_rt_id` / `normal_rt_id`: optional prepass RTs (0 = fallback).
    /// For SSAO (kind 11), pass camera near/far, kernel size, and projection
    /// matrices via the trailing arguments.
    #[wasm_bindgen(js_name = applyPostFx)]
    pub fn apply_post_fx(
        &mut self,
        input_rt_id: u32,
        depth_rt_id: u32,
        normal_rt_id: u32,
        kind: u32,
        time: f32,
        p2x: f32,
        p2y: f32,
        p2z: f32,
        p2w: f32,
        p3x: f32,
        p3y: f32,
        p3z: f32,
        p3w: f32,
        additive: u32,
        cam_near: f32,
        cam_far: f32,
        kernel_radius: f32,
        kernel_size: u32,
        proj: Vec<f32>,
        inv_proj: Vec<f32>,
    ) {
        let input = match ACTIVE_TARGETS.with(|m| m.borrow().get(&input_rt_id).cloned()) {
            Some(t) => t,
            None => return,
        };
        self.renderer.register_render_target(input_rt_id, &input);
        if depth_rt_id != 0 {
            if let Some(depth) = ACTIVE_TARGETS.with(|m| m.borrow().get(&depth_rt_id).cloned()) {
                self.renderer.register_render_target(depth_rt_id, &depth);
            }
        }
        if normal_rt_id != 0 {
            if let Some(normal) = ACTIVE_TARGETS.with(|m| m.borrow().get(&normal_rt_id).cloned()) {
                self.renderer.register_render_target(normal_rt_id, &normal);
            }
        }
        let camera = postfx_camera_from(
            cam_near,
            cam_far,
            kernel_radius,
            kernel_size,
            &proj,
            &inv_proj,
        );
        // On WebGL2 every canvas write goes through the persistent buffer
        // (`gl_back_buffer`): wgpu's GL backend hands the canvas out as a
        // fresh, uninitialised texture each time, so a second pass onto it —
        // UnrealBloomPass's bloom added over its copy, OutlinePass's edges
        // over the scene — would start from a cleared surface and lose the
        // first. Drawing into the buffer and presenting it keeps both.
        if self.is_gl {
            self.multi_view = true;
            if let Some((back_id, back)) = self.gl_back_buffer() {
                self.renderer.apply_postfx_by_id(
                    input_rt_id,
                    back_id,
                    &back.color_view,
                    depth_rt_id,
                    normal_rt_id,
                    kind,
                    time,
                    [p2x, p2y, p2z, p2w],
                    [p3x, p3y, p3z, p3w],
                    self.width,
                    self.height,
                    additive != 0,
                    camera,
                );
                self.present_gl_back_buffer(back_id);
                return;
            }
        }
        let frame = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(f)
            | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
            _ => {
                self.surface.configure(&self.device, &self.config);
                match self.surface.get_current_texture() {
                    wgpu::CurrentSurfaceTexture::Success(f)
                    | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
                    _ => return,
                }
            }
        };
        let output_view = frame
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        self.renderer.apply_postfx_by_id(
            input_rt_id,
            0,
            &output_view,
            depth_rt_id,
            normal_rt_id,
            kind,
            time,
            [p2x, p2y, p2z, p2w],
            [p3x, p3y, p3z, p3w],
            self.width,
            self.height,
            additive != 0,
            camera,
        );
        self.renderer.queue_arc().present(frame);
    }

    /// Apply a post-fx pass writing into a render target (not canvas).
    #[wasm_bindgen(js_name = applyPostFxToRT)]
    pub fn apply_post_fx_to_rt(
        &mut self,
        input_rt_id: u32,
        output_rt_id: u32,
        depth_rt_id: u32,
        normal_rt_id: u32,
        kind: u32,
        time: f32,
        p2x: f32,
        p2y: f32,
        p2z: f32,
        p2w: f32,
        p3x: f32,
        p3y: f32,
        p3z: f32,
        p3w: f32,
        cam_near: f32,
        cam_far: f32,
        kernel_radius: f32,
        kernel_size: u32,
        proj: Vec<f32>,
        inv_proj: Vec<f32>,
    ) {
        let input = match ACTIVE_TARGETS.with(|m| m.borrow().get(&input_rt_id).cloned()) {
            Some(t) => t,
            None => return,
        };
        let output = match ACTIVE_TARGETS.with(|m| m.borrow().get(&output_rt_id).cloned()) {
            Some(t) => t,
            None => return,
        };
        self.renderer.register_render_target(input_rt_id, &input);
        self.renderer.register_render_target(output_rt_id, &output);
        if depth_rt_id != 0 {
            if let Some(depth) = ACTIVE_TARGETS.with(|m| m.borrow().get(&depth_rt_id).cloned()) {
                self.renderer.register_render_target(depth_rt_id, &depth);
            }
        }
        if normal_rt_id != 0 {
            if let Some(normal) = ACTIVE_TARGETS.with(|m| m.borrow().get(&normal_rt_id).cloned()) {
                self.renderer.register_render_target(normal_rt_id, &normal);
            }
        }
        let camera = postfx_camera_from(
            cam_near,
            cam_far,
            kernel_radius,
            kernel_size,
            &proj,
            &inv_proj,
        );
        self.renderer.apply_postfx_by_id(
            input_rt_id,
            output_rt_id,
            &output.color_view,
            depth_rt_id,
            normal_rt_id,
            kind,
            time,
            [p2x, p2y, p2z, p2w],
            [p3x, p3y, p3z, p3w],
            output.width,
            output.height,
            false,
            camera,
        );
    }

    /// Async readback of a half-float render target (raw RGBA16F bytes).
    #[wasm_bindgen(js_name = readRenderTargetF16)]
    pub fn read_render_target_f16(
        &self,
        target_id: u32,
        x: u32,
        y: u32,
        w: u32,
        h: u32,
    ) -> js_sys::Promise {
        let device = self.device.clone();
        let queue = self.renderer.queue_arc();
        let target = ACTIVE_TARGETS.with(|m| m.borrow().get(&target_id).cloned());
        wasm_bindgen_futures::future_to_promise(async move {
            let target = target.ok_or_else(|| JsValue::from_str("unknown render target id"))?;
            let bytes = read_texture_region(
                &device,
                &queue,
                &target.color_texture,
                target.format,
                x,
                y,
                w,
                h,
            )
            .await
            .map_err(|e| JsValue::from_str(&e))?;
            let arr = js_sys::Uint8Array::new_with_length(bytes.len() as u32);
            arr.copy_from(&bytes);
            Ok(JsValue::from(arr))
        })
    }

    /// Present tightly-packed RGBA8 bytes (top-first rows) to the canvas surface.
    #[wasm_bindgen(js_name = blitRgba8ToCanvas)]
    pub fn blit_rgba8_to_canvas(&mut self, data: Vec<u8>, width: u32, height: u32) {
        let frame = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(f)
            | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
            _ => {
                self.surface.configure(&self.device, &self.config);
                match self.surface.get_current_texture() {
                    wgpu::CurrentSurfaceTexture::Success(f)
                    | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
                    _ => return,
                }
            }
        };
        let output_view = frame
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default());
        self.renderer
            .blit_rgba8(&data, width, height, &output_view, self.config.format);
        self.renderer.queue_arc().present(frame);
    }

    #[wasm_bindgen(js_name = setGlitchDisp)]
    pub fn set_glitch_disp(&mut self, data: Vec<f32>, size: u32) {
        self.renderer.set_glitch_disp(&data, size);
    }

    /// Upload SSAO hemisphere kernel (96 floats: 32×vec3, padded to vec4 on GPU).
    #[wasm_bindgen(js_name = setSsaoKernel)]
    pub fn set_ssao_kernel(&mut self, kernel: &[f32]) {
        self.renderer.set_ssao_kernel(kernel);
    }

    /// Upload 4×4 SSAO rotation noise (16 floats, R32Float texture).
    #[wasm_bindgen(js_name = setSsaoNoise)]
    pub fn set_ssao_noise(&mut self, noise: &[f32]) {
        self.renderer.set_ssao_noise(noise);
    }

    /// Render one face of a cube render target. CubeCamera.update() calls
    /// this six times with face indices 0..6 and the matching face camera.
    #[wasm_bindgen(js_name = renderToCubeFace)]
    pub fn render_to_cube_face(
        &mut self,
        scene: &mut WebScene,
        camera: &WebCamera,
        target: &WebCubeRenderTarget,
        face: u32,
    ) {
        match &camera.inner {
            CameraInner::Perspective(c) => {
                self.renderer
                    .render_to_cube_face(&mut scene.inner, c, &target.inner, face as usize)
            }
            CameraInner::Orthographic(c) => {
                self.renderer
                    .render_to_cube_face(&mut scene.inner, c, &target.inner, face as usize)
            }
        }
    }

    /// Render, then blend `overlay`'s caption for `time` seconds over the frame.
    ///
    /// The caption is composited on the GPU before the frame is presented, so
    /// it lands on top of the 3D image without a second canvas. Sizing follows
    /// the canvas automatically.
    #[cfg(feature = "captions")]
    #[wasm_bindgen(js_name = renderWithCaptions)]
    pub fn render_with_captions(
        &mut self,
        scene: &mut WebScene,
        camera: &WebCamera,
        overlay: &mut WebCaptionOverlay,
        time: f64,
    ) {
        if let Some(id) = self.current_target_id {
            if let Some(target) = ACTIVE_TARGETS.with(|m| m.borrow().get(&id).cloned()) {
                match &camera.inner {
                    CameraInner::Perspective(c) => {
                        self.renderer.render_to(&mut scene.inner, c, &target)
                    }
                    CameraInner::Orthographic(c) => {
                        self.renderer.render_to(&mut scene.inner, c, &target)
                    }
                }
                self.renderer.draw_caption_overlay(
                    &mut overlay.inner,
                    time,
                    target.width,
                    target.height,
                    &target.color_view,
                    target.format,
                );
                return;
            }
        }
        match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(frame)
            | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
                let view = frame
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());
                match &camera.inner {
                    CameraInner::Perspective(c) => {
                        self.renderer.render(&mut scene.inner, c, &view, false)
                    }
                    CameraInner::Orthographic(c) => {
                        self.renderer.render(&mut scene.inner, c, &view, false)
                    }
                }
                self.renderer.draw_caption_overlay(
                    &mut overlay.inner,
                    time,
                    self.width,
                    self.height,
                    &view,
                    self.config.format,
                );
                self.renderer.queue_arc().present(frame);
            }
            _ => {
                self.surface.configure(&self.device, &self.config);
            }
        }
    }

    /// Which backend this renderer got: `"webgpu"`, `"gl"`, or the backend's
    /// own name on other targets.
    ///
    /// Worth asking. On `"gl"` — WebGL2 — there is no compute stage, so bloom,
    /// ambient occlusion and the packed post chain switch themselves off. They
    /// do it quietly, because the alternative is refusing to draw at all, and
    /// without this there is no way to tell that from a scene that simply has
    /// no bloom in it.
    pub fn backend(&self) -> String {
        SHARED_BROWSER_BACKEND
            .with(|b| *b.borrow())
            .map(|b| match b {
                wgpu::Backend::BrowserWebGpu => "webgpu".to_string(),
                wgpu::Backend::Gl => "gl".to_string(),
                other => format!("{other:?}").to_lowercase(),
            })
            .unwrap_or_else(|| "unknown".to_string())
    }

    /// Whether this device can run compute passes.
    ///
    /// False on WebGL2, and the reason the compute-backed effects are
    /// unavailable there.
    #[wasm_bindgen(js_name = supportsCompute)]
    pub fn supports_compute(&self) -> bool {
        crate::renderer::caps::supports_compute(&self.device)
    }

    pub fn render(&mut self, scene: &mut WebScene, camera: &WebCamera) {
        // Targets resized since the last frame: their sample views are new.
        for id in RESIZED_TARGETS.with(|r| std::mem::take(&mut *r.borrow_mut())) {
            if let Some(t) = ACTIVE_TARGETS.with(|m| m.borrow().get(&id).cloned()) {
                self.renderer.register_render_target(id, &t);
            }
        }
        // If the scene references a cube render target as its environment map,
        // make sure the renderer's view cache has its cube view registered.
        if let Some(env_rt_id) = scene.inner.environment_cube_rt {
            if let Some(target) = ACTIVE_CUBE_TARGETS.with(|m| m.borrow().get(&env_rt_id).cloned())
            {
                self.renderer
                    .register_cube_render_target(env_rt_id, &target);
            }
        }
        // If a render target is set, render into it (no canvas presentation).
        if let Some(id) = self.current_target_id {
            if let Some(target) = ACTIVE_TARGETS.with(|m| m.borrow().get(&id).cloned()) {
                match &camera.inner {
                    CameraInner::Perspective(c) => {
                        self.renderer.render_to(&mut scene.inner, c, &target)
                    }
                    CameraInner::Orthographic(c) => {
                        self.renderer.render_to(&mut scene.inner, c, &target)
                    }
                }
                return;
            }
        }
        // A WebGL2 canvas is sRGB, so its hardware blend mixes linear light
        // where three.js's mixes the encoded bytes. The renderer reaches the
        // bytes through a texture — it draws the blended surfaces into a
        // `Unorm` copy of one — so on WebGL2 a frame with anything blended
        // goes through the back buffer, as a multi-pass frame does. The copy
        // to the canvas is exact; from then on every frame takes that path.
        if self.is_gl && !self.multi_view && scene_blends(&scene.inner) {
            self.multi_view = true;
        }
        if let Some((id, back)) = self.gl_back_buffer() {
            match &camera.inner {
                CameraInner::Perspective(c) => {
                    render_back(&mut self.renderer, &mut scene.inner, c, &back)
                }
                CameraInner::Orthographic(c) => {
                    render_back(&mut self.renderer, &mut scene.inner, c, &back)
                }
            }
            self.present_gl_back_buffer(id);
            return;
        }
        match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(frame)
            | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
                let view = frame
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());
                match &camera.inner {
                    CameraInner::Perspective(c) => {
                        self.renderer.render(&mut scene.inner, c, &view, false)
                    }
                    CameraInner::Orthographic(c) => {
                        self.renderer.render(&mut scene.inner, c, &view, false)
                    }
                }
                self.renderer.queue_arc().present(frame);
            }
            _ => {
                self.surface.configure(&self.device, &self.config);
            }
        }
    }

    /// Device and queue for sharing with [`crate::wasm_pathtrace::WebPathTracer`].
    #[cfg(feature = "raytrace")]
    pub(crate) fn gpu_device_queue(
        &self,
    ) -> (std::sync::Arc<wgpu::Device>, std::sync::Arc<wgpu::Queue>) {
        (
            std::sync::Arc::clone(&self.device),
            self.renderer.queue_arc(),
        )
    }
}

/// JS-visible scene wrapper. Returns a `Mesh` handle from `add(mesh)` so JS
/// can keep a reference for subsequent transform updates.
#[wasm_bindgen]
pub struct WebScene {
    inner: crate::Scene,
    /// Mirrored three.js `uuid`s, for animation track names that use them
    /// (`animation::WebScene::find_animation_node`).
    node_uuids: std::collections::HashMap<ObjectId, String>,
    /// Fur in this scene, animated by `stepFur`.
    fur_animator: crate::fur::FurAnimator,
}

#[wasm_bindgen]
impl WebScene {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebScene {
        WebScene {
            inner: crate::Scene::new(),
            node_uuids: std::collections::HashMap::new(),
            fur_animator: crate::fur::FurAnimator::new(),
        }
    }

    /// Add a mesh to the scene. Returns its `ObjectId` (wrapped as `WebObjectHandle`).
    pub fn add(&mut self, mesh: &WebMesh) -> WebObjectHandle {
        let obj = crate::core::Object3D::mesh(crate::core::Mesh::from_arc(
            mesh.geometry.clone(),
            mesh.material.clone(),
        ));
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Point a scene mesh at the current `WebMaterial` Arc (after `setColor` etc.).
    #[wasm_bindgen(js_name = setMeshMaterial)]
    pub fn set_mesh_material(&mut self, handle: &WebObjectHandle, mat: &WebMaterial) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            if let crate::core::ObjectKind::Mesh(mesh) = &mut obj.kind {
                mesh.material = mat.inner.clone();
            }
        }
    }

    /// Query whether a LineSegments object's geometry has a named attribute.
    #[wasm_bindgen(js_name = lineGeometryHasAttr)]
    pub fn line_geometry_has_attr(&self, handle: &WebObjectHandle, name: &str) -> bool {
        self.inner
            .get(handle.id)
            .and_then(|obj| match &obj.kind {
                crate::core::ObjectKind::LineSegments(ls) => {
                    ls.geometry.get_attribute(name).map(|_| ())
                }
                _ => None,
            })
            .is_some()
    }

    #[wasm_bindgen(js_name = lineGeometryUvX)]
    pub fn line_geometry_uv_x(&self, handle: &WebObjectHandle, vert: u32) -> f32 {
        self.inner
            .get(handle.id)
            .and_then(|obj| match &obj.kind {
                crate::core::ObjectKind::LineSegments(ls) => {
                    ls.geometry.get_attribute("uv").and_then(|u| {
                        let i = vert as usize * 2;
                        u.array.get(i).copied()
                    })
                }
                _ => None,
            })
            .unwrap_or(0.0)
    }

    #[wasm_bindgen(js_name = lineMaterialDashSize)]
    pub fn line_material_dash_size(&self, handle: &WebObjectHandle) -> f32 {
        self.inner
            .get(handle.id)
            .and_then(|obj| match &obj.kind {
                crate::core::ObjectKind::LineSegments(ls) => match &*ls.material {
                    crate::Material::Line(m) => Some(m.dash_size),
                    _ => None,
                },
                _ => None,
            })
            .unwrap_or(0.0)
    }

    /// Replace a LineSegments object's geometry after JS-side attribute edits
    /// (e.g. `computeLineDistances()` after `scene.add()`).
    #[wasm_bindgen(js_name = syncLineGeometry)]
    pub fn sync_line_geometry(&mut self, handle: &WebObjectHandle, geom: &WebBufferGeometry) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            if let crate::core::ObjectKind::LineSegments(ls) = &mut obj.kind {
                ls.geometry = geom.inner.clone();
            }
        }
    }

    /// Add a LineSegments primitive (geometry interpreted as line-list).
    #[wasm_bindgen(js_name = addLineSegments)]
    pub fn add_line_segments(
        &mut self,
        geom: &WebBufferGeometry,
        mat: &WebMaterial,
    ) -> WebObjectHandle {
        let ls = crate::core::LineSegments::from_arc(geom.inner.clone(), mat.inner.clone());
        let obj = crate::core::Object3D::line_segments(ls);
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Add a Sprite (billboard) at the scene root. The renderer expands the
    /// material into a camera-facing quad on the fly.
    #[wasm_bindgen(js_name = addSprite)]
    pub fn add_sprite(&mut self, mat: &WebMaterial) -> WebObjectHandle {
        let s = crate::core::Sprite::new((*mat.inner).clone());
        let obj = crate::core::Object3D::sprite(s);
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Add a SkinnedMesh. We default the skeleton to `bone_count` identity
    /// transforms — the mesh renders as a regular Mesh until bone matrices
    /// get updated (a hook can be added later to drive bones each frame).
    #[wasm_bindgen(js_name = addSkinnedMesh)]
    pub fn add_skinned_mesh(
        &mut self,
        geom: &WebGeometry,
        mat: &WebMaterial,
        bone_count: usize,
    ) -> WebObjectHandle {
        let skeleton = crate::core::Skeleton {
            bones: Vec::new(),
            bone_matrices: vec![crate::math::Matrix4::identity(); bone_count.max(1)],
        };
        let sm = crate::core::SkinnedMesh::from_unweighted(
            (*geom.inner).clone(),
            (*mat.inner).clone(),
            skeleton,
        );
        let obj = crate::core::Object3D::skinned_mesh(sm);
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Add an InstancedMesh — a geometry rendered N times with per-instance
    /// transforms, each entry is a column-major mat4 packed as 16 f32s.
    #[wasm_bindgen(js_name = addInstancedMesh)]
    pub fn add_instanced_mesh(
        &mut self,
        geom: &WebGeometry,
        mat: &WebMaterial,
        transforms: Vec<f32>,
    ) -> WebObjectHandle {
        let count = transforms.len() / 16;
        let mut im =
            crate::core::InstancedMesh::new((*geom.inner).clone(), (*mat.inner).clone(), count);
        for i in 0..count {
            let mut e = [0.0f32; 16];
            e.copy_from_slice(&transforms[i * 16..(i + 1) * 16]);
            im.set_matrix_at(i, crate::math::Matrix4 { elements: e });
        }
        let obj = crate::core::Object3D::instanced_mesh(im);
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Grow shell fur (`threers::fur`) on a geometry; returns its handle.
    /// The strand grid is fitted to the geometry's UVs.
    #[wasm_bindgen(js_name = addFur)]
    pub fn add_fur(&mut self, geom: &WebGeometry, fur: &WebFurMaterial) -> WebObjectHandle {
        let obj = crate::fur::fur_object((*geom.inner).clone(), &fur.inner);
        let id = self.inner.add(obj);
        self.fur_animator.track(id, &fur.inner);
        WebObjectHandle { id }
    }

    /// Grow strand hair (`threers::fur::strands`) on a geometry: `count`
    /// strands of `segments` pieces, ribbons `width` wide at the root, shaded
    /// and animated (by `stepFur`) as `fur` says. Returns its handle.
    /// `shadowStrands` (default 0.25) is the share of strands that cast
    /// shadows, 0 for none; the object casts them from shadow-casting lights.
    #[wasm_bindgen(js_name = addHair)]
    pub fn add_hair(
        &mut self,
        geom: &WebGeometry,
        fur: &WebFurMaterial,
        count: u32,
        segments: u32,
        width: f32,
        shadow_strands: Option<f32>,
    ) -> WebObjectHandle {
        let options = crate::fur::strands::StrandOptions {
            count: count as usize,
            segments: segments as usize,
            width,
            shadow_strands: shadow_strands
                .unwrap_or(crate::fur::strands::StrandOptions::default().shadow_strands),
        };
        let obj = crate::fur::strands::hair_object(&geom.inner, &fur.inner, &options);
        let id = self.inner.add(obj);
        self.fur_animator.track(id, &fur.inner);
        WebObjectHandle { id }
    }

    /// Grow strand hair on the skinned mesh `skinned` (a handle from
    /// `addSkinnedMesh` or `createSkinnedMesh`), as its child, carried
    /// through its animation by `stepFur`: each strand on its triangle,
    /// trailing its root on a spring. `undefined` if `skinned` is not a
    /// skinned mesh.
    /// `shadowStrands` as for `addHair`.
    #[wasm_bindgen(js_name = growHairOnSkinned)]
    pub fn grow_hair_on_skinned(
        &mut self,
        skinned: &WebObjectHandle,
        fur: &WebFurMaterial,
        count: u32,
        segments: u32,
        width: f32,
        shadow_strands: Option<f32>,
    ) -> Option<WebObjectHandle> {
        let options = crate::fur::strands::StrandOptions {
            count: count as usize,
            segments: segments as usize,
            width,
            shadow_strands: shadow_strands
                .unwrap_or(crate::fur::strands::StrandOptions::default().shadow_strands),
        };
        self.fur_animator
            .grow_hair_on_skinned(&mut self.inner, skinned.id, &fur.inner, &options)
            .map(|id| WebObjectHandle { id })
    }

    /// Advance every fur object in the scene — wind, flutter and inertia — to
    /// `time` seconds, `dt` after the last step. Once a frame, before
    /// rendering. (The three.js shim's renderer calls it for you.)
    #[wasm_bindgen(js_name = stepFur)]
    pub fn step_fur(&mut self, time: f32, dt: f32) {
        self.fur_animator.update(&mut self.inner, time, dt);
    }

    /// A hand in a fur or hair object's coat (`handle`): within `radius` of
    /// (`x`, `y`, `z`, world), strands are pushed by (`px`, `py`, `pz`) — a
    /// pull, per unit of their length, along the hand's motion — and parted
    /// away from it by `part`. Call it as the hand moves; let go and it
    /// fades, the strands springing back (`stepFur` runs that).
    #[wasm_bindgen(js_name = strokeFur)]
    #[allow(clippy::too_many_arguments)]
    pub fn stroke_fur(
        &mut self,
        handle: &WebObjectHandle,
        x: f32,
        y: f32,
        z: f32,
        radius: f32,
        px: f32,
        py: f32,
        pz: f32,
        part: f32,
    ) {
        self.fur_animator.stroke(
            handle.id,
            crate::Vector3::new(x, y, z),
            radius,
            crate::Vector3::new(px, py, pz),
            part,
        );
    }

    /// Advance a fur object's wind to `seconds`.
    #[wasm_bindgen(js_name = setFurTime)]
    pub fn set_fur_time(&mut self, handle: &WebObjectHandle, seconds: f32) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            crate::fur::set_fur_time(obj, seconds);
        }
    }

    /// Add a Points primitive (geometry interpreted as point-list).
    #[wasm_bindgen(js_name = addPoints)]
    pub fn add_points(&mut self, geom: &WebBufferGeometry, mat: &WebMaterial) -> WebObjectHandle {
        let p = crate::core::Points {
            geometry: geom.inner.clone(),
            material: mat.inner.clone(),
        };
        let obj = crate::core::Object3D::points(p);
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Add an empty Group node (Object3D with no kind). Returns its handle so
    /// children can be parented under it via `addMeshTo` / `addGroupTo`.
    #[wasm_bindgen(js_name = addGroup)]
    pub fn add_group(&mut self) -> WebObjectHandle {
        let obj = crate::core::Object3D::group();
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }

    /// Add a mesh under the given parent (a Group's handle). Returns the
    /// mesh's own handle for further transform updates.
    #[wasm_bindgen(js_name = addMeshTo)]
    pub fn add_mesh_to(&mut self, parent: &WebObjectHandle, mesh: &WebMesh) -> WebObjectHandle {
        let obj = crate::core::Object3D::mesh(crate::core::Mesh::from_arc(
            mesh.geometry.clone(),
            mesh.material.clone(),
        ));
        let id = self.inner.add_to(parent.id, obj);
        WebObjectHandle { id }
    }

    /// Add a light source.
    #[wasm_bindgen(js_name = addLight)]
    pub fn add_light(&mut self, light: &WebLight) -> WebObjectHandle {
        let id = match &light.inner {
            LightInner::Ambient(l) => self.inner.add_light(*l),
            LightInner::Directional(l) => self.inner.add_light(*l),
            LightInner::Point(l) => self.inner.add_light(*l),
            LightInner::Spot(l) => self.inner.add_light(*l),
            LightInner::Hemisphere(l) => self.inner.add_light(*l),
            LightInner::RectArea(l) => self.inner.add_light(*l),
        };
        WebObjectHandle { id }
    }

    /// Replace a light already in the scene with the wrapper's current state.
    ///
    /// `addLight` copies the light in, so every setter on the `WebLight`
    /// afterwards writes to a handle the renderer never reads again — moving a
    /// light, or changing its colour or intensity, silently did nothing once it
    /// had been added. This pushes the wrapper's state back over the scene's
    /// copy; the shim calls it from every light setter.
    #[wasm_bindgen(js_name = updateLight)]
    pub fn update_light(&mut self, handle: &WebObjectHandle, light: &WebLight) {
        let Some(obj) = self.inner.get_mut(handle.id) else {
            return;
        };
        let replacement: crate::lights::Light = match &light.inner {
            LightInner::Ambient(l) => (*l).into(),
            LightInner::Directional(l) => (*l).into(),
            LightInner::Point(l) => (*l).into(),
            LightInner::Spot(l) => (*l).into(),
            LightInner::Hemisphere(l) => (*l).into(),
            LightInner::RectArea(l) => (*l).into(),
        };
        if let crate::ObjectKind::Light(slot) = &mut obj.kind {
            *slot = replacement;
        }
    }

    /// Diagnostic — for each light in the scene, print its world position and
    /// (for spot/directional) direction, after update_world is called.
    #[wasm_bindgen(js_name = dumpLights)]
    pub fn dump_lights(&mut self) -> String {
        self.inner.update_world();
        let mut out = String::new();
        let root = self.inner.root;
        self.inner.arena.traverse_visible(root, &mut |_id, obj| {
            if let crate::ObjectKind::Light(l) = &obj.kind {
                let p = obj.world_position();
                let name = match l {
                    crate::Light::Ambient(_) => "Ambient",
                    crate::Light::Directional(_) => "Directional",
                    crate::Light::Point(_) => "Point",
                    crate::Light::Spot(_) => "Spot",
                    crate::Light::Hemisphere(_) => "Hemisphere",
                    crate::Light::RectArea(_) => "RectArea",
                };
                out.push_str(&format!(
                    "{name} world_pos=({:.3},{:.3},{:.3})\n",
                    p.x, p.y, p.z
                ));
            }
        });
        out
    }

    /// Diagnostic — count lights of each kind currently in this scene.
    #[wasm_bindgen(js_name = lightCounts)]
    pub fn light_counts(&self) -> String {
        let mut n_amb = 0;
        let mut n_dir = 0;
        let mut n_point = 0;
        let mut n_spot = 0;
        let mut n_hemi = 0;
        let root = self.inner.root;
        self.inner.arena.traverse_visible(root, &mut |_id, obj| {
            if let crate::ObjectKind::Light(l) = &obj.kind {
                match l {
                    crate::Light::Ambient(_) => n_amb += 1,
                    crate::Light::Directional(_) => n_dir += 1,
                    crate::Light::Point(_) => n_point += 1,
                    crate::Light::Spot(s) => {
                        n_spot += 1;
                        let _ = s; // intensity available for richer dumps later
                    }
                    crate::Light::Hemisphere(_) => n_hemi += 1,
                    crate::Light::RectArea(_) => {}
                }
            }
        });
        format!("amb={n_amb} dir={n_dir} pt={n_point} sp={n_spot} hemi={n_hemi}")
    }

    /// Configure fog. `mode`: 0 = off, 1 = linear, 2 = exp2. `near`/`far` are
    /// used for linear; `density` is used for exp2.
    #[wasm_bindgen(js_name = setFog)]
    pub fn set_fog(&mut self, color: &WebColor, near: f32, far: f32, density: f32, mode: u32) {
        self.inner.fog = crate::scene::FogParams {
            color: color.inner,
            near,
            far,
            density,
            mode,
        };
    }

    /// Bind a cube render target as this scene's environment map. Pass `0`
    /// to clear and fall back to the CPU-side `environment` cubemap.
    #[wasm_bindgen(js_name = setEnvironmentCube)]
    pub fn set_environment_cube(&mut self, rt_id: u32) {
        self.inner.environment_cube_rt = if rt_id == 0 { None } else { Some(rt_id) };
    }

    /// three.js `scene.environmentIntensity` (default 1).
    #[wasm_bindgen(js_name = setEnvironmentIntensity)]
    pub fn set_environment_intensity(&mut self, v: f32) {
        self.inner.environment_intensity = v;
    }

    /// three.js `scene.environmentRotation`, an Euler in `order`.
    #[wasm_bindgen(js_name = setEnvironmentRotation)]
    pub fn set_environment_rotation(&mut self, x: f32, y: f32, z: f32, order: &str) {
        self.inner.environment_rotation = crate::math::Euler {
            x,
            y,
            z,
            order: crate::math::EulerOrder::parse(order).unwrap_or_default(),
        };
    }

    /// three.js `scene.environment = null`: no environment at all, cube map
    /// or cube render target.
    #[wasm_bindgen(js_name = clearEnvironment)]
    pub fn clear_environment(&mut self) {
        self.inner.environment = None;
        self.inner.environment_cube_rt = None;
    }

    /// Bind a CPU-side cubemap (optionally PMREM-filtered) as the environment.
    #[wasm_bindgen(js_name = setEnvironmentMap)]
    pub fn set_environment_map(&mut self, cube: &WebCubeTexture) {
        self.inner.environment = Some(Arc::clone(&cube.inner));
        self.inner.environment_cube_rt = None;
    }

    /// Set the background color (clear color).
    #[wasm_bindgen(setter, js_name = background)]
    pub fn set_background(&mut self, color: &WebColor) {
        self.inner.background = color.inner;
    }

    /// Clear alpha for the framebuffer (0 = transparent canvas over HTML video).
    #[wasm_bindgen(js_name = setBackgroundAlpha)]
    pub fn set_background_alpha(&mut self, alpha: f32) {
        self.inner.background_alpha = alpha.clamp(0.0, 1.0);
    }

    /// Update an object's transform (position + quaternion).
    #[wasm_bindgen(js_name = setTransform)]
    pub fn set_transform(&mut self, handle: &WebObjectHandle, pos: &WebVector3, rot: &WebEuler) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.position = pos.inner;
            obj.quaternion = rot.inner.to_quaternion();
        }
    }

    /// three.js `Object3D.castShadow`.
    #[wasm_bindgen(js_name = setObjectCastShadow)]
    pub fn set_object_cast_shadow(&mut self, handle: &WebObjectHandle, cast: bool) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.cast_shadow = cast;
        }
    }

    /// One world-space clipping plane (`Object3D::clip_plane`): fragments
    /// where `n·p + constant < 0` are discarded. The shim resolves three.js's
    /// `material.clippingPlanes` / `renderer.clippingPlanes` to this each
    /// frame. `on = false` removes it.
    #[wasm_bindgen(js_name = setObjectClipPlane)]
    pub fn set_object_clip_plane(
        &mut self,
        handle: &WebObjectHandle,
        nx: f32,
        ny: f32,
        nz: f32,
        constant: f32,
        on: bool,
    ) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.clip_plane = on
                .then(|| crate::math::Plane::new(crate::math::Vector3::new(nx, ny, nz), constant));
        }
    }

    /// three.js `Object3D.receiveShadow`.
    #[wasm_bindgen(js_name = setObjectReceiveShadow)]
    pub fn set_object_receive_shadow(&mut self, handle: &WebObjectHandle, receive: bool) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.receive_shadow = receive;
        }
    }
}

#[wasm_bindgen]
pub struct WebObjectHandle {
    id: ObjectId,
}

#[wasm_bindgen]
impl WebObjectHandle {
    /// A number naming this object, stable while it lives — what
    /// `WebRaycaster.intersectObject(s)` take and report as `objectId`.
    /// `WebScene.handleOf` turns it back into a handle.
    #[wasm_bindgen(getter)]
    pub fn id(&self) -> f64 {
        object_id_to_f64(self.id)
    }
}

/// An `ObjectId` as a JS number: slotmap's `(version << 32) | index`, exact
/// below 2^53 (a slot reused two million times).
fn object_id_to_f64(id: ObjectId) -> f64 {
    use slotmap::Key;
    id.data().as_ffi() as f64
}

fn object_id_from_f64(id: f64) -> Option<ObjectId> {
    if !(id.is_finite() && id >= 0.0 && id.fract() == 0.0 && id < 9_007_199_254_740_992.0) {
        return None;
    }
    Some(ObjectId::from(slotmap::KeyData::from_ffi(id as u64)))
}

/// JS-visible camera that wraps either a perspective or orthographic camera.
#[wasm_bindgen]
pub struct WebCamera {
    inner: CameraInner,
}

enum CameraInner {
    Perspective(crate::PerspectiveCamera),
    Orthographic(crate::OrthographicCamera),
}

#[wasm_bindgen]
impl WebCamera {
    #[wasm_bindgen(js_name = perspective)]
    pub fn perspective(fov_deg: f32, aspect: f32, near: f32, far: f32) -> WebCamera {
        WebCamera {
            inner: CameraInner::Perspective(crate::PerspectiveCamera::new(
                fov_deg, aspect, near, far,
            )),
        }
    }

    #[wasm_bindgen(js_name = orthographic)]
    pub fn orthographic(
        left: f32,
        right: f32,
        top: f32,
        bottom: f32,
        near: f32,
        far: f32,
    ) -> WebCamera {
        WebCamera {
            inner: CameraInner::Orthographic(crate::OrthographicCamera::new(
                left, right, top, bottom, near, far,
            )),
        }
    }

    #[wasm_bindgen(js_name = setPosition)]
    pub fn set_position(&mut self, x: f32, y: f32, z: f32) {
        match &mut self.inner {
            CameraInner::Perspective(c) => c.position = crate::Vector3::new(x, y, z),
            CameraInner::Orthographic(c) => c.position = crate::Vector3::new(x, y, z),
        }
    }

    #[wasm_bindgen(js_name = readPosition)]
    pub fn read_position(&self) -> WebVector3 {
        let p = match &self.inner {
            CameraInner::Perspective(c) => c.position,
            CameraInner::Orthographic(c) => c.position,
        };
        WebVector3::new(p.x, p.y, p.z)
    }

    #[wasm_bindgen(js_name = readTarget)]
    pub fn read_target(&self) -> WebVector3 {
        let t = match &self.inner {
            CameraInner::Perspective(c) => c.target,
            CameraInner::Orthographic(c) => c.target,
        };
        WebVector3::new(t.x, t.y, t.z)
    }

    #[wasm_bindgen(js_name = lookAt)]
    pub fn look_at(&mut self, x: f32, y: f32, z: f32) {
        match &mut self.inner {
            CameraInner::Perspective(c) => {
                c.look_at(crate::Vector3::new(x, y, z));
            }
            CameraInner::Orthographic(c) => {
                c.target = crate::Vector3::new(x, y, z);
            }
        }
    }

    /// Atomic eye + look-at (+ optional FOV) update for cinematic animation.
    /// Pass `fov_deg < 0` to leave FOV unchanged. One wasm call per frame
    /// instead of separate `setPosition` / `lookAt` / `setFov`.
    #[wasm_bindgen(js_name = setView)]
    pub fn set_view(&mut self, px: f32, py: f32, pz: f32, tx: f32, ty: f32, tz: f32, fov_deg: f32) {
        let eye = crate::Vector3::new(px, py, pz);
        let target = crate::Vector3::new(tx, ty, tz);
        match &mut self.inner {
            CameraInner::Perspective(c) => {
                c.position = eye;
                c.look_at(target);
                if fov_deg.is_finite() && fov_deg >= 0.0 {
                    c.fov = fov_deg.to_radians();
                }
            }
            CameraInner::Orthographic(c) => {
                c.position = eye;
                c.target = target;
            }
        }
    }

    /// Set the camera's up vector. Needed by CubeCamera face cameras whose
    /// +Y/-Y views look straight up/down — with the default up of (0,1,0)
    /// those views become degenerate (lookAt parallel to up).
    #[wasm_bindgen(js_name = setUp)]
    pub fn set_up(&mut self, x: f32, y: f32, z: f32) {
        let v = crate::Vector3::new(x, y, z);
        match &mut self.inner {
            CameraInner::Perspective(c) => {
                c.up = v;
            }
            CameraInner::Orthographic(c) => {
                c.up = v;
            }
        }
    }

    /// three.js `PerspectiveCamera.fov`, in degrees. No-op on orthographic.
    #[wasm_bindgen(js_name = setFov)]
    pub fn set_fov(&mut self, fov_deg: f32) {
        if let CameraInner::Perspective(c) = &mut self.inner {
            c.fov = fov_deg.to_radians();
        }
    }

    /// Lens shift as a fraction of the sensor (three.js `filmOffset` / filmGauge).
    #[wasm_bindgen(js_name = setShift)]
    pub fn set_shift(&mut self, shift_x: f32, shift_y: f32) {
        if let CameraInner::Perspective(c) = &mut self.inner {
            c.shift_x = shift_x;
            c.shift_y = shift_y;
        }
    }

    /// Focus distance for DoF (three.js `camera.focus` is related but in different units;
    /// here we store world-space distance).
    #[wasm_bindgen(js_name = setFocusDistance)]
    pub fn set_focus_distance(&mut self, distance: f32) {
        if let CameraInner::Perspective(c) = &mut self.inner {
            c.focus_distance = distance.max(0.0);
        }
    }

    #[wasm_bindgen(js_name = setAspect)]
    pub fn set_aspect(&mut self, aspect: f32) {
        use crate::cameras::Camera;
        match &mut self.inner {
            CameraInner::Perspective(c) => c.set_aspect(aspect),
            CameraInner::Orthographic(c) => c.set_aspect(aspect),
        }
    }

    /// Copy fov/near/far/aspect from another camera. Used by Reflector to
    /// align its virtual camera with the main camera so the projective
    /// texture matrix lines up.
    #[wasm_bindgen(js_name = copyProjection)]
    pub fn copy_projection(&mut self, other: &WebCamera) {
        match (&mut self.inner, &other.inner) {
            (CameraInner::Perspective(a), CameraInner::Perspective(b)) => {
                a.fov = b.fov;
                a.aspect = b.aspect;
                a.near = b.near;
                a.far = b.far;
            }
            (CameraInner::Orthographic(a), CameraInner::Orthographic(b)) => {
                a.left = b.left;
                a.right = b.right;
                a.top = b.top;
                a.bottom = b.bottom;
                a.near = b.near;
                a.far = b.far;
            }
            _ => {}
        }
    }

    /// Read back the column-major 4×4 view matrix (camera.matrixWorldInverse
    /// in three.js terms). Needed by Reflector/Refractor to build the
    /// projective texture matrix for their reflected camera.
    #[wasm_bindgen(js_name = viewMatrix)]
    pub fn view_matrix(&self) -> Vec<f32> {
        use crate::cameras::Camera;
        match &self.inner {
            CameraInner::Perspective(c) => c.view_matrix().elements.to_vec(),
            CameraInner::Orthographic(c) => c.view_matrix().elements.to_vec(),
        }
    }

    /// Read back the column-major 4×4 projection matrix.
    #[wasm_bindgen(js_name = projectionMatrix)]
    pub fn projection_matrix(&self) -> Vec<f32> {
        use crate::cameras::Camera;
        match &self.inner {
            CameraInner::Perspective(c) => c.projection_matrix().elements.to_vec(),
            CameraInner::Orthographic(c) => c.projection_matrix().elements.to_vec(),
        }
    }

    /// Override the virtual camera projection (Reflector oblique near clip).
    #[wasm_bindgen(js_name = setProjectionOverride)]
    pub fn set_projection_override(&mut self, elements: Vec<f32>) {
        if elements.len() != 16 {
            return;
        }
        if let CameraInner::Perspective(c) = &mut self.inner {
            let mut m = [0f32; 16];
            m.copy_from_slice(&elements);
            c.projection_override = Some(m);
        }
    }

    #[wasm_bindgen(js_name = clearProjectionOverride)]
    pub fn clear_projection_override(&mut self) {
        if let CameraInner::Perspective(c) = &mut self.inner {
            c.projection_override = None;
        }
    }

    /// Flatten the scene for [`crate::raytrace::RaytraceRenderer`].
    #[cfg(feature = "raytrace")]
    pub(crate) fn prepare_path_tracer(
        &self,
        scene: &mut WebScene,
        renderer: &mut crate::raytrace::RaytraceRenderer,
    ) {
        match &self.inner {
            CameraInner::Perspective(c) => renderer.prepare(&mut scene.inner, c),
            CameraInner::Orthographic(c) => renderer.prepare(&mut scene.inner, c),
        }
    }

    /// As [`Self::prepare_path_tracer`], but skip BVH rebuild when unchanged.
    #[cfg(feature = "raytrace")]
    pub(crate) fn prepare_path_tracer_if_changed(
        &self,
        scene: &mut WebScene,
        renderer: &mut crate::raytrace::RaytraceRenderer,
    ) -> bool {
        match &self.inner {
            CameraInner::Perspective(c) => renderer.prepare_if_changed(&mut scene.inner, c),
            CameraInner::Orthographic(c) => renderer.prepare_if_changed(&mut scene.inner, c),
        }
    }
}

#[wasm_bindgen]
pub struct WebGeometry {
    inner: Arc<crate::BufferGeometry>,
}

#[wasm_bindgen]
impl WebGeometry {
    #[wasm_bindgen(js_name = box)]
    pub fn box_(width: f32, height: f32, depth: f32) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::BoxGeometry::new(width, height, depth)),
        }
    }

    #[wasm_bindgen(js_name = sphere)]
    pub fn sphere(radius: f32, w_segments: usize, h_segments: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::SphereGeometry::new(radius, w_segments, h_segments)),
        }
    }

    /// A sphere patch — three.js's `phiStart/phiLength/thetaStart/thetaLength`.
    ///
    /// UVs span 0..1 across the patch, not across the whole sphere, so each
    /// patch can carry its own texture. That is what makes a tiled globe
    /// possible without a single texture past the 8192 device limit.
    #[wasm_bindgen(js_name = sphereRange)]
    #[allow(clippy::too_many_arguments)]
    pub fn sphere_range(
        radius: f32,
        w_segments: usize,
        h_segments: usize,
        phi_start: f32,
        phi_length: f32,
        theta_start: f32,
        theta_length: f32,
    ) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::SphereGeometry::with_range(
                radius,
                w_segments,
                h_segments,
                phi_start,
                phi_length,
                theta_start,
                theta_length,
            )),
        }
    }

    #[wasm_bindgen(js_name = plane)]
    pub fn plane(width: f32, height: f32) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::PlaneGeometry::new(width, height)),
        }
    }

    /// A quad from four corners in winding order, flattened as
    /// `[x0, y0, z0, …, x3, y3, z3]`; subdivided as a bilinear patch.
    #[wasm_bindgen(js_name = quad)]
    pub fn quad(
        corners: &[f32],
        width_segments: usize,
        height_segments: usize,
    ) -> Result<WebGeometry, JsValue> {
        if corners.len() != 12 {
            return Err(JsValue::from_str(&format!(
                "quad: expected 12 corner coordinates, got {}",
                corners.len()
            )));
        }
        let c =
            |i: usize| crate::Vector3::new(corners[i * 3], corners[i * 3 + 1], corners[i * 3 + 2]);
        Ok(WebGeometry {
            inner: Arc::new(crate::QuadGeometry::with_segments(
                [c(0), c(1), c(2), c(3)],
                width_segments,
                height_segments,
            )),
        })
    }

    #[wasm_bindgen(js_name = cylinder)]
    pub fn cylinder(
        radius_top: f32,
        radius_bottom: f32,
        height: f32,
        radial_segments: usize,
    ) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::CylinderGeometry::new(
                radius_top,
                radius_bottom,
                height,
                radial_segments,
                1,
                false,
                0.0,
                std::f32::consts::PI * 2.0,
            )),
        }
    }

    #[wasm_bindgen(js_name = torus)]
    pub fn torus(
        radius: f32,
        tube: f32,
        radial_segments: u32,
        tubular_segments: u32,
    ) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::TorusGeometry::new(
                radius,
                tube,
                radial_segments.max(3) as usize,
                tubular_segments.max(3) as usize,
                std::f32::consts::PI * 2.0,
            )),
        }
    }

    /// Kirigami Expanded Miura plate lattice.
    ///
    /// `variant`: preset index with slot [`KIRIGAMI_NET_VARIANT`] = developed 2D net.
    /// See [`KirigamiPreset::from_variant`].
    #[wasm_bindgen(js_name = kirigami)]
    pub fn kirigami(variant: u32, nx: u32, ny: u32, thickness: f32) -> WebGeometry {
        let nx = (nx as usize).max(1);
        let ny = (ny as usize).max(2);
        let t = thickness.max(0.0) as f64;
        let geom = if variant == crate::KIRIGAMI_NET_VARIANT {
            crate::KirigamiPreset::Planar
                .evaluate(nx, ny, t)
                .develop_joined()
                .to_geometry(t.max(0.4))
        } else if let Some(preset) = crate::KirigamiPreset::from_variant(variant) {
            let mesh = preset.evaluate(nx, ny, t);
            preset.to_geometry(&mesh)
        } else {
            crate::KirigamiPreset::Planar
                .evaluate(nx, ny, t)
                .to_geometry()
        };
        WebGeometry {
            inner: Arc::new(geom),
        }
    }

    /// Developed crease-pattern SVG (mm) for a preset or the planar net fallback.
    #[wasm_bindgen(js_name = kirigamiNetSvg)]
    pub fn kirigami_net_svg(variant: u32, nx: u32, ny: u32) -> String {
        let nx = (nx as usize).max(1);
        let ny = (ny as usize).max(2);
        let preset =
            crate::KirigamiPreset::from_variant(variant).unwrap_or(crate::KirigamiPreset::Planar);
        preset.evaluate(nx, ny, 0.0).develop_joined().to_svg()
    }

    /// Face-connected cuboct continuum lattice (Jenett et al. Sci. Adv. 2020).
    ///
    /// `variant`: 0 rigid, 1 compliant, 2 auxetic, 3 chiral CW, 4 chiral CCW.
    #[wasm_bindgen(js_name = cuboctLattice)]
    pub fn cuboct_lattice(
        variant: u32,
        size: f32,
        cells: u32,
        resolution: u32,
        shape: f32,
    ) -> WebGeometry {
        let kind = match variant {
            1 => crate::Cuboct::Compliant,
            2 => crate::Cuboct::Auxetic,
            3 => crate::Cuboct::ChiralCw,
            4 => crate::Cuboct::ChiralCcw,
            _ => crate::Cuboct::Rigid,
        };
        let n = (cells as usize).clamp(1, 3);
        let res = resolution.clamp(10, 20) as usize;
        let geom = crate::Lattice::new(crate::LatticeKind::Cuboct(kind))
            .size(crate::Vector3::new(size, size, size))
            .cells([n, n, n])
            .shape(shape)
            .resolution(res)
            .max_samples(3_000_000)
            .fit_relative_density(0.18)
            .resolve_walls(2.5)
            .build();
        WebGeometry {
            inner: Arc::new(geom),
        }
    }

    /// Discrete cuboct assembly — exploded face parts, optional vertex colors.
    #[wasm_bindgen(js_name = cuboctAssembly)]
    pub fn cuboct_assembly(
        variant: u32,
        pitch: f32,
        cells: u32,
        explode: f32,
        colored: bool,
    ) -> WebGeometry {
        let kind = match variant {
            1 => crate::Cuboct::Compliant,
            2 => crate::Cuboct::Auxetic,
            3 => crate::Cuboct::ChiralCw,
            4 => crate::Cuboct::ChiralCcw,
            _ => crate::Cuboct::Rigid,
        };
        let n = (cells as usize).clamp(1, 2);
        let asm = crate::CuboctAssembly::new(kind)
            .pitch(pitch.max(0.1))
            .cells([n, n, n])
            .shape(kind.default_shape())
            .explode(explode.max(0.0))
            .resolution(16);
        let geom = if colored {
            asm.build_colored()
        } else {
            asm.build()
        };
        WebGeometry {
            inner: Arc::new(geom),
        }
    }

    /// 2D laser-cut profile for one cuboct face (mm).
    #[wasm_bindgen(js_name = cuboctFaceSvg)]
    pub fn cuboct_face_svg(variant: u32, pitch: f32, shape: f32) -> String {
        let kind = match variant {
            1 => crate::Cuboct::Compliant,
            2 => crate::Cuboct::Auxetic,
            3 => crate::Cuboct::ChiralCw,
            4 => crate::Cuboct::ChiralCcw,
            _ => crate::Cuboct::Rigid,
        };
        crate::CuboctAssembly::new(kind)
            .pitch(pitch.max(0.1))
            .shape(shape)
            .svg()
    }
}

#[wasm_bindgen]
pub struct WebMaterial {
    inner: Arc<crate::Material>,
}

#[wasm_bindgen]
impl WebMaterial {
    #[wasm_bindgen(js_name = basic)]
    pub fn basic(color: &WebColor) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Basic(crate::BasicMaterial::new(
                color.inner,
            ))),
        }
    }

    /// ShadowMaterial — black transparent surface that only shows shadow darkness.
    #[wasm_bindgen(js_name = shadow)]
    pub fn shadow(opacity: f32) -> WebMaterial {
        let mut m = crate::BasicMaterial::new(crate::math::Color::BLACK);
        m.transparent = true;
        m.opacity = opacity;
        m.shadow_only = true;
        WebMaterial {
            inner: Arc::new(crate::Material::Basic(m)),
        }
    }

    #[wasm_bindgen(js_name = setColor)]
    pub fn set_color(&mut self, color: &WebColor) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Basic(m) => m.color = color.inner,
            crate::Material::Lambert(m) => m.color = color.inner,
            crate::Material::Phong(m) => m.color = color.inner,
            crate::Material::Standard(m) => m.color = color.inner,
            crate::Material::Physical(m) => m.color = color.inner,
            crate::Material::Toon(m) => m.color = color.inner,
            crate::Material::Matcap(m) => m.color = color.inner,
            crate::Material::Line(m) => m.color = color.inner,
            crate::Material::Points(m) => m.color = color.inner,
            crate::Material::Sprite(m) => m.color = color.inner,
            crate::Material::Mirror(m) => m.color = color.inner,
            _ => {}
        }
    }

    /// three.js `toneMapped`: whether the renderer's tone mapping applies to
    /// this material (normal and depth materials never take it).
    #[wasm_bindgen(js_name = setToneMapped)]
    pub fn set_tone_mapped(&mut self, on: bool) {
        Arc::make_mut(&mut self.inner).set_tone_mapped(on);
    }

    /// three.js `depthTest`, `depthWrite`, `depthFunc` (`THREE.NeverDepth`
    /// … `THREE.NotEqualDepth`; anything else keeps the current one) and
    /// `colorWrite`, on any material.
    #[wasm_bindgen(js_name = setRenderState)]
    pub fn set_render_state(
        &mut self,
        depth_test: bool,
        depth_write: bool,
        depth_func: u32,
        color_write: bool,
    ) {
        let s = Arc::make_mut(&mut self.inner).render_state_mut();
        s.depth_test = depth_test;
        s.depth_write = Some(depth_write);
        if let Some(f) = crate::materials::DepthFunc::from_three(depth_func) {
            s.depth_func = f;
        }
        s.color_write = color_write;
    }

    /// three.js `blending` on any material: `THREE.NormalBlending` (1) or
    /// `THREE.AdditiveBlending` (2); anything else keeps the current mode.
    #[wasm_bindgen(js_name = setBlending)]
    pub fn set_blending(&mut self, mode: u32) {
        if let Some(b) = crate::materials::Blending::from_three(mode) {
            Arc::make_mut(&mut self.inner).render_state_mut().blending = b;
        }
    }

    /// three.js `polygonOffset` / `polygonOffsetFactor` /
    /// `polygonOffsetUnits`, on every mesh material that has them.
    #[wasm_bindgen(js_name = setPolygonOffset)]
    pub fn set_polygon_offset(&mut self, enabled: bool, factor: f32, units: f32) {
        let offset = enabled.then_some(crate::materials::PolygonOffset::new(factor, units));
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Basic(m) => m.polygon_offset = offset,
            crate::Material::Lambert(m) => m.polygon_offset = offset,
            crate::Material::Phong(m) => m.polygon_offset = offset,
            crate::Material::Standard(m) => m.polygon_offset = offset,
            crate::Material::Physical(m) => m.polygon_offset = offset,
            crate::Material::Toon(m) => m.polygon_offset = offset,
            crate::Material::Normal(m) => m.polygon_offset = offset,
            crate::Material::Matcap(m) => m.polygon_offset = offset,
            crate::Material::Depth(m) => m.polygon_offset = offset,
            _ => {}
        }
    }

    #[wasm_bindgen(js_name = setAlphaTest)]
    pub fn set_alpha_test(&mut self, value: f32) {
        Arc::make_mut(&mut self.inner).set_alpha_test(value);
    }

    #[wasm_bindgen(js_name = lambert)]
    pub fn lambert(color: &WebColor) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Lambert(crate::LambertMaterial::new(
                color.inner,
            ))),
        }
    }

    #[wasm_bindgen(js_name = standard)]
    pub fn standard(color: &WebColor, roughness: f32, metalness: f32) -> WebMaterial {
        let m = crate::StandardMaterial::new(color.inner)
            .with_roughness(roughness)
            .with_metalness(metalness);
        WebMaterial {
            inner: Arc::new(crate::Material::Standard(m)),
        }
    }

    #[wasm_bindgen(js_name = matcap)]
    pub fn matcap(color: &WebColor) -> WebMaterial {
        let m = crate::MatcapMaterial {
            color: color.inner,
            ..Default::default()
        };
        WebMaterial {
            inner: Arc::new(crate::Material::Matcap(m)),
        }
    }

    /// SkyMaterial — Preetham atmospheric scattering shader. Defaults match
    /// three.js's `examples/jsm/objects/Sky.js`: turbidity 10, rayleigh 3,
    /// mieCoefficient 0.005, mieDirectionalG 0.7.
    #[wasm_bindgen(js_name = sky)]
    pub fn sky(
        sun_x: f32,
        sun_y: f32,
        sun_z: f32,
        turbidity: f32,
        rayleigh: f32,
        mie_coefficient: f32,
        mie_directional_g: f32,
    ) -> WebMaterial {
        let m = crate::materials::SkyMaterial {
            sun_position: crate::math::Vector3::new(sun_x, sun_y, sun_z),
            turbidity,
            rayleigh,
            mie_coefficient,
            mie_directional_g,
            ..Default::default()
        };
        WebMaterial {
            inner: Arc::new(crate::Material::Sky(m)),
        }
    }

    /// Mirror material — drives the Reflector / Refractor / Water shader path.
    /// Color tints the reflection; `setMap` binds the render-target texture;
    /// `setTextureMatrix` pushes the per-frame projective UV transform.
    #[wasm_bindgen(js_name = mirror)]
    pub fn mirror(r: f32, g: f32, b: f32) -> WebMaterial {
        let m = crate::materials::MirrorMaterial {
            color: crate::math::Color::new(r, g, b),
            ..Default::default()
        };
        WebMaterial {
            inner: Arc::new(crate::Material::Mirror(m)),
        }
    }

    /// Push a per-frame texture matrix (column-major 4×4) used by the mirror
    /// fragment shader to projectively sample the RT. Computed JS-side as
    /// `(0.5*bias+0.5) * virtualCam.projection * virtualCam.matrixWorldInverse`.
    #[wasm_bindgen(js_name = setTextureMatrix)]
    pub fn set_texture_matrix(&mut self, elements: Vec<f32>) {
        if elements.len() < 16 {
            return;
        }
        let inner = Arc::make_mut(&mut self.inner);
        if let crate::Material::Mirror(m) = inner {
            m.texture_matrix.copy_from_slice(&elements[..16]);
        }
    }

    /// MeshDistanceMaterial — used by point-light shadow depth passes.
    /// `ref_x/y/z` is the reference position (typically the light's world pos).
    #[wasm_bindgen(js_name = distance)]
    pub fn distance(ref_x: f32, ref_y: f32, ref_z: f32, near: f32, far: f32) -> WebMaterial {
        let m = crate::materials::DistanceMaterial::new(
            crate::math::Vector3::new(ref_x, ref_y, ref_z),
            near,
            far,
        );
        WebMaterial {
            inner: Arc::new(crate::Material::Distance(m)),
        }
    }

    #[wasm_bindgen(js_name = setMatcap)]
    pub fn set_matcap(&mut self, tex: &WebTexture) {
        // The matcap texture lives on the MatcapMaterial variant; for all
        // others this is a no-op.
        let new_inner = match &*self.inner {
            crate::Material::Matcap(m) => {
                let mut m2 = m.clone();
                m2.matcap = Some(tex.inner.clone());
                crate::Material::Matcap(m2)
            }
            other => other.clone(),
        };
        self.inner = Arc::new(new_inner);
    }

    #[wasm_bindgen(js_name = setMatcapData)]
    pub fn set_matcap_data(&mut self, tex: &WebDataTexture) {
        let new_inner = match &*self.inner {
            crate::Material::Matcap(m) => {
                let mut m2 = m.clone();
                m2.matcap = Some(tex.inner.clone());
                crate::Material::Matcap(m2)
            }
            other => other.clone(),
        };
        self.inner = Arc::new(new_inner);
    }

    /// Attach an albedo / color texture to this material. Mirrors three.js's
    /// `material.map = texture`. Only Basic / Standard / Physical / Sprite
    /// honor the slot; calling on other variants is a no-op.
    #[wasm_bindgen(js_name = setMap)]
    pub fn set_map(&mut self, tex: &WebTexture) {
        self.set_map_arc(tex.inner.clone());
    }

    /// `setMapData` for textures created from raw `Uint8Array` data (three.js
    /// `DataTexture` path). Same effect as `setMap` but typed for that handle.
    #[wasm_bindgen(js_name = setMapData)]
    pub fn set_map_data(&mut self, tex: &WebDataTexture) {
        self.set_map_arc(tex.inner.clone());
    }

    /// Attach a tangent-space normal map (three.js `material.normalMap`).
    #[wasm_bindgen(js_name = setNormalMap)]
    pub fn set_normal_map(&mut self, tex: &WebTexture) {
        self.set_normal_map_arc(tex.inner.clone());
    }

    /// `setNormalMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setNormalMapData)]
    pub fn set_normal_map_data(&mut self, tex: &WebDataTexture) {
        self.set_normal_map_arc(tex.inner.clone());
    }

    /// Attach a roughness map (three.js `material.roughnessMap`). Sampled from
    /// the green channel, and multiplied by `material.roughness`.
    /// An analytic planetary atmosphere — see
    /// [`AtmosphereMaterial`](crate::AtmosphereMaterial). Put it on a sphere a
    /// little larger than the planet, sharing its centre.
    pub fn atmosphere(planet_radius: f32, atmosphere_radius: f32) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Atmosphere(crate::AtmosphereMaterial::new(
                planet_radius,
                atmosphere_radius,
            ))),
        }
    }

    /// Tune the atmosphere: scattering tint, the colour it takes at the
    /// terminator, overall strength, and how fast density falls with altitude.
    #[wasm_bindgen(js_name = setAtmosphere)]
    pub fn set_atmosphere(
        &mut self,
        sunset: &WebColor,
        intensity: f32,
        falloff: f32,
        opacity: f32,
    ) {
        if let crate::Material::Atmosphere(m) = Arc::make_mut(&mut self.inner) {
            m.sunset_color = crate::Color::new(sunset.r(), sunset.g(), sunset.b());
            m.intensity = intensity.max(0.0);
            m.falloff = falloff.clamp(0.1, 32.0);
            m.opacity = opacity.clamp(0.0, 1.0);
        }
    }

    /// Airglow strength and colour on an `AtmosphereMaterial`.
    #[wasm_bindgen(js_name = setAirglow)]
    pub fn set_airglow(&mut self, strength: f32, color: &WebColor) {
        let inner = Arc::make_mut(&mut self.inner);
        if let crate::Material::Atmosphere(m) = inner {
            m.airglow = strength.max(0.0);
            m.airglow_color = crate::Color::new(color.r(), color.g(), color.b());
        }
    }

    #[wasm_bindgen(js_name = setRoughnessMap)]
    pub fn set_roughness_map(&mut self, tex: &WebTexture) {
        self.set_roughness_map_arc(tex.inner.clone());
    }

    /// `setRoughnessMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setRoughnessMapData)]
    pub fn set_roughness_map_data(&mut self, tex: &WebDataTexture) {
        self.set_roughness_map_arc(tex.inner.clone());
    }

    /// Attach an emissive map (three.js `material.emissiveMap`), multiplied by
    /// `emissive` and `emissiveIntensity` — city lights on a night side, say.
    #[wasm_bindgen(js_name = setEmissiveMap)]
    pub fn set_emissive_map(&mut self, tex: &WebTexture) {
        self.set_emissive_map_arc(tex.inner.clone());
    }

    /// `setEmissiveMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setEmissiveMapData)]
    pub fn set_emissive_map_data(&mut self, tex: &WebDataTexture) {
        self.set_emissive_map_arc(tex.inner.clone());
    }

    /// Attach a height map (three.js `material.displacementMap`). Unlike a
    /// normal map this moves vertices, so the mesh needs enough of them.
    #[wasm_bindgen(js_name = setDisplacementMap)]
    pub fn set_displacement_map(&mut self, tex: &WebTexture) {
        self.set_displacement_map_arc(tex.inner.clone());
    }

    /// `setDisplacementMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setDisplacementMapData)]
    pub fn set_displacement_map_data(&mut self, tex: &WebDataTexture) {
        self.set_displacement_map_arc(tex.inner.clone());
    }

    /// three.js `material.displacementScale` / `displacementBias`.
    #[wasm_bindgen(js_name = setDisplacement)]
    pub fn set_displacement(&mut self, scale: f32, bias: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Standard(m) => {
                m.displacement_scale = scale;
                m.displacement_bias = bias;
            }
            crate::Material::Physical(m) => {
                m.displacement_scale = scale;
                m.displacement_bias = bias;
            }
            crate::Material::Lambert(m) => {
                m.displacement_scale = scale;
                m.displacement_bias = bias;
            }
            crate::Material::Phong(m) => {
                m.displacement_scale = scale;
                m.displacement_bias = bias;
            }
            crate::Material::Toon(m) => {
                m.displacement_scale = scale;
                m.displacement_bias = bias;
            }
            _ => {}
        }
    }

    /// A cloud deck that casts shadows onto this surface.
    #[wasm_bindgen(js_name = setCloudShadowMapData)]
    pub fn set_cloud_shadow_map_data(&mut self, tex: &WebDataTexture) {
        let inner = Arc::make_mut(&mut self.inner);
        let t = Some(tex.inner.clone());
        match inner {
            crate::Material::Standard(m) => m.cloud_shadow_map = t,
            crate::Material::Physical(m) => m.cloud_shadow_map = t,
            _ => {}
        }
    }

    /// `[shell height, shadow strength, cloud longitude offset in turns,
    /// twilight width]`.
    #[wasm_bindgen(js_name = setAtmosphereShading)]
    pub fn set_atmosphere_shading(
        &mut self,
        height: f32,
        shadow: f32,
        rotation: f32,
        twilight: f32,
    ) {
        let inner = Arc::make_mut(&mut self.inner);
        macro_rules! set {
            ($m:expr) => {{
                $m.cloud_height = height.max(0.0);
                $m.cloud_shadow = shadow.clamp(0.0, 1.0);
                $m.cloud_rotation = rotation;
                $m.twilight = twilight.max(0.0);
            }};
        }
        match inner {
            crate::Material::Standard(m) => set!(m),
            crate::Material::Physical(m) => set!(m),
            _ => {}
        }
    }

    /// The colour scattered light takes on near the terminator.
    #[wasm_bindgen(js_name = setTwilightColor)]
    pub fn set_twilight_color(&mut self, color: &WebColor) {
        let inner = Arc::make_mut(&mut self.inner);
        let c = crate::Color::new(color.r(), color.g(), color.b());
        match inner {
            crate::Material::Standard(m) => m.twilight_color = c,
            crate::Material::Physical(m) => m.twilight_color = c,
            _ => {}
        }
    }

    /// A sphere that can eclipse the sun for this surface: world-space centre
    /// and radius, plus the sun's angular radius in radians. A radius of 0
    /// clears it.
    #[wasm_bindgen(js_name = setEclipse)]
    pub fn set_eclipse(&mut self, x: f32, y: f32, z: f32, radius: f32, sun_angular_radius: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        let occ = if radius > 0.0 {
            Some([x, y, z, radius])
        } else {
            None
        };
        match inner {
            crate::Material::Standard(m) => {
                m.eclipse_occluder = occ;
                m.sun_angular_radius = sun_angular_radius;
            }
            crate::Material::Physical(m) => {
                m.eclipse_occluder = occ;
                m.sun_angular_radius = sun_angular_radius;
            }
            _ => {}
        }
    }

    /// three.js `material.normalScale`.
    #[wasm_bindgen(js_name = setNormalScale)]
    pub fn set_normal_scale(&mut self, x: f32, y: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        let v = crate::math::Vector2::new(x, y);
        match inner {
            crate::Material::Standard(m) => m.normal_scale = v,
            crate::Material::Physical(m) => m.normal_scale = v,
            crate::Material::Lambert(m) => m.normal_scale = v,
            crate::Material::Phong(m) => m.normal_scale = v,
            crate::Material::Toon(m) => m.normal_scale = v,
            _ => {}
        }
    }

    /// three.js `material.aoMap`: ambient occlusion from the red channel,
    /// occluding the indirect light. Standard, Physical, Lambert, Phong, Toon.
    #[wasm_bindgen(js_name = setAoMap)]
    pub fn set_ao_map(&mut self, tex: &WebTexture) {
        self.set_ao_map_arc(tex.inner.clone());
    }

    /// `setAoMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setAoMapData)]
    pub fn set_ao_map_data(&mut self, tex: &WebDataTexture) {
        self.set_ao_map_arc(tex.inner.clone());
    }

    /// three.js `material.alphaMap`: its green channel scales the opacity.
    /// Basic, Lambert, Phong, Toon, Standard, Physical, Matcap and Sprite.
    #[wasm_bindgen(js_name = setAlphaMap)]
    pub fn set_alpha_map(&mut self, tex: &WebTexture) {
        self.set_slot("alphaMap", Some(tex.inner.clone()));
    }

    /// `setAlphaMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setAlphaMapData)]
    pub fn set_alpha_map_data(&mut self, tex: &WebDataTexture) {
        self.set_slot("alphaMap", Some(tex.inner.clone()));
    }

    /// three.js `material.metalnessMap`: its blue channel scales `metalness`.
    /// Standard and Physical.
    #[wasm_bindgen(js_name = setMetalnessMap)]
    pub fn set_metalness_map(&mut self, tex: &WebTexture) {
        self.set_slot("metalnessMap", Some(tex.inner.clone()));
    }

    /// `setMetalnessMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setMetalnessMapData)]
    pub fn set_metalness_map_data(&mut self, tex: &WebDataTexture) {
        self.set_slot("metalnessMap", Some(tex.inner.clone()));
    }

    /// three.js `material.lightMap`: baked irradiance added to the indirect
    /// light. Basic, Lambert, Phong, Toon, Standard and Physical.
    #[wasm_bindgen(js_name = setLightMap)]
    pub fn set_light_map(&mut self, tex: &WebTexture) {
        self.set_slot("lightMap", Some(tex.inner.clone()));
    }

    /// `setLightMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setLightMapData)]
    pub fn set_light_map_data(&mut self, tex: &WebDataTexture) {
        self.set_slot("lightMap", Some(tex.inner.clone()));
    }

    /// three.js `material.lightMapIntensity` (default 1).
    #[wasm_bindgen(js_name = setLightMapIntensity)]
    pub fn set_light_map_intensity(&mut self, v: f32) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Basic(m) => m.light_map_intensity = v,
            crate::Material::Lambert(m) => m.light_map_intensity = v,
            crate::Material::Phong(m) => m.light_map_intensity = v,
            crate::Material::Toon(m) => m.light_map_intensity = v,
            crate::Material::Standard(m) => m.light_map_intensity = v,
            crate::Material::Physical(m) => m.light_map_intensity = v,
            _ => {}
        }
    }

    /// three.js `material.bumpMap`: a height field perturbing the normal.
    /// Lambert, Phong, Toon, Standard and Physical.
    #[wasm_bindgen(js_name = setBumpMap)]
    pub fn set_bump_map(&mut self, tex: &WebTexture) {
        self.set_slot("bumpMap", Some(tex.inner.clone()));
    }

    /// `setBumpMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setBumpMapData)]
    pub fn set_bump_map_data(&mut self, tex: &WebDataTexture) {
        self.set_slot("bumpMap", Some(tex.inner.clone()));
    }

    /// three.js `material.bumpScale` (default 1).
    #[wasm_bindgen(js_name = setBumpScale)]
    pub fn set_bump_scale(&mut self, v: f32) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Lambert(m) => m.bump_scale = v,
            crate::Material::Phong(m) => m.bump_scale = v,
            crate::Material::Toon(m) => m.bump_scale = v,
            crate::Material::Standard(m) => m.bump_scale = v,
            crate::Material::Physical(m) => m.bump_scale = v,
            _ => {}
        }
    }

    /// three.js `material.specularMap`: its red channel scales the specular
    /// term. Basic, Lambert and Phong.
    #[wasm_bindgen(js_name = setSpecularMap)]
    pub fn set_specular_map(&mut self, tex: &WebTexture) {
        self.set_slot("specularMap", Some(tex.inner.clone()));
    }

    /// `setSpecularMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setSpecularMapData)]
    pub fn set_specular_map_data(&mut self, tex: &WebDataTexture) {
        self.set_slot("specularMap", Some(tex.inner.clone()));
    }

    /// `material[name] = texture` for any map slot three.js names — the
    /// Physical material's `specularIntensityMap`, `clearcoatNormalMap`,
    /// `sheenColorMap` and the rest included (see
    /// [`Material::map_slot_mut`](crate::Material::map_slot_mut)). Whether
    /// this material has that slot.
    #[wasm_bindgen(js_name = setNamedMap)]
    pub fn set_named_map(&mut self, name: &str, tex: &WebTexture) -> bool {
        self.set_slot(name, Some(tex.inner.clone()))
    }

    /// `setNamedMap` for the raw `Uint8Array` / `DataTexture` path.
    #[wasm_bindgen(js_name = setNamedMapData)]
    pub fn set_named_map_data(&mut self, name: &str, tex: &WebDataTexture) -> bool {
        self.set_slot(name, Some(tex.inner.clone()))
    }

    /// three.js `clearcoatNormalScale`.
    #[wasm_bindgen(js_name = setClearcoatNormalScale)]
    pub fn set_clearcoat_normal_scale(&mut self, x: f32, y: f32) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.clearcoat_normal_scale = crate::math::Vector2::new(x, y);
        }
    }

    /// `material[name] = null`: empty the map slot three.js calls `name`
    /// (`"map"`, `"alphaMap"`, `"aoMap"`, `"envMap"`, …). Whether this
    /// material had one.
    #[wasm_bindgen(js_name = clearMap)]
    pub fn clear_map(&mut self, name: &str) -> bool {
        if name == "envMap" {
            if let Some(slot) = self.pbr_env_slot() {
                *slot = None;
                return true;
            }
            return self.env_mut(|m| *m.env_map = None);
        }
        self.set_slot(name, None)
    }

    /// three.js `material.envMap`. On Basic, Lambert and Phong a cube map
    /// reflected (or refracted, per the cube's `mapping`) and combined with
    /// the shaded colour; on Standard and Physical the material's own
    /// image-based light, in place of `scene.environment`. Whether this
    /// material takes one.
    #[wasm_bindgen(js_name = setEnvMap)]
    pub fn set_env_map(&mut self, cube: &WebCubeTexture) -> bool {
        let c = cube.inner.clone();
        if let Some(slot) = self.pbr_env_slot() {
            *slot = Some(c);
            return true;
        }
        self.env_mut(|m| *m.env_map = Some(c.clone()))
    }

    /// three.js `material.envMapIntensity` on Standard and Physical
    /// (default 1).
    #[wasm_bindgen(js_name = setEnvMapIntensity)]
    pub fn set_env_map_intensity(&mut self, v: f32) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => m.env_map_intensity = v,
            crate::Material::Physical(m) => m.env_map_intensity = v,
            _ => {}
        }
    }

    /// three.js `material.combine`: 0 `MultiplyOperation`, 1 `MixOperation`,
    /// 2 `AddOperation`.
    #[wasm_bindgen(js_name = setCombine)]
    pub fn set_combine(&mut self, combine: u32) {
        let c = match combine {
            1 => crate::materials::Combine::Mix,
            2 => crate::materials::Combine::Add,
            _ => crate::materials::Combine::Multiply,
        };
        self.env_mut(|m| *m.combine = c);
    }

    /// three.js `material.reflectivity` (default 1).
    #[wasm_bindgen(js_name = setReflectivity)]
    pub fn set_reflectivity(&mut self, v: f32) {
        self.env_mut(|m| *m.reflectivity = v);
    }

    /// three.js `material.refractionRatio` (default 0.98).
    #[wasm_bindgen(js_name = setRefractionRatio)]
    pub fn set_refraction_ratio(&mut self, v: f32) {
        self.env_mut(|m| *m.refraction_ratio = v);
    }

    /// three.js `material.envMapRotation`, an Euler in `order` (`"XYZ"`, …).
    #[wasm_bindgen(js_name = setEnvMapRotation)]
    pub fn set_env_map_rotation(&mut self, x: f32, y: f32, z: f32, order: &str) {
        let e = crate::math::Euler {
            x,
            y,
            z,
            order: crate::math::EulerOrder::parse(order).unwrap_or_default(),
        };
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => m.env_map_rotation = e,
            crate::Material::Physical(m) => m.env_map_rotation = e,
            _ => {
                self.env_mut(|m| *m.env_map_rotation = e);
            }
        }
    }

    /// three.js `material.aoMapIntensity` (default 1).
    #[wasm_bindgen(js_name = setAoMapIntensity)]
    pub fn set_ao_map_intensity(&mut self, intensity: f32) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => m.ao_intensity = intensity,
            crate::Material::Physical(m) => m.ao_intensity = intensity,
            crate::Material::Lambert(m) => m.ao_intensity = intensity,
            crate::Material::Phong(m) => m.ao_intensity = intensity,
            crate::Material::Toon(m) => m.ao_intensity = intensity,
            _ => {}
        }
    }
}

/// Extended `MeshPhysicalMaterial` layers.
///
/// These are separate setters rather than a 20-argument constructor so the JS
/// shim can forward only the options the caller actually supplied, and so each
/// one mirrors the corresponding Rust builder method on `PhysicalMaterial`.
/// All are no-ops on non-Physical materials.
#[wasm_bindgen]
impl WebMaterial {
    /// three.js `transmission` / `ior` / `thickness` / `dispersion`.
    #[wasm_bindgen(js_name = setTransmission)]
    pub fn set_transmission(
        &mut self,
        transmission: f32,
        ior: f32,
        thickness: f32,
        dispersion: f32,
    ) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.transmission = transmission;
            m.ior = ior;
            m.thickness = thickness;
            m.dispersion = dispersion;
        }
    }

    /// three.js `material.roughness`.
    #[wasm_bindgen(js_name = setRoughness)]
    pub fn set_roughness(&mut self, roughness: f32) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => m.roughness = roughness,
            crate::Material::Physical(m) => m.roughness = roughness,
            _ => {}
        }
    }

    /// three.js `material.metalness`.
    #[wasm_bindgen(js_name = setMetalness)]
    pub fn set_metalness(&mut self, metalness: f32) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => m.metalness = metalness,
            crate::Material::Physical(m) => m.metalness = metalness,
            _ => {}
        }
    }

    /// three.js `anisotropy` / `anisotropyRotation` (radians).
    #[wasm_bindgen(js_name = setAnisotropy)]
    pub fn set_anisotropy(&mut self, strength: f32, rotation: f32) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.anisotropy = strength;
            m.anisotropy_rotation = rotation;
        }
    }

    /// three.js `sheen` / `sheenColor` / `sheenRoughness`.
    #[wasm_bindgen(js_name = setSheen)]
    pub fn set_sheen(&mut self, strength: f32, color: &WebColor, roughness: f32) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.sheen = strength;
            m.sheen_color = color.inner;
            m.sheen_roughness = roughness;
        }
    }

    /// three.js `iridescence` / `iridescenceIOR`, and the film thickness in
    /// nanometres — the top of `iridescenceThicknessRange`.
    #[wasm_bindgen(js_name = setIridescence)]
    pub fn set_iridescence(&mut self, strength: f32, ior: f32, thickness_nm: f32) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.iridescence = strength;
            m.iridescence_ior = ior;
            m.iridescence_thickness_range[1] = thickness_nm;
        }
    }

    /// Every scalar of three.js's `MeshPhysicalMaterial` at once, as the
    /// JavaScript layer holds them: `clearcoat`, `clearcoatRoughness`, `ior`,
    /// `specularIntensity`, `sheen`, `sheenRoughness`, `iridescence`,
    /// `iridescenceIOR`, `iridescenceThicknessRange` (min, max),
    /// `anisotropy`, `anisotropyRotation`, `transmission`, `thickness`,
    /// `attenuationDistance` and `dispersion`.
    #[allow(clippy::too_many_arguments)]
    #[wasm_bindgen(js_name = setPhysical)]
    pub fn set_physical(
        &mut self,
        clearcoat: f32,
        clearcoat_roughness: f32,
        ior: f32,
        specular_intensity: f32,
        sheen: f32,
        sheen_roughness: f32,
        iridescence: f32,
        iridescence_ior: f32,
        iridescence_thickness_min: f32,
        iridescence_thickness_max: f32,
        anisotropy: f32,
        anisotropy_rotation: f32,
        transmission: f32,
        thickness: f32,
        attenuation_distance: f32,
        dispersion: f32,
    ) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.clearcoat = clearcoat;
            m.clearcoat_roughness = clearcoat_roughness;
            m.ior = ior;
            m.specular_intensity = specular_intensity;
            m.sheen = sheen;
            m.sheen_roughness = sheen_roughness;
            m.iridescence = iridescence;
            m.iridescence_ior = iridescence_ior;
            m.iridescence_thickness_range = [iridescence_thickness_min, iridescence_thickness_max];
            m.anisotropy = anisotropy;
            m.anisotropy_rotation = anisotropy_rotation;
            m.transmission = transmission;
            m.thickness = thickness;
            m.attenuation_distance = attenuation_distance;
            m.dispersion = dispersion;
        }
    }

    /// three.js `sheenColor`.
    #[wasm_bindgen(js_name = setSheenColor)]
    pub fn set_sheen_color(&mut self, color: &WebColor) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.sheen_color = color.inner;
        }
    }

    /// three.js `specularColor`.
    #[wasm_bindgen(js_name = setSpecularColor)]
    pub fn set_specular_color(&mut self, color: &WebColor) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.specular_color = color.inner;
        }
    }

    /// three.js `attenuationColor`.
    #[wasm_bindgen(js_name = setAttenuationColor)]
    pub fn set_attenuation_color(&mut self, color: &WebColor) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.attenuation_color = color.inner;
        }
    }

    /// three.js `attenuationColor` / `attenuationDistance`. A non-finite or
    /// non-positive distance disables Beer-Lambert absorption.
    #[wasm_bindgen(js_name = setAttenuation)]
    pub fn set_attenuation(&mut self, color: &WebColor, distance: f32) {
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.attenuation_color = color.inner;
            m.attenuation_distance = distance;
        }
    }

    /// The transparency compositing mode, as `setTransparencyMode` numbers
    /// it (0 for anything but a `PhysicalMaterial`).
    #[wasm_bindgen(getter, js_name = transparencyMode)]
    pub fn transparency_mode(&self) -> u32 {
        use crate::TransparencyMode::*;
        match &*self.inner {
            crate::Material::Physical(m) => match m.transparency {
                Blend => 0,
                Glass => 1,
                Oit => 2,
                Refract => 3,
            },
            _ => 0,
        }
    }

    /// Transparency compositing mode: 0 = Blend, 1 = Glass, 2 = OIT,
    /// 3 = Refract (screen-space refraction).
    #[wasm_bindgen(js_name = setTransparencyMode)]
    pub fn set_transparency_mode(&mut self, mode: u32) {
        use crate::TransparencyMode::*;
        if let crate::Material::Physical(m) = Arc::make_mut(&mut self.inner) {
            m.transparency = match mode {
                1 => Glass,
                2 => Oit,
                3 => Refract,
                _ => Blend,
            };
        }
    }

    /// A measured-reflectance preset from `threers::materials::presets`.
    ///
    /// `param` is only read by the presets that take one: `anodized_titanium`
    /// (film thickness, nm) and `brushed_aluminum` (streak rotation, radians).
    /// An unknown name falls back to a neutral dielectric rather than throwing,
    /// so a typo shows up as a visibly plain sphere instead of a dead page.
    #[wasm_bindgen(js_name = preset)]
    pub fn preset(name: &str, param: f32) -> WebMaterial {
        use crate::materials::presets as p;
        let m = match name {
            "gold_foil" => p::gold_foil(),
            "silver_foil" => p::silver_foil(),
            "aluminum" => p::aluminum(),
            "brushed_aluminum" => p::brushed_aluminum(param),
            "titanium" => p::titanium(),
            "anodized_titanium" => p::anodized_titanium(param),
            "solar_cell" => p::solar_cell(),
            "array_backing" => p::array_backing(),
            "optical_glass" => p::optical_glass(),
            "white_thermal_paint" => p::white_thermal_paint(),
            "black_kapton" => p::black_kapton(),
            _ => crate::PhysicalMaterial::new(crate::Color::from_hex(0x808080)),
        };
        WebMaterial {
            inner: Arc::new(crate::Material::Physical(m)),
        }
    }
}

#[wasm_bindgen]
impl WebMaterial {
    #[wasm_bindgen(js_name = debugString)]
    pub fn debug_string(&self) -> String {
        let slots = self.inner.texture_slots();
        format!(
            "Material kind={:?} map={} normal={} rough={} metal={} ao={} emissive={}",
            self.inner.kind(),
            slots.map.is_some(),
            slots.normal_map.is_some(),
            slots.roughness_map.is_some(),
            slots.metalness_map.is_some(),
            slots.ao_map.is_some(),
            slots.emissive_map.is_some(),
        )
    }
}

#[wasm_bindgen]
impl WebMaterial {
    #[wasm_bindgen(js_name = setDashed)]
    pub fn set_dashed(&mut self, scale: f32, dash_size: f32, gap_size: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        if let crate::Material::Line(m) = inner {
            m.dashed = true;
            m.dash_scale = scale;
            m.dash_size = dash_size;
            m.gap_size = gap_size;
        }
    }

    /// Set per-material opacity (0..1). Sets the matching field on whichever
    /// concrete material this wraps.
    /// three.js `material.opacity`, on every material that has one.
    #[wasm_bindgen(js_name = setOpacity)]
    pub fn set_opacity(&mut self, opacity: f32) {
        Arc::make_mut(&mut self.inner).set_opacity(opacity);
    }

    /// three.js `PointsMaterial.size`, in pixels.
    #[wasm_bindgen(js_name = setPointSize)]
    pub fn set_point_size(&mut self, size: f32) {
        if let crate::Material::Points(m) = Arc::make_mut(&mut self.inner) {
            m.size = size;
        }
    }

    /// Mark a material as needing alpha blending. three.js uses an explicit
    /// `transparent` flag separate from `opacity` so semi-transparent textures
    /// can render correctly even at opacity 1.0.
    #[wasm_bindgen(js_name = setTransparent)]
    pub fn set_transparent(&mut self, transparent: bool) {
        Arc::make_mut(&mut self.inner).set_transparent(transparent);
    }

    /// Set the emissive color. Standard / Physical / Lambert / Phong / Toon
    /// honor this; other variants are no-ops.
    #[wasm_bindgen(js_name = setEmissive)]
    pub fn set_emissive(&mut self, color: &WebColor) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Standard(m) => m.emissive = color.inner,
            crate::Material::Physical(m) => m.emissive = color.inner,
            crate::Material::Lambert(m) => m.emissive = color.inner,
            crate::Material::Phong(m) => m.emissive = color.inner,
            crate::Material::Toon(m) => m.emissive = color.inner,
            _ => {}
        }
    }

    /// Multiplier on the emissive contribution (`material.emissiveIntensity`).
    #[wasm_bindgen(js_name = setEmissiveIntensity)]
    pub fn set_emissive_intensity(&mut self, intensity: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        if let crate::Material::Standard(m) = inner {
            m.emissive_intensity = intensity;
        } else if let crate::Material::Physical(m) = inner {
            m.emissive_intensity = intensity;
        }
    }

    /// Confine the emissive map to the night side (0 = always on, 1 = terminator-gated).
    /// City-lights maps need 1; lamps need 0.
    #[wasm_bindgen(js_name = setEmissiveNightSide)]
    pub fn set_emissive_night_side(&mut self, amount: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        if let crate::Material::Standard(m) = inner {
            m.emissive_night_side = amount.clamp(0.0, 1.0);
        }
    }

    /// Toggle wireframe rendering (renderer picks the line-polygon pipeline).
    #[wasm_bindgen(js_name = setWireframe)]
    pub fn set_wireframe(&mut self, wireframe: bool) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Basic(m) => m.wireframe = wireframe,
            crate::Material::Lambert(m) => m.wireframe = wireframe,
            crate::Material::Phong(m) => m.wireframe = wireframe,
            crate::Material::Standard(m) => m.wireframe = wireframe,
            crate::Material::Physical(m) => m.wireframe = wireframe,
            crate::Material::Normal(m) => m.wireframe = wireframe,
            crate::Material::Depth(m) => m.wireframe = wireframe,
            crate::Material::Toon(m) => m.wireframe = wireframe,
            crate::Material::Matcap(m) => m.wireframe = wireframe,
            _ => {}
        }
    }
}

impl WebMaterial {
    fn set_map_arc(&mut self, tex: std::sync::Arc<crate::Texture>) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Basic(m) => m.map = Some(tex),
            crate::Material::Standard(m) => m.map = Some(tex),
            crate::Material::Physical(m) => m.map = Some(tex),
            crate::Material::Sprite(m) => m.map = Some(tex),
            crate::Material::Mirror(m) => m.map = Some(tex),
            crate::Material::Lambert(m) => m.map = Some(tex),
            crate::Material::Phong(m) => m.map = Some(tex),
            crate::Material::Toon(m) => m.map = Some(tex),
            crate::Material::Matcap(m) => m.map = Some(tex),
            crate::Material::Points(m) => m.map = Some(tex),
            _ => {}
        }
    }

    /// A Standard or Physical material's own `envMap` slot.
    fn pbr_env_slot(&mut self) -> Option<&mut Option<Arc<crate::CubeTexture>>> {
        if !matches!(
            &*self.inner,
            crate::Material::Standard(_) | crate::Material::Physical(_)
        ) {
            return None;
        }
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => Some(&mut m.env_map),
            crate::Material::Physical(m) => Some(&mut m.env_map),
            _ => None,
        }
    }

    /// Apply `f` to the env-map state of a Basic, Lambert or Phong material;
    /// whether this is one.
    fn env_mut(&mut self, f: impl Fn(&mut EnvState<'_>)) -> bool {
        let inner = Arc::make_mut(&mut self.inner);
        let mut state = match inner {
            crate::Material::Basic(m) => EnvState::of(m),
            crate::Material::Lambert(m) => EnvState::of(m),
            crate::Material::Phong(m) => EnvState::of(m),
            _ => return false,
        };
        f(&mut state);
        true
    }

    fn set_slot(&mut self, name: &str, tex: Option<std::sync::Arc<crate::Texture>>) -> bool {
        match Arc::make_mut(&mut self.inner).map_slot_mut(name) {
            Some(slot) => {
                *slot = tex;
                true
            }
            None => false,
        }
    }

    fn set_ao_map_arc(&mut self, tex: std::sync::Arc<crate::Texture>) {
        match Arc::make_mut(&mut self.inner) {
            crate::Material::Standard(m) => m.ao_map = Some(tex),
            crate::Material::Physical(m) => m.ao_map = Some(tex),
            crate::Material::Lambert(m) => m.ao_map = Some(tex),
            crate::Material::Phong(m) => m.ao_map = Some(tex),
            crate::Material::Toon(m) => m.ao_map = Some(tex),
            _ => {}
        }
    }

    fn set_normal_map_arc(&mut self, tex: std::sync::Arc<crate::Texture>) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Standard(m) => m.normal_map = Some(tex),
            crate::Material::Physical(m) => m.normal_map = Some(tex),
            crate::Material::Lambert(m) => m.normal_map = Some(tex),
            crate::Material::Phong(m) => m.normal_map = Some(tex),
            crate::Material::Toon(m) => m.normal_map = Some(tex),
            _ => {}
        }
    }

    fn set_roughness_map_arc(&mut self, tex: std::sync::Arc<crate::Texture>) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Standard(m) => m.roughness_map = Some(tex),
            crate::Material::Physical(m) => m.roughness_map = Some(tex),
            _ => {}
        }
    }

    fn set_displacement_map_arc(&mut self, tex: std::sync::Arc<crate::Texture>) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Standard(m) => m.displacement_map = Some(tex),
            crate::Material::Physical(m) => m.displacement_map = Some(tex),
            crate::Material::Lambert(m) => m.displacement_map = Some(tex),
            crate::Material::Phong(m) => m.displacement_map = Some(tex),
            crate::Material::Toon(m) => m.displacement_map = Some(tex),
            _ => {}
        }
    }

    fn set_emissive_map_arc(&mut self, tex: std::sync::Arc<crate::Texture>) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Standard(m) => m.emissive_map = Some(tex),
            crate::Material::Physical(m) => m.emissive_map = Some(tex),
            crate::Material::Lambert(m) => m.emissive_map = Some(tex),
            crate::Material::Phong(m) => m.emissive_map = Some(tex),
            crate::Material::Toon(m) => m.emissive_map = Some(tex),
            _ => {}
        }
    }
}

#[wasm_bindgen]
impl WebMaterial {
    /// Set the material's render side. `0` = FrontSide (default),
    /// `1` = BackSide, `2` = DoubleSide. Both 1 and 2 route to the no-cull
    /// triangle pipeline at draw time.
    #[wasm_bindgen(js_name = setSide)]
    pub fn set_side(&mut self, side: u32) {
        let inner = Arc::make_mut(&mut self.inner);
        match inner {
            crate::Material::Basic(m) => m.side = side,
            crate::Material::Lambert(m) => m.side = side,
            crate::Material::Phong(m) => m.side = side,
            crate::Material::Standard(m) => m.side = side,
            crate::Material::Physical(m) => m.side = side,
            crate::Material::Toon(m) => m.side = side,
            // Sky always uses BackSide; setting from JS is a no-op (already 1).
            _ => {}
        }
    }
}

/// A custom-shader material, from JavaScript.
///
/// three.js's `ShaderMaterial` is one of the most-used classes in the library
/// and this had no counterpart at all, so every custom shader in the crate was
/// reachable from Rust and from nowhere else — which for a package that ships
/// to npm is most of the audience.
///
/// The WGSL contract is the one documented on
/// [`crate::ShaderMaterial`]: a fragment defining
/// `@fragment fn fs_main(in: VsOut) -> @location(0) vec4<f32>`, optionally a
/// vertex stage defining `@vertex fn vs_custom`, both compiled against the
/// renderer's preamble.
///
/// ```js
/// const m = new THREE.ShaderMaterial(`
///   @fragment
///   fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
///     let tint = u_data.data[0].rgb;
///     return vec4<f32>(framebuffer_encode(apply_tone_mapping(tint)), 1.0);
///   }
/// `);
/// m.setData([1.0, 0.3, 0.1, 1.0]);
/// scene.add(new THREE.Mesh(geometry, m.material()));
/// ```
///
/// On WebGL2 there are no storage buffers, so read the storage slots through
/// `s0(i)`/`s1(i)`/`s2(i)` rather than `u_s0[i]` — those are defined on every
/// backend and fall back to a texture where they have to.
#[wasm_bindgen]
pub struct WebShaderMaterial {
    inner: crate::ShaderMaterial,
    /// `u_vol0` / `u_vol1` as set, kept apart from `inner.volumes` (which is
    /// positional and has no holes — see `sync_volumes`).
    volumes: [Option<Arc<wgpu::TextureView>>; 2],
}

#[wasm_bindgen]
impl WebShaderMaterial {
    /// `fragment` is WGSL defining `@fragment fn fs_main`.
    #[wasm_bindgen(constructor)]
    pub fn new(fragment: &str) -> WebShaderMaterial {
        WebShaderMaterial {
            inner: crate::ShaderMaterial::new(fragment),
            volumes: [None, None],
        }
    }

    /// three.js `Data3DTexture` bound as `u_vol0` (`slot` 0) or `u_vol1` (1),
    /// sampled with `u_vol_samp` or read with `textureLoad`. 8-bit data, x
    /// fastest: `channels` 1 is `RedFormat` (`R8Unorm`), 4 is `RGBAFormat`.
    ///
    /// Uploaded to the GPU the WebGPU renderer opened, so a renderer must
    /// exist first; WebGL2 has no shared device and is refused.
    #[wasm_bindgen(js_name = setVolume)]
    pub fn set_volume(
        &mut self,
        slot: u32,
        data: &[u8],
        width: u32,
        height: u32,
        depth: u32,
        channels: u32,
    ) -> Result<(), JsValue> {
        use crate::volume::VolumeFormat;
        let format = if channels == 4 {
            VolumeFormat::Rgba8Unorm
        } else {
            VolumeFormat::R8Unorm
        };
        self.put_volume(slot, width, height, depth, format, data.to_vec())
    }

    /// A `FloatType` `Data3DTexture` (one channel). Stored as `R16Float`, the
    /// float format that can be filtered everywhere: the volume slots are
    /// declared filterable, which `R32Float` is not without an extension.
    #[wasm_bindgen(js_name = setVolumeF32)]
    pub fn set_volume_f32(
        &mut self,
        slot: u32,
        data: &[f32],
        width: u32,
        height: u32,
        depth: u32,
    ) -> Result<(), JsValue> {
        let bytes = data
            .iter()
            .flat_map(|v| crate::renderer::readback::f32_to_f16(*v).to_le_bytes())
            .collect();
        self.put_volume(
            slot,
            width,
            height,
            depth,
            crate::volume::VolumeFormat::R16Float,
            bytes,
        )
    }

    /// Unbind a volume slot (it reads as zero again).
    #[wasm_bindgen(js_name = clearVolume)]
    pub fn clear_volume(&mut self, slot: u32) {
        if let Some(v) = self.volumes.get_mut(slot as usize) {
            *v = None;
        }
        let device = SHARED_BROWSER_GPU.with(|g| g.borrow().as_ref().map(|(d, _)| d.clone()));
        self.sync_volumes(device.as_deref());
    }

    /// WGSL defining `@vertex fn vs_custom(in: VsIn, ...) -> VsOut`.
    ///
    /// For anything whose position has to be computed rather than read — a
    /// camera-facing ribbon, a strand, a billboard. `standard_vertex(in)` is
    /// the built-in transform, so the usual shape is to take its output and
    /// move it.
    #[wasm_bindgen(js_name = setVertex)]
    pub fn set_vertex(&mut self, vertex: &str) {
        self.inner.vertex = Some(vertex.to_string());
    }

    /// The uniform block, as a flat array of floats read four at a time into
    /// `u_data.data[0..16]`. Anything past sixty-four floats is ignored.
    #[wasm_bindgen(js_name = setData)]
    pub fn set_data(&mut self, data: Vec<f32>) {
        self.inner.data = data
            .chunks(4)
            .map(|c| {
                let mut v = [0.0f32; 4];
                v[..c.len()].copy_from_slice(c);
                v
            })
            .collect();
    }

    /// One of the three storage slots, read as `s0(i)`, `s1(i)` or `s2(i)`.
    ///
    /// Use those rather than `u_s0[i]`: on WebGL2 there are no storage buffers
    /// and the same data arrives as a texture instead, which the accessors
    /// know about and a raw index does not.
    #[wasm_bindgen(js_name = setStorage)]
    pub fn set_storage(&mut self, slot: u32, data: Vec<f32>) {
        match slot {
            0 => self.inner.storage0 = data,
            1 => self.inner.storage1 = data,
            _ => self.inner.storage2 = data,
        }
    }

    #[wasm_bindgen(js_name = setTransparent)]
    pub fn set_transparent(&mut self, transparent: bool) {
        self.inner.transparent = transparent;
    }

    #[wasm_bindgen(js_name = setOpacity)]
    pub fn set_opacity(&mut self, opacity: f32) {
        self.inner.opacity = opacity;
    }

    /// three.js `alphaToCoverage`: under MSAA the fragment's alpha is the
    /// share of the pixel's samples it covers (return
    /// `coverage_alpha(c)`, or write samples with `frag_out`).
    #[wasm_bindgen(js_name = setAlphaToCoverage)]
    pub fn set_alpha_to_coverage(&mut self, on: bool) {
        self.inner.alpha_to_coverage = on;
    }

    /// `0` FrontSide, `1` BackSide, `2` DoubleSide — three.js's `side`.
    #[wasm_bindgen(js_name = setSide)]
    pub fn set_side(&mut self, side: u32) {
        self.inner.side = side;
    }

    /// Override depth writing: by default opaque writes and blended does not.
    #[wasm_bindgen(js_name = setDepthWrite)]
    pub fn set_depth_write(&mut self, write: bool) {
        self.inner.render_state.depth_write = Some(write);
    }

    /// Draw in the screen-space pass, with the opaque scene available to
    /// sample — what screen-space refraction needs.
    #[wasm_bindgen(js_name = setScreenSpace)]
    pub fn set_screen_space(&mut self, on: bool) {
        self.inner.screen_space = on;
    }

    /// Compile-check the shader, returning the error or `undefined`.
    ///
    /// Always `undefined` in a browser: naga is not in wgpu's wasm build, so
    /// there is nothing to check against and the browser's own WGSL compiler
    /// reports to the console instead. `validationAvailable()` says so rather
    /// than letting an always-passing check look like a passing one.
    #[wasm_bindgen(js_name = validate)]
    pub fn validate(&self) -> Option<String> {
        self.inner.validate(true).err()
    }

    /// Whether [`validate`](Self::validate) can check anything here.
    #[wasm_bindgen(js_name = validationAvailable)]
    pub fn validation_available() -> bool {
        crate::ShaderMaterial::VALIDATION_AVAILABLE
    }

    /// The material to hand to a `Mesh`.
    #[wasm_bindgen(js_name = material)]
    pub fn material(&self) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Shader(self.inner.clone())),
        }
    }
}

impl WebShaderMaterial {
    fn put_volume(
        &mut self,
        slot: u32,
        width: u32,
        height: u32,
        depth: u32,
        format: crate::volume::VolumeFormat,
        bytes: Vec<u8>,
    ) -> Result<(), JsValue> {
        use crate::volume::{Data3DTexture, GpuVolume};
        if slot > 1 {
            return Err(JsValue::from_str(
                "a ShaderMaterial has two volume slots, 0 and 1",
            ));
        }
        let expected =
            width as usize * height as usize * depth as usize * format.bytes_per_texel() as usize;
        if bytes.len() != expected {
            return Err(JsValue::from_str(&format!(
                "a {width}x{height}x{depth} {format:?} volume needs {expected} bytes, got {}",
                bytes.len()
            )));
        }
        let Some((device, queue)) = SHARED_BROWSER_GPU.with(|g| g.borrow().clone()) else {
            return Err(JsValue::from_str(
                "3D textures need the WebGPU renderer: create a WebGLRenderer before setting a volume",
            ));
        };
        let vol = GpuVolume::from_texture(
            &device,
            &queue,
            &Data3DTexture::new(width, height, depth, format, bytes),
        );
        self.volumes[slot as usize] = Some(Arc::new(vol.view));
        self.sync_volumes(Some(&device));
        Ok(())
    }

    /// `inner.volumes` from the slots. It is positional, so `u_vol1` alone
    /// needs something in slot 0: a 1x1x1 zero volume, as an empty slot reads.
    fn sync_volumes(&mut self, device: Option<&wgpu::Device>) {
        self.inner.volumes = match &self.volumes {
            [None, None] => Vec::new(),
            [Some(a), None] => vec![a.clone()],
            [a, Some(b)] => {
                let first = a.clone().or_else(|| {
                    let device = device?;
                    let v = crate::volume::GpuVolume::new(
                        device,
                        [1, 1, 1],
                        crate::volume::VolumeFormat::R8Unorm,
                    );
                    Some(Arc::new(v.view))
                });
                first.map_or_else(Vec::new, |a| vec![a, b.clone()])
            }
        };
    }
}

#[wasm_bindgen]
pub struct WebMesh {
    geometry: Arc<crate::BufferGeometry>,
    material: Arc<crate::Material>,
}

#[wasm_bindgen]
impl WebMesh {
    #[wasm_bindgen(constructor)]
    pub fn new(geom: &WebGeometry, mat: &WebMaterial) -> WebMesh {
        WebMesh {
            geometry: geom.inner.clone(),
            material: mat.inner.clone(),
        }
    }
}

#[wasm_bindgen]
pub struct WebLight {
    inner: LightInner,
}

enum LightInner {
    Ambient(crate::AmbientLight),
    Directional(crate::DirectionalLight),
    Point(crate::PointLight),
    Spot(crate::SpotLight),
    Hemisphere(crate::HemisphereLight),
    RectArea(crate::RectAreaLight),
}

#[wasm_bindgen]
impl WebLight {
    #[wasm_bindgen(js_name = ambient)]
    pub fn ambient(color: &WebColor, intensity: f32) -> WebLight {
        WebLight {
            inner: LightInner::Ambient(crate::AmbientLight::new(color.inner, intensity)),
        }
    }

    #[wasm_bindgen(js_name = directional)]
    pub fn directional(color: &WebColor, intensity: f32) -> WebLight {
        WebLight {
            inner: LightInner::Directional(crate::DirectionalLight::new(color.inner, intensity)),
        }
    }

    /// Set the direction the light shines toward (only meaningful for
    /// Directional / Spot lights). Vector does not need to be normalized.
    #[wasm_bindgen(js_name = setDirection)]
    pub fn set_direction(&mut self, x: f32, y: f32, z: f32) {
        let v = crate::Vector3::new(x, y, z);
        match &mut self.inner {
            LightInner::Directional(d) => d.direction = v,
            LightInner::Spot(s) => s.direction = v,
            _ => {}
        }
    }

    /// Diagnostic: dump kind + key state as a string. Lets parity tests assert
    /// that JS-side mutations actually landed on the wasm side.
    #[wasm_bindgen(js_name = debugString)]
    pub fn debug_string(&self) -> String {
        match &self.inner {
            LightInner::Spot(s) => format!(
                "Spot dir=({:.3},{:.3},{:.3}) intensity={} angle={} penumbra={} distance={} decay={}",
                s.direction.x, s.direction.y, s.direction.z,
                s.intensity, s.angle, s.penumbra, s.distance, s.decay,
            ),
            LightInner::Directional(d) => format!(
                "Directional dir=({:.3},{:.3},{:.3}) intensity={}",
                d.direction.x, d.direction.y, d.direction.z, d.intensity,
            ),
            LightInner::Hemisphere(h) => format!(
                "Hemisphere sky=({},{},{}) ground=({},{},{}) intensity={}",
                h.sky_color.r, h.sky_color.g, h.sky_color.b,
                h.ground_color.r, h.ground_color.g, h.ground_color.b,
                h.intensity,
            ),
            _ => "(other)".to_string(),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebColor {
    inner: crate::Color,
}

#[wasm_bindgen]
impl WebColor {
    #[wasm_bindgen(constructor)]
    pub fn new(r: f32, g: f32, b: f32) -> WebColor {
        WebColor {
            inner: crate::Color::new(r, g, b),
        }
    }

    #[wasm_bindgen(js_name = fromHex)]
    pub fn from_hex(hex: u32) -> WebColor {
        WebColor {
            inner: crate::Color::from_hex(hex),
        }
    }

    /// A CSS colour string — hex (`#rgb` to `#rrggbbaa`), the named colours,
    /// `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`,
    /// `color()` — as linear RGB, or `undefined` if it is not one. The alpha
    /// is dropped; `cssAlpha` reads it.
    #[wasm_bindgen(js_name = fromCss)]
    pub fn from_css(css: &str) -> Option<WebColor> {
        crate::Color::from_css(css)
            .ok()
            .map(|inner| WebColor { inner })
    }

    /// The alpha of a CSS colour string (1 when it gives none), or
    /// `undefined` if it is not one.
    #[wasm_bindgen(js_name = cssAlpha)]
    pub fn css_alpha(css: &str) -> Option<f32> {
        crate::Color::parse_css(css).ok().map(|(_, a)| a)
    }
}

/// three.js's shadow-map type numbers as this renderer's filters.
fn shadow_type_of(kind: u32) -> crate::lights::ShadowType {
    use crate::lights::ShadowType::*;
    match kind {
        0 => Basic,
        2 => PcfSoft,
        3 => Pcss,
        _ => Pcf,
    }
}

/// Data to colour — `threers::math::ColorScale`, d3's sequential, diverging,
/// quantize, quantile and threshold scales over any named scheme.
#[wasm_bindgen]
pub struct WebColorScale {
    inner: crate::math::ColorScale,
}

fn named_ramp(name: &str) -> Result<crate::math::ColorRamp, JsValue> {
    crate::math::ColorRamp::named(name)
        .ok_or_else(|| JsValue::from_str(&format!("no colour scheme named {name}")))
}

#[wasm_bindgen]
impl WebColorScale {
    /// `lo..hi` along the named scheme (`"viridis"`, `"blues"`, `"RdBu"`,
    /// `"interpolateSpectral"`, …).
    pub fn sequential(scheme: &str, lo: f32, hi: f32) -> Result<WebColorScale, JsValue> {
        Ok(Self {
            inner: crate::math::ColorScale::sequential(named_ramp(scheme)?, lo, hi),
        })
    }

    /// Away from `mid` both ways.
    pub fn diverging(scheme: &str, lo: f32, mid: f32, hi: f32) -> Result<WebColorScale, JsValue> {
        Ok(Self {
            inner: crate::math::ColorScale::diverging(named_ramp(scheme)?, lo, mid, hi),
        })
    }

    /// `classes` equal-width bins.
    pub fn quantize(
        scheme: &str,
        lo: f32,
        hi: f32,
        classes: usize,
    ) -> Result<WebColorScale, JsValue> {
        Ok(Self {
            inner: crate::math::ColorScale::quantize(named_ramp(scheme)?, lo, hi, classes),
        })
    }

    /// `classes` bins of equal count of `data`.
    pub fn quantile(scheme: &str, data: &[f32], classes: usize) -> Result<WebColorScale, JsValue> {
        Ok(Self {
            inner: crate::math::ColorScale::quantile(named_ramp(scheme)?, data, classes),
        })
    }

    /// Explicit class breaks.
    pub fn threshold(scheme: &str, breaks: Vec<f32>) -> Result<WebColorScale, JsValue> {
        Ok(Self {
            inner: crate::math::ColorScale::threshold(named_ramp(scheme)?, breaks),
        })
    }

    /// Logarithmic in `base`.
    pub fn log(self, base: f32) -> WebColorScale {
        Self {
            inner: self.inner.log(base),
        }
    }

    /// By the square root.
    pub fn sqrt(self) -> WebColorScale {
        Self {
            inner: self.inner.sqrt(),
        }
    }

    /// By a power.
    pub fn pow(self, exponent: f32) -> WebColorScale {
        Self {
            inner: self.inner.pow(exponent),
        }
    }

    /// Symmetric log, linear within `constant` of zero.
    pub fn symlog(self, constant: f32) -> WebColorScale {
        Self {
            inner: self.inner.symlog(constant),
        }
    }

    /// The scheme reversed, end to end.
    pub fn reversed(self) -> WebColorScale {
        let ramp = self.inner.ramp().clone().reversed();
        let domain = self.inner.domain().to_vec();
        let mut inner = if domain.len() == 3 {
            crate::math::ColorScale::diverging(ramp, domain[0], domain[1], domain[2])
        } else {
            crate::math::ColorScale::sequential(ramp, domain[0], domain[1])
        };
        inner = match self.inner.kind().clone() {
            crate::math::ScaleKind::Log { base } => inner.log(base),
            crate::math::ScaleKind::Pow { exponent } => inner.pow(exponent),
            crate::math::ScaleKind::Symlog { constant } => inner.symlog(constant),
            _ => return Self { inner: self.inner },
        };
        Self { inner }
    }

    /// The colour for `value`, linear RGB.
    pub fn map(&self, value: f32) -> WebColor {
        WebColor {
            inner: self.inner.map(value),
        }
    }

    /// Colours for `values` as sRGB bytes, four to a value — straight into a
    /// colour attribute or a data texture.
    #[wasm_bindgen(js_name = mapRgba8)]
    pub fn map_rgba8(&self, values: &[f32]) -> Vec<u8> {
        self.inner.map_rgba8(values).into_iter().flatten().collect()
    }

    /// A legend's rows, `[from, to, r, g, b]` each (linear RGB), `n` steps
    /// for a continuous scale.
    pub fn legend(&self, n: usize) -> Vec<f32> {
        self.inner
            .legend(n)
            .into_iter()
            .flat_map(|(a, b, c)| [a, b, c.r, c.g, c.b])
            .collect()
    }

    /// Every scheme name the scales know.
    #[wasm_bindgen(js_name = schemeNames)]
    pub fn scheme_names() -> Vec<String> {
        crate::math::ColorRamp::scheme_names()
            .into_iter()
            .map(|(n, _)| n.to_string())
            .collect()
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebVector3 {
    inner: crate::Vector3,
}

#[wasm_bindgen]
impl WebVector3 {
    #[wasm_bindgen(constructor)]
    pub fn new(x: f32, y: f32, z: f32) -> WebVector3 {
        WebVector3 {
            inner: crate::Vector3::new(x, y, z),
        }
    }

    #[wasm_bindgen(getter)]
    pub fn x(&self) -> f32 {
        self.inner.x
    }
    #[wasm_bindgen(getter)]
    pub fn y(&self) -> f32 {
        self.inner.y
    }
    #[wasm_bindgen(getter)]
    pub fn z(&self) -> f32 {
        self.inner.z
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebEuler {
    inner: crate::Euler,
}

#[wasm_bindgen]
impl WebEuler {
    #[wasm_bindgen(constructor)]
    pub fn new(x: f32, y: f32, z: f32) -> WebEuler {
        WebEuler {
            inner: crate::Euler::new(x, y, z),
        }
    }

    #[wasm_bindgen(getter)]
    pub fn x(&self) -> f32 {
        self.inner.x
    }
    #[wasm_bindgen(getter)]
    pub fn y(&self) -> f32 {
        self.inner.y
    }
    #[wasm_bindgen(getter)]
    pub fn z(&self) -> f32 {
        self.inner.z
    }
}

// JS console logging convenience.
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    pub fn log(s: &str);
}

// ======================================================================
//                              MATH
// ======================================================================

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebVector2 {
    pub x: f32,
    pub y: f32,
}
#[wasm_bindgen]
impl WebVector2 {
    #[wasm_bindgen(constructor)]
    pub fn new(x: f32, y: f32) -> WebVector2 {
        WebVector2 { x, y }
    }
    #[wasm_bindgen(js_name = lengthSq)]
    pub fn length_sq(&self) -> f32 {
        self.x * self.x + self.y * self.y
    }
    pub fn length(&self) -> f32 {
        self.length_sq().sqrt()
    }
    pub fn dot(&self, o: &WebVector2) -> f32 {
        self.x * o.x + self.y * o.y
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebVector4 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub w: f32,
}
#[wasm_bindgen]
impl WebVector4 {
    #[wasm_bindgen(constructor)]
    pub fn new(x: f32, y: f32, z: f32, w: f32) -> WebVector4 {
        WebVector4 { x, y, z, w }
    }
    pub fn length(&self) -> f32 {
        (self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w).sqrt()
    }
}

#[wasm_bindgen]
#[derive(Clone)]
pub struct WebMatrix3 {
    inner: crate::Matrix3,
}
#[wasm_bindgen]
impl WebMatrix3 {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebMatrix3 {
        WebMatrix3 {
            inner: crate::Matrix3::identity(),
        }
    }
    pub fn identity() -> WebMatrix3 {
        WebMatrix3 {
            inner: crate::Matrix3::identity(),
        }
    }
    pub fn elements(&self) -> Vec<f32> {
        self.inner.elements.to_vec()
    }
}

#[wasm_bindgen]
#[derive(Clone)]
pub struct WebMatrix4 {
    pub(crate) inner: crate::Matrix4,
}
#[wasm_bindgen]
impl WebMatrix4 {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebMatrix4 {
        WebMatrix4 {
            inner: crate::Matrix4::identity(),
        }
    }
    pub fn identity() -> WebMatrix4 {
        WebMatrix4 {
            inner: crate::Matrix4::identity(),
        }
    }
    pub fn elements(&self) -> Vec<f32> {
        self.inner.elements.to_vec()
    }
    #[wasm_bindgen(js_name = makePerspective)]
    pub fn make_perspective(fov: f32, aspect: f32, near: f32, far: f32) -> WebMatrix4 {
        WebMatrix4 {
            inner: crate::Matrix4::perspective(fov, aspect, near, far),
        }
    }
    pub fn invert(&self) -> WebMatrix4 {
        WebMatrix4 {
            inner: self.inner.invert(),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebQuaternion {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub w: f32,
}
#[wasm_bindgen]
impl WebQuaternion {
    #[wasm_bindgen(constructor)]
    pub fn new(x: f32, y: f32, z: f32, w: f32) -> WebQuaternion {
        WebQuaternion { x, y, z, w }
    }
    pub fn identity() -> WebQuaternion {
        WebQuaternion {
            x: 0.0,
            y: 0.0,
            z: 0.0,
            w: 1.0,
        }
    }
    #[wasm_bindgen(js_name = setFromEuler)]
    pub fn set_from_euler(e: &WebEuler) -> WebQuaternion {
        let q = e.inner.to_quaternion();
        WebQuaternion {
            x: q.x,
            y: q.y,
            z: q.z,
            w: q.w,
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebBox2 {
    inner: crate::Box2,
}
#[wasm_bindgen]
impl WebBox2 {
    #[wasm_bindgen(constructor)]
    pub fn new(min: &WebVector2, max: &WebVector2) -> WebBox2 {
        WebBox2 {
            inner: crate::Box2::new(
                crate::Vector2::new(min.x, min.y),
                crate::Vector2::new(max.x, max.y),
            ),
        }
    }
    pub fn empty() -> WebBox2 {
        WebBox2 {
            inner: crate::Box2::empty(),
        }
    }
    #[wasm_bindgen(js_name = isEmpty)]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebBox3 {
    pub(crate) inner: crate::Box3,
}
#[wasm_bindgen]
impl WebBox3 {
    #[wasm_bindgen(constructor)]
    pub fn new(min: &WebVector3, max: &WebVector3) -> WebBox3 {
        WebBox3 {
            inner: crate::Box3::new(min.inner, max.inner),
        }
    }
    pub fn empty() -> WebBox3 {
        WebBox3 {
            inner: crate::Box3::empty(),
        }
    }
    #[wasm_bindgen(js_name = isEmpty)]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
    #[wasm_bindgen(js_name = containsPoint)]
    pub fn contains_point(&self, p: &WebVector3) -> bool {
        self.inner.contains_point(p.inner)
    }
    #[wasm_bindgen(js_name = intersectsBox)]
    pub fn intersects_box(&self, o: &WebBox3) -> bool {
        self.inner.intersects_box(&o.inner)
    }
    pub fn center(&self) -> WebVector3 {
        WebVector3 {
            inner: self.inner.center(),
        }
    }
    pub fn size(&self) -> WebVector3 {
        WebVector3 {
            inner: self.inner.size(),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebSphere {
    inner: crate::Sphere,
}
#[wasm_bindgen]
impl WebSphere {
    #[wasm_bindgen(constructor)]
    pub fn new(center: &WebVector3, radius: f32) -> WebSphere {
        WebSphere {
            inner: crate::Sphere::new(center.inner, radius),
        }
    }
    #[wasm_bindgen(js_name = containsPoint)]
    pub fn contains_point(&self, p: &WebVector3) -> bool {
        self.inner.contains_point(p.inner)
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebRay {
    inner: crate::Ray,
}
#[wasm_bindgen]
impl WebRay {
    #[wasm_bindgen(constructor)]
    pub fn new(origin: &WebVector3, direction: &WebVector3) -> WebRay {
        WebRay {
            inner: crate::Ray::new(origin.inner, direction.inner),
        }
    }
    pub fn at(&self, t: f32) -> WebVector3 {
        WebVector3 {
            inner: self.inner.at(t),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebPlane {
    inner: crate::Plane,
}
#[wasm_bindgen]
impl WebPlane {
    #[wasm_bindgen(constructor)]
    pub fn new(normal: &WebVector3, constant: f32) -> WebPlane {
        WebPlane {
            inner: crate::Plane::new(normal.inner, constant),
        }
    }
    #[wasm_bindgen(js_name = distanceToPoint)]
    pub fn distance_to_point(&self, p: &WebVector3) -> f32 {
        self.inner.distance_to_point(p.inner)
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebTriangle {
    inner: crate::Triangle,
}
#[wasm_bindgen]
impl WebTriangle {
    #[wasm_bindgen(constructor)]
    pub fn new(a: &WebVector3, b: &WebVector3, c: &WebVector3) -> WebTriangle {
        WebTriangle {
            inner: crate::Triangle::new(a.inner, b.inner, c.inner),
        }
    }
    pub fn area(&self) -> f32 {
        self.inner.area()
    }
    pub fn normal(&self) -> WebVector3 {
        WebVector3 {
            inner: self.inner.normal(),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone)]
pub struct WebFrustum {
    inner: crate::Frustum,
}
#[wasm_bindgen]
impl WebFrustum {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebFrustum {
        WebFrustum {
            inner: crate::Frustum::default(),
        }
    }
    #[wasm_bindgen(js_name = setFromProjectionMatrix)]
    pub fn set_from_projection_matrix(m: &WebMatrix4) -> WebFrustum {
        WebFrustum {
            inner: crate::Frustum::from_projection_matrix(&m.inner),
        }
    }
    #[wasm_bindgen(js_name = containsPoint)]
    pub fn contains_point(&self, p: &WebVector3) -> bool {
        self.inner.contains_point(p.inner)
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebSpherical {
    inner: crate::Spherical,
}
#[wasm_bindgen]
impl WebSpherical {
    #[wasm_bindgen(constructor)]
    pub fn new(radius: f32, phi: f32, theta: f32) -> WebSpherical {
        WebSpherical {
            inner: crate::Spherical::new(radius, phi, theta),
        }
    }
    #[wasm_bindgen(js_name = setFromVector3)]
    pub fn set_from_vector3(v: &WebVector3) -> WebSpherical {
        WebSpherical {
            inner: crate::Spherical::from_vector3(v.inner),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebCylindrical {
    inner: crate::Cylindrical,
}
#[wasm_bindgen]
impl WebCylindrical {
    #[wasm_bindgen(constructor)]
    pub fn new(radius: f32, theta: f32, y: f32) -> WebCylindrical {
        WebCylindrical {
            inner: crate::Cylindrical::new(radius, theta, y),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Copy)]
pub struct WebLine3 {
    inner: crate::Line3,
}
#[wasm_bindgen]
impl WebLine3 {
    #[wasm_bindgen(constructor)]
    pub fn new(start: &WebVector3, end: &WebVector3) -> WebLine3 {
        WebLine3 {
            inner: crate::Line3::new(start.inner, end.inner),
        }
    }
    pub fn distance(&self) -> f32 {
        self.inner.distance()
    }
    pub fn center(&self) -> WebVector3 {
        WebVector3 {
            inner: self.inner.center(),
        }
    }
}

// ======================================================================
//                          GEOMETRIES (extras)
// ======================================================================

#[wasm_bindgen]
impl WebGeometry {
    #[wasm_bindgen(js_name = circle)]
    pub fn circle(radius: f32, segments: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::CircleGeometry::new(
                radius,
                segments.max(3),
                0.0,
                std::f32::consts::PI * 2.0,
            )),
        }
    }
    #[wasm_bindgen(js_name = ring)]
    pub fn ring(inner: f32, outer: f32, theta_segments: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::RingGeometry::new(
                inner,
                outer,
                theta_segments.max(3),
                1,
                0.0,
                std::f32::consts::PI * 2.0,
            )),
        }
    }
    #[wasm_bindgen(js_name = cone)]
    pub fn cone(radius: f32, height: f32, radial_segments: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::ConeGeometry::new(
                radius,
                height,
                radial_segments.max(3),
                1,
                false,
                0.0,
                std::f32::consts::PI * 2.0,
            )),
        }
    }
    #[wasm_bindgen(js_name = torusKnot)]
    pub fn torus_knot(
        radius: f32,
        tube: f32,
        tubular_segments: usize,
        radial_segments: usize,
        p: u32,
        q: u32,
    ) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::TorusKnotGeometry::new(
                radius,
                tube,
                tubular_segments.max(3),
                radial_segments.max(3),
                p,
                q,
            )),
        }
    }
    #[wasm_bindgen(js_name = capsule)]
    pub fn capsule(
        radius: f64,
        length: f64,
        cap_segments: usize,
        radial_segments: usize,
    ) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::CapsuleGeometry::with_f64(
                radius,
                length,
                cap_segments.max(1),
                radial_segments.max(3),
            )),
        }
    }
    #[wasm_bindgen(js_name = tetrahedron)]
    pub fn tetrahedron(radius: f32, detail: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::TetrahedronGeometry::new(radius, detail)),
        }
    }
    #[wasm_bindgen(js_name = octahedron)]
    pub fn octahedron(radius: f32, detail: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::OctahedronGeometry::new(radius, detail)),
        }
    }
    #[wasm_bindgen(js_name = icosahedron)]
    pub fn icosahedron(radius: f32, detail: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::IcosahedronGeometry::new(radius, detail)),
        }
    }
    #[wasm_bindgen(js_name = dodecahedron)]
    pub fn dodecahedron(radius: f32, detail: usize) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::DodecahedronGeometry::new(radius, detail)),
        }
    }
    #[wasm_bindgen(js_name = boxLine)]
    pub fn box_line(w: f32, h: f32, d: f32) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::BoxLineGeometry::new(w, h, d)),
        }
    }

    /// Clone into a `WebBufferGeometry` handle (same underlying data).
    #[wasm_bindgen(js_name = toBufferGeometry)]
    pub fn to_buffer_geometry(&self) -> WebBufferGeometry {
        WebBufferGeometry {
            inner: self.inner.clone(),
        }
    }
}

// ======================================================================
//                            MATERIALS (extras)
// ======================================================================

#[wasm_bindgen]
impl WebMaterial {
    #[wasm_bindgen(js_name = phong)]
    pub fn phong(color: &WebColor) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Phong(crate::PhongMaterial::new(
                color.inner,
            ))),
        }
    }
    #[wasm_bindgen(js_name = physical)]
    pub fn physical(
        color: &WebColor,
        roughness: f32,
        metalness: f32,
        clearcoat: f32,
        clearcoat_roughness: f32,
    ) -> WebMaterial {
        let mut m = crate::PhysicalMaterial::new(color.inner);
        m.roughness = roughness;
        m.metalness = metalness;
        m.clearcoat = clearcoat;
        m.clearcoat_roughness = clearcoat_roughness;
        WebMaterial {
            inner: Arc::new(crate::Material::Physical(m)),
        }
    }
    #[wasm_bindgen(js_name = normalMat)]
    pub fn normal_mat() -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Normal(crate::NormalMaterial::new())),
        }
    }
    #[wasm_bindgen(js_name = depth)]
    pub fn depth() -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Depth(crate::DepthMaterial::new())),
        }
    }
    #[wasm_bindgen(js_name = toon)]
    pub fn toon(color: &WebColor) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Toon(crate::ToonMaterial::new(color.inner))),
        }
    }
    #[wasm_bindgen(js_name = lineDashed)]
    pub fn line_dashed(color: &WebColor, scale: f32, dash_size: f32, gap_size: f32) -> WebMaterial {
        let mut m = crate::LineBasicMaterial::new(color.inner);
        m.dashed = true;
        m.dash_scale = scale;
        m.dash_size = dash_size;
        m.gap_size = gap_size;
        WebMaterial {
            inner: Arc::new(crate::Material::Line(m)),
        }
    }
    #[wasm_bindgen(js_name = line)]
    pub fn line(color: &WebColor) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Line(crate::LineBasicMaterial::new(
                color.inner,
            ))),
        }
    }
    #[wasm_bindgen(js_name = points)]
    pub fn points(color: &WebColor, size: f32) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Points(crate::PointsMaterial::new(
                color.inner,
                size,
            ))),
        }
    }
    #[wasm_bindgen(js_name = sprite)]
    pub fn sprite(color: &WebColor) -> WebMaterial {
        WebMaterial {
            inner: Arc::new(crate::Material::Sprite(crate::SpriteMaterial::new(
                color.inner,
            ))),
        }
    }
}

// ======================================================================
//                              LIGHTS (extras)
// ======================================================================

#[wasm_bindgen]
impl WebLight {
    #[wasm_bindgen(js_name = point)]
    pub fn point(color: &WebColor, intensity: f32, distance: f32, decay: f32) -> WebLight {
        let mut p = crate::PointLight::new(color.inner, intensity);
        p.distance = distance;
        p.decay = decay;
        WebLight {
            inner: LightInner::Point(p),
        }
    }

    // Adjust intensity in-place (three.js .intensity = ...).
    #[wasm_bindgen(js_name = setIntensity)]
    pub fn set_intensity(&mut self, intensity: f32) {
        match &mut self.inner {
            LightInner::Ambient(l) => l.intensity = intensity,
            LightInner::Directional(l) => l.intensity = intensity,
            LightInner::Point(l) => l.intensity = intensity,
            LightInner::Spot(l) => l.intensity = intensity,
            LightInner::Hemisphere(l) => l.intensity = intensity,
            LightInner::RectArea(l) => l.intensity = intensity,
        }
    }

    /// Toggle whether this light casts shadows. Only Directional / Spot /
    /// Point variants honor it; every one that does gets a shadow map of its
    /// own.
    #[wasm_bindgen(js_name = setCastShadow)]
    pub fn set_cast_shadow(&mut self, cast: bool) {
        match &mut self.inner {
            LightInner::Directional(l) => l.cast_shadow = cast,
            LightInner::Spot(l) => l.cast_shadow = cast,
            LightInner::Point(l) => l.cast_shadow = cast,
            _ => {}
        }
    }

    /// Orthographic shadow frustum (three.js `light.shadow.camera.*`).
    #[wasm_bindgen(js_name = setShadowCamera)]
    pub fn set_shadow_camera(
        &mut self,
        left: f32,
        right: f32,
        top: f32,
        bottom: f32,
        near: f32,
        far: f32,
    ) {
        let size = ((right - left).abs().max((top - bottom).abs())) * 0.5;
        let settings = crate::ShadowSettings {
            camera_size: size.max(0.1),
            camera_near: near,
            camera_far: far,
            ..match &self.inner {
                LightInner::Directional(l) => l.shadow,
                LightInner::Spot(l) => l.shadow,
                LightInner::Point(l) => l.shadow,
                _ => crate::ShadowSettings::default(),
            }
        };
        match &mut self.inner {
            LightInner::Directional(l) => l.shadow = settings,
            LightInner::Spot(l) => l.shadow = settings,
            LightInner::Point(l) => l.shadow = settings,
            _ => {}
        }
    }
    /// The light's shadow settings as this renderer holds them:
    /// `[bias, normalBias, radius, mapSize]` — bias positive, the depth this
    /// renderer subtracts (see `setShadowParams`). Empty for a light that
    /// casts none.
    #[wasm_bindgen(getter, js_name = shadowSettings)]
    pub fn shadow_settings(&self) -> Vec<f32> {
        let shadow = match &self.inner {
            LightInner::Directional(l) => &l.shadow,
            LightInner::Spot(l) => &l.shadow,
            LightInner::Point(l) => &l.shadow,
            _ => return Vec::new(),
        };
        vec![
            shadow.bias,
            shadow.normal_bias,
            shadow.radius,
            shadow.map_size as f32,
        ]
    }

    /// Cascaded shadow maps for a directional light
    /// (`ShadowSettings::cascades`): `count` (1 to 4) maps over the camera's
    /// view out to `distance` (0: its far plane), split between even and
    /// logarithmic by `split` (0 to 1).
    #[wasm_bindgen(js_name = setShadowCascades)]
    pub fn set_shadow_cascades(&mut self, count: u32, distance: f32, split: f32) {
        if let LightInner::Directional(l) = &mut self.inner {
            l.shadow.cascades = count.clamp(1, 4);
            l.shadow.cascade_distance = distance.max(0.0);
            l.shadow.cascade_split = split.clamp(0.0, 1.0);
        }
    }

    /// This light's size for soft shadows (`ShadowSettings::light_size`) and
    /// its own filter, overriding the renderer's (three.js shadow-map type
    /// numbers; anything else to follow the renderer).
    #[wasm_bindgen(js_name = setShadowSoftness)]
    pub fn set_shadow_softness(&mut self, light_size: f32, filter: i32) {
        let shadow = match &mut self.inner {
            LightInner::Directional(l) => &mut l.shadow,
            LightInner::Spot(l) => &mut l.shadow,
            LightInner::Point(l) => &mut l.shadow,
            _ => return,
        };
        shadow.light_size = light_size.max(0.0);
        shadow.filter = (0..=3)
            .contains(&filter)
            .then(|| shadow_type_of(filter as u32));
    }

    /// three.js `light.shadow.mapSize`: the shadow map's side in texels (the
    /// larger of width and height; the maps are square), for directional and
    /// spot lights. A point light's cube faces are fixed at 512.
    #[wasm_bindgen(js_name = setShadowMapSize)]
    pub fn set_shadow_map_size(&mut self, width: u32, height: u32) {
        let size = width.max(height).max(1);
        match &mut self.inner {
            LightInner::Directional(l) => l.shadow.map_size = size,
            LightInner::Spot(l) => l.shadow.map_size = size,
            LightInner::Point(l) => l.shadow.map_size = size,
            _ => {}
        }
    }

    /// three.js `light.shadow.bias`, `.normalBias` and `.radius`: the depth
    /// offset, the offset along the surface normal, and how soft the edge is
    /// (the radius, in shadow-map texels, it is filtered over; 1 by default).
    #[wasm_bindgen(js_name = setShadowParams)]
    pub fn set_shadow_params(&mut self, bias: f32, normal_bias: f32, radius: f32) {
        let shadow = match &mut self.inner {
            LightInner::Directional(l) => &mut l.shadow,
            LightInner::Spot(l) => &mut l.shadow,
            LightInner::Point(l) => &mut l.shadow,
            _ => return,
        };
        // three.js adds its bias to the shadow coordinate, so the usual
        // value is negative; this renderer subtracts a positive one.
        shadow.bias = (-bias).max(0.0);
        shadow.normal_bias = normal_bias.max(0.0);
        shadow.radius = radius.max(0.0);
    }

    #[wasm_bindgen(js_name = spot)]
    pub fn spot(
        color: &WebColor,
        intensity: f32,
        distance: f32,
        angle: f32,
        penumbra: f32,
        decay: f32,
    ) -> WebLight {
        let mut s = crate::SpotLight::new(color.inner, intensity);
        s.distance = distance;
        s.angle = angle;
        s.penumbra = penumbra;
        s.decay = decay;
        WebLight {
            inner: LightInner::Spot(s),
        }
    }
    #[wasm_bindgen(js_name = hemisphere)]
    pub fn hemisphere(sky: &WebColor, ground: &WebColor, intensity: f32) -> WebLight {
        let h = crate::HemisphereLight::new(sky.inner, ground.inner, intensity);
        WebLight {
            inner: LightInner::Hemisphere(h),
        }
    }
    #[wasm_bindgen(js_name = rectArea)]
    pub fn rect_area(color: &WebColor, intensity: f32, width: f32, height: f32) -> WebLight {
        let r = crate::RectAreaLight::new(color.inner, intensity, width, height);
        WebLight {
            inner: LightInner::RectArea(r),
        }
    }
}

// ======================================================================
//                            TEXTURES
// ======================================================================

#[wasm_bindgen]
pub struct WebTexture {
    inner: Arc<crate::Texture>,
}
#[wasm_bindgen]
impl WebTexture {
    /// three.js `texture.colorSpace`: `true` for `SRGBColorSpace` (the bytes
    /// are sRGB-encoded and the sampler decodes them), `false` for none or
    /// linear. Applies to the 8-bit RGBA formats; others are left as they are.
    /// A material bound to the texture before the change keeps the old one
    /// until it is bound again.
    #[wasm_bindgen(js_name = setSrgb)]
    pub fn set_srgb(&mut self, srgb: bool) {
        use crate::TextureFormat as F;
        let want = if srgb {
            F::Rgba8UnormSrgb
        } else {
            F::Rgba8Unorm
        };
        if matches!(self.inner.format, F::Rgba8Unorm | F::Rgba8UnormSrgb)
            && self.inner.format != want
        {
            Arc::make_mut(&mut self.inner).format = want;
        }
    }
    #[wasm_bindgen(constructor)]
    pub fn new(width: u32, height: u32, data: Vec<u8>) -> WebTexture {
        WebTexture {
            inner: Arc::new(crate::Texture::new(
                width,
                height,
                crate::TextureFormat::Rgba8UnormSrgb,
                data,
            )),
        }
    }
    #[wasm_bindgen(js_name = solid)]
    pub fn solid(r: u8, g: u8, b: u8, a: u8) -> WebTexture {
        WebTexture {
            inner: Arc::new(crate::Texture::solid(
                [r, g, b, a],
                crate::TextureFormat::Rgba8UnormSrgb,
            )),
        }
    }
    /// Set sampler filter/wrap — see [`set_texture_filters`].
    #[wasm_bindgen(js_name = setFilters)]
    pub fn set_filters(&mut self, mag: u32, min: u32, wrap_s: u32, wrap_t: u32) {
        set_texture_filters(Arc::make_mut(&mut self.inner), mag, min, wrap_s, wrap_t);
    }

    /// Resample this equirectangular map onto the six faces of a cube.
    ///
    /// A cube has no poles. An equirectangular map converges every longitude
    /// onto one texel at each end, and anything with width near there fans out
    /// radially when it is wrapped on a sphere; a cube face is a plane, its
    /// texels are near enough uniform everywhere, and no point on it is
    /// special. Returns the faces in `+X, -X, +Y, -Y, +Z, -Z` order, which is
    /// the order `planet::CUBE_FACES` places them in.
    ///
    /// `face_size` of 0 picks a quarter of the map's width — four faces carry
    /// the 360 degrees the map spends its full width on, so that is lossless at
    /// the equator and a gain toward the poles.
    #[cfg(feature = "planet")]
    #[wasm_bindgen(js_name = cubeFaces)]
    pub fn cube_faces(&self, face_size: u32) -> js_sys::Array {
        let n = if face_size == 0 {
            (self.inner.width / 4).clamp(64, 4096)
        } else {
            face_size
        };
        let out = js_sys::Array::new();
        for face in crate::planet::equirect_to_cube_faces(&self.inner, n) {
            out.push(&JsValue::from(WebTexture {
                inner: Arc::new(face),
            }));
        }
        out
    }

    /// A second handle on the same pixels, carrying its own UV transform.
    ///
    /// `Texture`'s bytes live behind their own `Arc`, so this clones a handle
    /// and not an image — and the renderer keys its GPU cache on those bytes,
    /// so every view of one buffer shares a single upload between them.
    ///
    /// This is what lets a body split into patches for tile streaming still
    /// cost one texture per map at level 0: eight patches over one map, each
    /// addressing its own quarter through `offset`/`repeat`, instead of eight
    /// sliced copies uploaded separately.
    #[wasm_bindgen(js_name = view)]
    pub fn view(&self, ox: f32, oy: f32, rx: f32, ry: f32) -> WebDataTexture {
        let mut inner = (*self.inner).clone();
        inner.offset = crate::math::Vector2::new(ox, oy);
        inner.repeat = crate::math::Vector2::new(rx, ry);
        WebDataTexture {
            inner: Arc::new(inner),
        }
    }

    /// three.js `Texture.offset` / `Texture.repeat` — the UV sub-rectangle this
    /// texture covers. What lets several meshes share one atlas.
    #[wasm_bindgen(js_name = setUvTransform)]
    pub fn set_uv_transform(&mut self, ox: f32, oy: f32, rx: f32, ry: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        inner.offset = crate::math::Vector2::new(ox, oy);
        inner.repeat = crate::math::Vector2::new(rx, ry);
        inner.rotation = 0.0;
        inner.center = crate::math::Vector2::ZERO;
        inner.matrix_auto_update = true;
    }

    /// three.js `Texture.channel`: the uv set the texture is read through —
    /// 0 the geometry's `uv`, 1–3 its `uv1`, `uv2`, `uv3`.
    #[wasm_bindgen(js_name = setChannel)]
    pub fn set_channel(&mut self, channel: u32) {
        Arc::make_mut(&mut self.inner).channel = channel.min(3);
    }

    /// three.js `Texture.matrix` as its top two rows, `(a, b, c)` and
    /// `(d, e, f)`: `u' = a·u + b·v + c`, `v' = d·u + e·v + f`. What
    /// `offset`, `repeat`, `rotation` and `center` compose to
    /// (`Matrix3.setUvTransform`), or a matrix set by hand.
    #[wasm_bindgen(js_name = setUvMatrix)]
    pub fn set_uv_matrix(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
        set_uv_matrix(Arc::make_mut(&mut self.inner), [a, b, c, d, e, f]);
    }
    pub fn width(&self) -> u32 {
        self.inner.width
    }
    pub fn height(&self) -> u32 {
        self.inner.height
    }
}

#[wasm_bindgen]
pub struct WebCubeTexture {
    inner: Arc<crate::CubeTexture>,
}
#[wasm_bindgen]
impl WebCubeTexture {
    #[wasm_bindgen(constructor)]
    pub fn new(
        size: u32,
        px: Vec<u8>,
        nx: Vec<u8>,
        py: Vec<u8>,
        ny: Vec<u8>,
        pz: Vec<u8>,
        nz: Vec<u8>,
    ) -> WebCubeTexture {
        WebCubeTexture {
            inner: Arc::new(crate::CubeTexture::new(
                size,
                crate::TextureFormat::Rgba8UnormSrgb,
                [px, nx, py, ny, pz, nz],
            )),
        }
    }

    #[wasm_bindgen(getter)]
    pub fn size(&self) -> u32 {
        self.inner.size
    }

    /// three.js `cubeTexture.magFilter` / `minFilter`, in its constants (see
    /// `three_filter`).
    #[wasm_bindgen(js_name = setFilters)]
    pub fn set_filters(&mut self, mag: u32, min: u32) {
        let c = Arc::make_mut(&mut self.inner);
        c.mag_filter = three_filter(mag).0;
        (c.min_filter, c.mipmap_filter) = three_filter(min);
    }

    /// three.js `cubeTexture.colorSpace`: `true` (`SRGBColorSpace`, what
    /// `CubeTextureLoader` sets) decodes the faces on sampling; `false` reads
    /// them as they are.
    #[wasm_bindgen(js_name = setSrgb)]
    pub fn set_srgb(&mut self, srgb: bool) {
        Arc::make_mut(&mut self.inner).format = if srgb {
            crate::TextureFormat::Rgba8UnormSrgb
        } else {
            crate::TextureFormat::Rgba8Unorm
        };
    }

    /// three.js `cubeTexture.mapping`: `true` for `CubeRefractionMapping`,
    /// `false` for the default `CubeReflectionMapping`.
    #[wasm_bindgen(js_name = setRefraction)]
    pub fn set_refraction(&mut self, refraction: bool) {
        Arc::make_mut(&mut self.inner).mapping = if refraction {
            crate::textures::CubeMapping::Refraction
        } else {
            crate::textures::CubeMapping::Reflection
        };
    }

    #[wasm_bindgen(js_name = sampleCubeUvEnv)]
    pub fn sample_cube_uv_env(&self, dx: f32, dy: f32, dz: f32, roughness: f32) -> Vec<f32> {
        let Some(atlas) = self.inner.cube_uv_atlas.as_ref() else {
            return vec![0.0, 0.0, 0.0];
        };
        crate::extras::cube_uv::sample_cube_uv_env(atlas, [dx, dy, dz], roughness).to_vec()
    }
}

#[wasm_bindgen]
pub struct WebPmremGenerator;
#[wasm_bindgen]
impl WebPmremGenerator {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebPmremGenerator {
        WebPmremGenerator
    }

    /// Prefilter `cube` into a PMREM mip chain at `size` and return a CubeTexture wrapper.
    #[wasm_bindgen(js_name = fromCubemap)]
    pub fn from_cubemap(cube: &WebCubeTexture, size: u32) -> WebCubeTexture {
        let pmrem = crate::PmremGenerator::generate_pmrem(&cube.inner, size.max(1));
        WebCubeTexture {
            inner: Arc::new(pmrem),
        }
    }

    /// three.js's `pmrem.fromScene(new RoomEnvironment())`: the room built
    /// exactly (`extras::RoomEnvironment`, HDR) and prefiltered at `size`.
    #[wasm_bindgen(js_name = roomEnvironment)]
    pub fn room_environment(size: u32) -> WebCubeTexture {
        WebCubeTexture {
            inner: crate::extras::RoomEnvironment::pmrem(size.clamp(16, 256)),
        }
    }

    /// Convert an equirectangular RGBA8 texture into a PMREM cubemap.
    #[wasm_bindgen(js_name = fromEquirectangular)]
    pub fn from_equirectangular(
        data: Vec<u8>,
        src_w: u32,
        src_h: u32,
        cube_size: u32,
    ) -> WebCubeTexture {
        let cube = crate::PmremGenerator::from_equirect(&data, src_w, src_h, cube_size.max(1));
        let pmrem = crate::PmremGenerator::generate_pmrem(&cube, cube_size.max(1));
        WebCubeTexture {
            inner: Arc::new(pmrem),
        }
    }
}

#[wasm_bindgen]
pub struct WebDataTexture {
    inner: Arc<crate::Texture>,
}
#[wasm_bindgen]
impl WebDataTexture {
    /// three.js `texture.colorSpace`: `true` for `SRGBColorSpace` (the bytes
    /// are sRGB-encoded and the sampler decodes them), `false` for none or
    /// linear. Applies to the 8-bit RGBA formats; others are left as they are.
    /// A material bound to the texture before the change keeps the old one
    /// until it is bound again.
    #[wasm_bindgen(js_name = setSrgb)]
    pub fn set_srgb(&mut self, srgb: bool) {
        use crate::TextureFormat as F;
        let want = if srgb {
            F::Rgba8UnormSrgb
        } else {
            F::Rgba8Unorm
        };
        if matches!(self.inner.format, F::Rgba8Unorm | F::Rgba8UnormSrgb)
            && self.inner.format != want
        {
            Arc::make_mut(&mut self.inner).format = want;
        }
    }
    #[wasm_bindgen(constructor)]
    pub fn new(width: u32, height: u32, data: Vec<u8>) -> WebDataTexture {
        WebDataTexture {
            inner: Arc::new(crate::DataTexture::new(
                width,
                height,
                crate::TextureFormat::Rgba8Unorm,
                data,
            )),
        }
    }
    /// A texture whose bytes are sRGB-encoded — what every JPEG and PNG colour
    /// map is.
    ///
    /// The default constructor uploads `Rgba8Unorm`, i.e. the sampler reads the
    /// bytes as linear. Feeding it an ordinary image makes the darks far too
    /// bright; this asks the hardware to decode instead, which is both correct
    /// and free. Use it for colour maps, never for normal/roughness data.
    #[wasm_bindgen(js_name = newSrgb)]
    pub fn new_srgb(width: u32, height: u32, data: Vec<u8>) -> WebDataTexture {
        WebDataTexture {
            inner: Arc::new(crate::DataTexture::new(
                width,
                height,
                crate::TextureFormat::Rgba8UnormSrgb,
                data,
            )),
        }
    }

    /// Replace RGBA8 level-0 bytes without allocating a new texture id.
    #[wasm_bindgen(js_name = replaceRgba)]
    pub fn replace_rgba(&mut self, data: Vec<u8>) -> bool {
        let inner = Arc::make_mut(&mut self.inner);
        inner.replace_rgba_bytes(data)
    }

    #[wasm_bindgen(js_name = setFilters)]
    pub fn set_filters(&mut self, mag: u32, min: u32, wrap_s: u32, wrap_t: u32) {
        set_texture_filters(Arc::make_mut(&mut self.inner), mag, min, wrap_s, wrap_t);
    }

    /// Resample this equirectangular map onto the six faces of a cube.
    ///
    /// See [`WebTexture::cube_faces`]. Both sky paths need it — the generated
    /// starfield arrives as a `DataTexture`, and leaving it on a sphere left
    /// the pole exactly as it was.
    #[cfg(feature = "planet")]
    #[wasm_bindgen(js_name = cubeFaces)]
    pub fn cube_faces(&self, face_size: u32) -> js_sys::Array {
        let n = if face_size == 0 {
            (self.inner.width / 4).clamp(64, 4096)
        } else {
            face_size
        };
        let out = js_sys::Array::new();
        for face in crate::planet::equirect_to_cube_faces(&self.inner, n) {
            out.push(&JsValue::from(WebDataTexture {
                inner: Arc::new(face),
            }));
        }
        out
    }

    /// A second handle on the same pixels, carrying its own UV transform.
    ///
    /// `Texture`'s bytes live behind their own `Arc`, so this clones a handle
    /// and not an image — and the renderer keys its GPU cache on those bytes,
    /// so every view of one buffer shares a single upload between them.
    #[wasm_bindgen(js_name = view)]
    pub fn view(&self, ox: f32, oy: f32, rx: f32, ry: f32) -> WebDataTexture {
        let mut inner = (*self.inner).clone();
        inner.offset = crate::math::Vector2::new(ox, oy);
        inner.repeat = crate::math::Vector2::new(rx, ry);
        WebDataTexture {
            inner: Arc::new(inner),
        }
    }

    /// three.js `Texture.offset` / `Texture.repeat` — the UV sub-rectangle this
    /// texture covers. What lets several meshes share one atlas.
    #[wasm_bindgen(js_name = setUvTransform)]
    pub fn set_uv_transform(&mut self, ox: f32, oy: f32, rx: f32, ry: f32) {
        let inner = Arc::make_mut(&mut self.inner);
        inner.offset = crate::math::Vector2::new(ox, oy);
        inner.repeat = crate::math::Vector2::new(rx, ry);
        inner.rotation = 0.0;
        inner.center = crate::math::Vector2::ZERO;
        inner.matrix_auto_update = true;
    }

    /// three.js `Texture.channel`: the uv set the texture is read through —
    /// 0 the geometry's `uv`, 1–3 its `uv1`, `uv2`, `uv3`.
    #[wasm_bindgen(js_name = setChannel)]
    pub fn set_channel(&mut self, channel: u32) {
        Arc::make_mut(&mut self.inner).channel = channel.min(3);
    }

    /// three.js `Texture.matrix` as its top two rows, `(a, b, c)` and
    /// `(d, e, f)`: `u' = a·u + b·v + c`, `v' = d·u + e·v + f`. What
    /// `offset`, `repeat`, `rotation` and `center` compose to
    /// (`Matrix3.setUvTransform`), or a matrix set by hand.
    #[wasm_bindgen(js_name = setUvMatrix)]
    pub fn set_uv_matrix(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
        set_uv_matrix(Arc::make_mut(&mut self.inner), [a, b, c, d, e, f]);
    }
}

/// The env-map fields Basic, Lambert and Phong share, borrowed.
struct EnvState<'a> {
    env_map: &'a mut Option<Arc<crate::CubeTexture>>,
    combine: &'a mut crate::materials::Combine,
    reflectivity: &'a mut f32,
    refraction_ratio: &'a mut f32,
    env_map_rotation: &'a mut crate::math::Euler,
}

macro_rules! env_state_of {
    ($($t:ty),*) => {$(
        impl<'a> EnvStateOf<'a> for $t {
            fn env_state(&'a mut self) -> EnvState<'a> {
                EnvState {
                    env_map: &mut self.env_map,
                    combine: &mut self.combine,
                    reflectivity: &mut self.reflectivity,
                    refraction_ratio: &mut self.refraction_ratio,
                    env_map_rotation: &mut self.env_map_rotation,
                }
            }
        }
    )*};
}

trait EnvStateOf<'a> {
    fn env_state(&'a mut self) -> EnvState<'a>;
}
env_state_of!(
    crate::BasicMaterial,
    crate::LambertMaterial,
    crate::PhongMaterial
);

impl<'a> EnvState<'a> {
    fn of<T: EnvStateOf<'a>>(m: &'a mut T) -> Self {
        m.env_state()
    }
}

/// `setUvMatrix` for both texture handles. Offset and repeat are kept in step
/// where the matrix is a plain scale and translation, so code reading them
/// sees the same transform.
fn set_uv_matrix(t: &mut crate::Texture, [a, b, c, d, e, f]: [f32; 6]) {
    t.matrix = [a, d, 0.0, b, e, 0.0, c, f, 1.0];
    t.matrix_auto_update = false;
    if b == 0.0 && d == 0.0 {
        t.offset = crate::math::Vector2::new(c, f);
        t.repeat = crate::math::Vector2::new(a, e);
        t.rotation = 0.0;
        t.center = crate::math::Vector2::ZERO;
    }
}

/// three.js `magFilter` / `minFilter` constants as `(within a level, between
/// levels)`: `NearestFilter` 1003, `NearestMipmapNearestFilter` 1004,
/// `NearestMipmapLinearFilter` 1005, `LinearFilter` 1006,
/// `LinearMipmapNearestFilter` 1007, `LinearMipmapLinearFilter` 1008 (the
/// default for anything else). The second is `None` without mipmaps.
fn three_filter(
    f: u32,
) -> (
    crate::textures::TextureFilter,
    Option<crate::textures::TextureFilter>,
) {
    use crate::textures::TextureFilter::{Linear, Nearest};
    match f {
        1003 => (Nearest, None),
        1004 => (Nearest, Some(Nearest)),
        1005 => (Nearest, Some(Linear)),
        1006 => (Linear, None),
        1007 => (Linear, Some(Nearest)),
        _ => (Linear, Some(Linear)),
    }
}

/// `setFilters(magFilter, minFilter, wrapS, wrapT)` for both texture handles,
/// in three.js's constants: the filters as [`three_filter`] reads them, the
/// wraps `RepeatWrapping` 1000, `ClampToEdgeWrapping` 1001 (the default),
/// `MirroredRepeatWrapping` 1002. Each is the texture's own, as three.js's are.
fn set_texture_filters(t: &mut crate::Texture, mag: u32, min: u32, wrap_s: u32, wrap_t: u32) {
    use crate::textures::TextureWrap;
    let wrap = |w: u32| match w {
        1000 => TextureWrap::Repeat,
        1002 => TextureWrap::MirroredRepeat,
        _ => TextureWrap::ClampToEdge,
    };
    t.mag_filter = three_filter(mag).0;
    (t.min_filter, t.mipmap_filter) = three_filter(min);
    t.wrap_s = wrap(wrap_s);
    t.wrap_t = wrap(wrap_t);
}

// ======================================================================
//                             CURVES
// ======================================================================

// The three.js curve classes are `WebCurve`, in `src/wasm/curves.rs`.

#[wasm_bindgen]
pub struct WebPath {
    inner: crate::Path,
}
#[wasm_bindgen]
impl WebPath {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebPath {
        WebPath {
            inner: crate::Path::new(),
        }
    }
    #[wasm_bindgen(js_name = moveTo)]
    pub fn move_to(&mut self, x: f32, y: f32) {
        self.inner.move_to(crate::Vector2::new(x, y));
    }
    #[wasm_bindgen(js_name = lineTo)]
    pub fn line_to(&mut self, x: f32, y: f32) {
        self.inner.line_to(crate::Vector2::new(x, y));
    }

    #[wasm_bindgen(js_name = quadraticCurveTo)]
    pub fn quadratic_curve_to(&mut self, cpx: f32, cpy: f32, x: f32, y: f32) {
        self.inner
            .quadratic_curve_to(crate::Vector2::new(cpx, cpy), crate::Vector2::new(x, y));
    }

    #[wasm_bindgen(js_name = bezierCurveTo)]
    pub fn bezier_curve_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) {
        self.inner.bezier_curve_to(
            crate::Vector2::new(c1x, c1y),
            crate::Vector2::new(c2x, c2y),
            crate::Vector2::new(x, y),
        );
    }

    pub fn arc(&mut self, cx: f32, cy: f32, radius: f32, start: f32, end: f32, clockwise: bool) {
        self.inner
            .arc(crate::Vector2::new(cx, cy), radius, start, end, clockwise);
    }

    /// Sample the path as a flat polyline — `divisions` points per sub-curve.
    #[wasm_bindgen(js_name = getPoints)]
    pub fn get_points(&self, divisions: usize) -> Vec<f32> {
        self.inner
            .get_points(divisions.max(1))
            .into_iter()
            .flat_map(|p| [p.x, p.y])
            .collect()
    }

    /// The path as an SVG `d` string, with its curves intact rather than
    /// flattened. Note that SVG's y axis points down and these coordinates are
    /// y-up, so a document usually wants a `scale(1,-1)` around them.
    #[wasm_bindgen(js_name = toSvgPathData)]
    pub fn to_svg_path_data(&self, precision: usize) -> String {
        self.inner.to_svg_path_data(precision)
    }

    /// Read an SVG `d` string — the inbound half, for turning artwork into
    /// geometry.
    #[wasm_bindgen(js_name = fromSvgPathData)]
    pub fn from_svg_path_data(d: &str) -> Result<WebPath, JsValue> {
        crate::Path::from_svg_path_data(d)
            .map(|inner| WebPath { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }
}

#[wasm_bindgen]
pub struct WebShape {
    pub(crate) inner: crate::Shape,
}
#[wasm_bindgen]
impl WebShape {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebShape {
        WebShape {
            inner: crate::Shape::new(),
        }
    }

    #[wasm_bindgen(js_name = fromPath)]
    pub fn from_path(outline: &WebPath) -> WebShape {
        WebShape {
            inner: crate::Shape::from_path(
                crate::Path::from_svg_path_data(&outline.inner.to_svg_path_data(6))
                    .unwrap_or_default(),
            ),
        }
    }

    #[wasm_bindgen(js_name = addHole)]
    pub fn add_hole(&mut self, hole: &WebPath) {
        if let Ok(p) = crate::Path::from_svg_path_data(&hole.inner.to_svg_path_data(6)) {
            self.inner.add_hole(p);
        }
    }

    /// Outline then holes, as one `d` string. Fill it with
    /// `fill-rule="evenodd"` — see the Rust-side docs for why.
    #[wasm_bindgen(js_name = toSvgPathData)]
    pub fn to_svg_path_data(&self, precision: usize) -> String {
        self.inner.to_svg_path_data(precision)
    }

    /// Read SVG path data as an outline plus holes: first subpath is the
    /// outline, the rest are holes.
    #[wasm_bindgen(js_name = fromSvgPathData)]
    pub fn from_svg_path_data(d: &str) -> Result<WebShape, JsValue> {
        crate::Shape::from_svg_path_data(d)
            .map(|inner| WebShape { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }
}

// ======================================================================
//                            ANIMATION
// ======================================================================

// three.js's animation system is in `animation.rs`.

// ======================================================================
//                            CONTROLS
// ======================================================================

#[wasm_bindgen]
pub struct WebOrbitControls {
    inner: crate::OrbitControls,
}
#[wasm_bindgen]
impl WebOrbitControls {
    #[wasm_bindgen(constructor)]
    pub fn new(camera: &WebCamera) -> WebOrbitControls {
        let c = match &camera.inner {
            CameraInner::Perspective(p) => p.clone(),
            _ => crate::PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0),
        };
        WebOrbitControls {
            inner: crate::OrbitControls::new(&c),
        }
    }
    #[wasm_bindgen(js_name = setLimits)]
    #[allow(clippy::too_many_arguments)]
    pub fn set_limits(
        &mut self,
        min_distance: f32,
        max_distance: f32,
        min_polar_angle: f32,
        max_polar_angle: f32,
        rotate_speed: f32,
        zoom_speed: f32,
        pan_speed: f32,
        damping: f32,
    ) {
        self.inner.min_distance = min_distance.max(0.0);
        self.inner.max_distance = max_distance.max(self.inner.min_distance);
        self.inner.min_polar_angle = min_polar_angle;
        self.inner.max_polar_angle = max_polar_angle;
        self.inner.rotate_speed = rotate_speed;
        self.inner.zoom_speed = zoom_speed;
        self.inner.pan_speed = pan_speed;
        self.inner.damping = damping;
        self.inner.enable_damping = damping > 0.0;
    }

    /// Enable / tune inertia and auto-rotate (three.js parity).
    #[wasm_bindgen(js_name = setMotion)]
    pub fn set_motion(
        &mut self,
        enable_damping: bool,
        damping: f32,
        auto_rotate: bool,
        auto_rotate_speed: f32,
    ) {
        self.inner.enable_damping = enable_damping;
        self.inner.damping = damping.clamp(0.0, 1.0);
        self.inner.auto_rotate = auto_rotate;
        self.inner.auto_rotate_speed = auto_rotate_speed;
    }

    pub fn update(
        &mut self,
        camera: &mut WebCamera,
        dx: f32,
        dy: f32,
        wheel: f32,
        rotating: bool,
        panning: bool,
        w: f32,
        h: f32,
    ) {
        self.update_dt(camera, dx, dy, wheel, rotating, panning, w, h, 1.0 / 60.0);
    }

    #[wasm_bindgen(js_name = updateDt)]
    #[allow(clippy::too_many_arguments)]
    pub fn update_dt(
        &mut self,
        camera: &mut WebCamera,
        dx: f32,
        dy: f32,
        wheel: f32,
        rotating: bool,
        panning: bool,
        w: f32,
        h: f32,
        dt: f32,
    ) {
        let ev = crate::PointerEvent {
            dx,
            dy,
            wheel,
            rotating,
            panning,
        };
        if let CameraInner::Perspective(c) = &mut camera.inner {
            self.inner.update_dt(ev, c, (w, h), dt);
        }
    }

    #[wasm_bindgen(js_name = reseedFromCamera)]
    pub fn reseed_from_camera(&mut self, camera: &WebCamera) {
        if let CameraInner::Perspective(c) = &camera.inner {
            self.inner.reseed_from_camera(c);
        }
    }

    /// Orbit centre.
    #[wasm_bindgen(js_name = setTarget)]
    pub fn set_target(&mut self, x: f32, y: f32, z: f32) {
        self.inner.target = crate::Vector3::new(x, y, z);
    }
}

#[wasm_bindgen]
pub struct WebTrackballControls {
    inner: crate::TrackballControls,
}
#[wasm_bindgen]
impl WebTrackballControls {
    #[wasm_bindgen(constructor)]
    pub fn new(camera: &WebCamera) -> WebTrackballControls {
        let c = match &camera.inner {
            CameraInner::Perspective(p) => p.clone(),
            _ => crate::PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0),
        };
        WebTrackballControls {
            inner: crate::TrackballControls::new(&c),
        }
    }
    pub fn update(
        &mut self,
        camera: &mut WebCamera,
        dx: f32,
        dy: f32,
        wheel: f32,
        rotating: bool,
        panning: bool,
        w: f32,
        h: f32,
    ) {
        let ev = crate::PointerEvent {
            dx,
            dy,
            wheel,
            rotating,
            panning,
        };
        if let CameraInner::Perspective(c) = &mut camera.inner {
            self.inner.update(ev, c, (w, h));
        }
    }
}

#[wasm_bindgen]
pub struct WebArcballControls {
    inner: crate::ArcballControls,
}
#[wasm_bindgen]
impl WebArcballControls {
    #[wasm_bindgen(constructor)]
    pub fn new(camera: &WebCamera) -> WebArcballControls {
        let c = match &camera.inner {
            CameraInner::Perspective(p) => p.clone(),
            _ => crate::PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0),
        };
        WebArcballControls {
            inner: crate::ArcballControls::new(&c),
        }
    }
    #[wasm_bindgen(js_name = setTarget)]
    pub fn set_target(&mut self, x: f32, y: f32, z: f32) {
        self.inner.target = crate::Vector3::new(x, y, z);
    }
    pub fn update(
        &mut self,
        camera: &mut WebCamera,
        ndc_x: f32,
        ndc_y: f32,
        wheel: f32,
        rotating: bool,
    ) {
        let ev = crate::PointerEvent {
            dx: 0.0,
            dy: 0.0,
            wheel,
            rotating,
            panning: false,
        };
        let ndc = crate::Vector2::new(ndc_x, ndc_y);
        if let CameraInner::Perspective(c) = &mut camera.inner {
            self.inner.update(ndc, ev, c);
        }
    }
}

#[wasm_bindgen]
pub struct WebFirstPersonControls {
    inner: crate::FirstPersonControls,
}
#[wasm_bindgen]
impl WebFirstPersonControls {
    #[wasm_bindgen(constructor)]
    pub fn new(camera: &WebCamera) -> WebFirstPersonControls {
        let c = match &camera.inner {
            CameraInner::Perspective(p) => p.clone(),
            _ => crate::PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0),
        };
        WebFirstPersonControls {
            inner: crate::FirstPersonControls::new(&c),
        }
    }
    pub fn update(&mut self, camera: &mut WebCamera, dx: f32, dy: f32, dt: f32, rotating: bool) {
        let ev = crate::PointerEvent {
            dx,
            dy,
            wheel: 0.0,
            rotating,
            panning: false,
        };
        if let CameraInner::Perspective(c) = &mut camera.inner {
            self.inner.update(ev, c, dt);
        }
    }
    #[wasm_bindgen(js_name = setMoveInput)]
    pub fn set_move_input(&mut self, forward: f32, right: f32, up: f32) {
        self.inner.move_input = crate::Vector3::new(forward, right, up);
    }
}

#[wasm_bindgen]
pub struct WebPointerLockControls {
    inner: crate::PointerLockControls,
}
#[wasm_bindgen]
impl WebPointerLockControls {
    #[wasm_bindgen(constructor)]
    pub fn new(camera: &WebCamera) -> WebPointerLockControls {
        let c = match &camera.inner {
            CameraInner::Perspective(p) => p.clone(),
            _ => crate::PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0),
        };
        WebPointerLockControls {
            inner: crate::PointerLockControls::new(&c),
        }
    }
}

// ======================================================================
//                              HELPERS
// ======================================================================

#[wasm_bindgen]
pub struct WebAxesHelper {
    obj: crate::core::Object3D,
}
#[wasm_bindgen]
impl WebAxesHelper {
    #[wasm_bindgen(constructor)]
    pub fn new(size: f32) -> WebAxesHelper {
        WebAxesHelper {
            obj: crate::AxesHelper::new(size),
        }
    }
}

#[wasm_bindgen]
pub struct WebGridHelper {
    obj: crate::core::Object3D,
}
#[wasm_bindgen]
impl WebGridHelper {
    #[wasm_bindgen(constructor)]
    pub fn new(size: f32, divisions: usize, color1: u32, color2: u32) -> WebGridHelper {
        WebGridHelper {
            obj: crate::GridHelper::new_from_hex(size, divisions, color1, color2),
        }
    }
}

#[wasm_bindgen]
pub struct WebBoxHelper {
    obj: crate::core::Object3D,
}
#[wasm_bindgen]
impl WebBoxHelper {
    #[wasm_bindgen(constructor)]
    pub fn new(bb: &WebBox3) -> WebBoxHelper {
        WebBoxHelper {
            obj: crate::BoxHelper::new(&bb.inner, crate::Color::WHITE),
        }
    }
}

#[wasm_bindgen]
pub struct WebPolarGridHelper {
    obj: crate::core::Object3D,
}
#[wasm_bindgen]
impl WebPolarGridHelper {
    #[wasm_bindgen(constructor)]
    pub fn new(radius: f32, segments: usize, circles: usize) -> WebPolarGridHelper {
        WebPolarGridHelper {
            obj: crate::PolarGridHelper::default_(radius, segments, circles),
        }
    }
}

#[wasm_bindgen]
impl WebScene {
    /// Add a helper as a scene-graph child (returns its handle for later removal).
    #[wasm_bindgen(js_name = addHelper)]
    pub fn add_helper(
        &mut self,
        axes: Option<WebAxesHelper>,
        grid: Option<WebGridHelper>,
    ) -> WebObjectHandle {
        let obj = if let Some(a) = axes {
            a.obj
        } else if let Some(g) = grid {
            g.obj
        } else {
            crate::core::Object3D::group()
        };
        let id = self.inner.add(obj);
        WebObjectHandle { id }
    }
}

// ======================================================================
//                              LOADERS
// ======================================================================

#[wasm_bindgen]
pub struct WebObjLoader;
#[wasm_bindgen]
impl WebObjLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebObjLoader {
        WebObjLoader
    }
    pub fn parse(&self, src: &str) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::ObjLoader::parse(src)),
        }
    }
}

#[wasm_bindgen]
pub struct WebStlLoader;
#[wasm_bindgen]
impl WebStlLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebStlLoader {
        WebStlLoader
    }
    pub fn parse(&self, bytes: Vec<u8>) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::StlLoader::parse(&bytes)),
        }
    }
}

#[wasm_bindgen]
pub struct WebPlyLoader;
#[wasm_bindgen]
impl WebPlyLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebPlyLoader {
        WebPlyLoader
    }
    pub fn parse(&self, bytes: Vec<u8>) -> WebGeometry {
        WebGeometry {
            inner: Arc::new(crate::PlyLoader::parse(&bytes)),
        }
    }
}

#[wasm_bindgen]
pub struct WebHdrLoader;
#[wasm_bindgen]
impl WebHdrLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebHdrLoader {
        WebHdrLoader
    }
    pub fn parse(&self, bytes: Vec<u8>) -> Result<WebTexture, JsValue> {
        crate::HdrLoader::parse(&bytes)
            .map(|t| WebTexture { inner: Arc::new(t) })
            .map_err(|e| JsValue::from_str(&format!("{e:?}")))
    }
}

#[wasm_bindgen]
pub struct WebFbxLoader;
#[wasm_bindgen]
impl WebFbxLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebFbxLoader {
        WebFbxLoader
    }
    pub fn parse(&self, bytes: Vec<u8>) -> Result<WebGeometry, JsValue> {
        crate::FbxLoader::parse(&bytes)
            .map(|g| WebGeometry { inner: Arc::new(g) })
            .map_err(|e| JsValue::from_str(&format!("{e:?}")))
    }
}

/// KTX2 textures, which is how a browser gets a GPU-compressed one.
///
/// The container is read here; a Basis Universal payload still needs
/// transcoding and is reported as such rather than returned as noise.
#[wasm_bindgen]
pub struct WebKtx2Loader;
#[wasm_bindgen]
impl WebKtx2Loader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebKtx2Loader {
        WebKtx2Loader
    }

    /// The base mip level as raw bytes, with the format and size reported
    /// separately — a compressed payload is not pixels and must not be handed
    /// back as if it were.
    pub fn parse(&self, bytes: Vec<u8>) -> Result<WebKtx2Texture, JsValue> {
        let ktx =
            crate::loaders::ktx2::parse(&bytes).map_err(|e| JsValue::from_str(&format!("{e}")))?;
        let format = format!("{:?}", ktx.texture_format().ok());
        let levels = ktx
            .level_data()
            .map_err(|e| JsValue::from_str(&format!("{e}")))?;
        Ok(WebKtx2Texture {
            width: ktx.width,
            height: ktx.height,
            format,
            block_compressed: ktx
                .texture_format()
                .map(|f| f.is_block_compressed())
                .unwrap_or(false),
            levels,
        })
    }
}

#[wasm_bindgen]
pub struct WebKtx2Texture {
    #[wasm_bindgen(readonly)]
    pub width: u32,
    #[wasm_bindgen(readonly)]
    pub height: u32,
    /// Whether the bytes are blocks rather than pixels, which decides whether a
    /// caller may index them.
    #[wasm_bindgen(readonly)]
    pub block_compressed: bool,
    format: String,
    levels: Vec<Vec<u8>>,
}

#[wasm_bindgen]
impl WebKtx2Texture {
    #[wasm_bindgen(getter)]
    pub fn format(&self) -> String {
        self.format.clone()
    }

    #[wasm_bindgen(getter)]
    pub fn level_count(&self) -> usize {
        self.levels.len()
    }

    /// One mip level's bytes, largest first.
    pub fn level(&self, index: usize) -> Option<Vec<u8>> {
        self.levels.get(index).cloned()
    }
}

/// Alembic geometry caches.
#[wasm_bindgen]
pub struct WebAlembicLoader;
#[wasm_bindgen]
impl WebAlembicLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebAlembicLoader {
        WebAlembicLoader
    }

    /// The first `PolyMesh` in the archive, as a geometry.
    pub fn parse(&self, bytes: Vec<u8>) -> Result<WebGeometry, JsValue> {
        let archive = crate::loaders::alembic::Archive::open(&bytes)
            .map_err(|e| JsValue::from_str(&format!("{e}")))?;
        let mesh = archive
            .poly_meshes()
            .into_iter()
            .next()
            .ok_or_else(|| JsValue::from_str("no PolyMesh in this archive"))?;
        Ok(WebGeometry {
            inner: Arc::new(poly_mesh_geometry(&mesh)),
        })
    }

    /// How many meshes the archive holds, for a caller that wants to choose.
    pub fn mesh_names(&self, bytes: Vec<u8>) -> Result<Vec<JsValue>, JsValue> {
        let archive = crate::loaders::alembic::Archive::open(&bytes)
            .map_err(|e| JsValue::from_str(&format!("{e}")))?;
        Ok(archive
            .poly_meshes()
            .iter()
            .map(|m| JsValue::from_str(&m.name))
            .collect())
    }
}

/// An Alembic `PolyMesh` as a triangulated `BufferGeometry`.
///
/// Faces are fanned and remembered as polygons; see [`PolyMesh::geometry`].
///
/// [`PolyMesh::geometry`]: crate::loaders::PolyMesh::geometry
fn poly_mesh_geometry(mesh: &crate::loaders::PolyMesh) -> crate::core::BufferGeometry {
    mesh.geometry()
}

/// USD in the browser.
///
/// Gated on the `usd` feature like the rest of it, so a wasm build that does
/// not want ten thousand lines of scene description does not pay for them.
/// `.usda`, `.usdc` and `.usdz` all arrive as bytes here, and the loader tells
/// them apart by what is in them rather than by a file name — which a browser
/// often does not have.
#[cfg(feature = "usd")]
#[wasm_bindgen]
pub struct WebUsdLoader;

#[cfg(feature = "usd")]
#[wasm_bindgen]
impl WebUsdLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebUsdLoader {
        WebUsdLoader
    }

    /// The first mesh in the layer, as a geometry.
    pub fn parse(&self, bytes: Vec<u8>) -> Result<WebGeometry, JsValue> {
        let scene = crate::loaders::usd::UsdLoader::parse(&bytes)
            .map_err(|e| JsValue::from_str(&format!("{e}")))?;
        let geometry = scene
            .arena
            .nodes
            .iter()
            .find_map(|(_, o)| match &o.kind {
                crate::core::ObjectKind::Mesh(m) => Some(m.geometry.clone()),
                _ => None,
            })
            .ok_or_else(|| JsValue::from_str("no mesh in this USD layer"))?;
        Ok(WebGeometry { inner: geometry })
    }

    /// Which of the three forms the bytes are, for a caller that wants to know
    /// before committing to them.
    pub fn sniff(&self, bytes: Vec<u8>) -> Option<String> {
        crate::loaders::usd::sniff(&bytes).map(|f| format!("{f:?}"))
    }
}

/// Writing glTF from the browser, which is how a scene edited there gets out.
#[wasm_bindgen]
pub struct WebGltfExporter;
#[wasm_bindgen]
impl WebGltfExporter {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebGltfExporter {
        WebGltfExporter
    }

    /// One geometry as a self-contained `.glb`.
    pub fn geometry_to_glb(&self, geometry: &WebGeometry) -> Vec<u8> {
        crate::loaders::gltf_geometry_to_glb(&geometry.inner)
    }
}

#[wasm_bindgen]
pub struct WebColladaLoader;
#[wasm_bindgen]
impl WebColladaLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebColladaLoader {
        WebColladaLoader
    }
    pub fn parse(&self, src: &str) -> Result<WebGeometry, JsValue> {
        crate::ColladaLoader::parse(src)
            .map(|g| WebGeometry { inner: Arc::new(g) })
            .map_err(|e| JsValue::from_str(&format!("{e:?}")))
    }
}

#[wasm_bindgen]
pub struct WebExrLoader;
#[wasm_bindgen]
impl WebExrLoader {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebExrLoader {
        WebExrLoader
    }
    pub fn parse(&self, bytes: Vec<u8>) -> Result<WebTexture, JsValue> {
        crate::ExrLoader::parse(&bytes)
            .map(|t| WebTexture { inner: Arc::new(t) })
            .map_err(|e| JsValue::from_str(&format!("{e:?}")))
    }

    /// Decode to half-float instead of clipping to 8 bits.
    ///
    /// EXR is scene-referred, and a star map is the extreme case: over half of
    /// NASA's Deep Star Maps sits below a hundredth of full scale, so the 8-bit
    /// path leaves the galaxy as a handful of grey dots.
    #[wasm_bindgen(js_name = parseHdr)]
    pub fn parse_hdr(&self, bytes: Vec<u8>) -> Result<WebTexture, JsValue> {
        crate::ExrLoader::parse_hdr(&bytes)
            .map(|t| WebTexture { inner: Arc::new(t) })
            .map_err(|e| JsValue::from_str(&format!("{e:?}")))
    }
}

// ======================================================================
//                               AUDIO
// ======================================================================

#[wasm_bindgen]
pub struct WebAudioListener {
    inner: crate::AudioListener,
}
#[wasm_bindgen]
impl WebAudioListener {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebAudioListener {
        WebAudioListener {
            inner: crate::AudioListener::default(),
        }
    }
    #[wasm_bindgen(js_name = setMasterVolume)]
    pub fn set_master_volume(&mut self, v: f32) {
        self.inner.master_volume = v;
    }
}

#[wasm_bindgen]
pub struct WebAudio {
    inner: crate::Audio,
}
#[wasm_bindgen]
impl WebAudio {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebAudio {
        WebAudio {
            inner: crate::Audio::default(),
        }
    }
    #[wasm_bindgen(js_name = setVolume)]
    pub fn set_volume(&mut self, v: f32) {
        self.inner.volume = v;
    }
    #[wasm_bindgen(js_name = setLoop)]
    pub fn set_loop(&mut self, l: bool) {
        self.inner.loop_ = l;
    }
    pub fn play(&mut self) {
        self.inner.playing = true;
    }
    pub fn stop(&mut self) {
        self.inner.playing = false;
    }
}

// ======================================================================
//                           POST-PROCESSING
// ======================================================================

// `WebEffectComposer`, `WebPass` and the shared random stream: see
// `wasm/postfx.rs`.

// ======================================================================
//                              EXTRAS
// ======================================================================

#[wasm_bindgen]
pub struct WebOctree {
    inner: crate::Octree,
}
#[wasm_bindgen]
impl WebOctree {
    #[wasm_bindgen(constructor)]
    pub fn new(bb: &WebBox3, max_depth: u32, max_points: usize) -> WebOctree {
        WebOctree {
            inner: crate::Octree::new(bb.inner, max_depth, max_points),
        }
    }
    pub fn insert(&mut self, p: &WebVector3) {
        self.inner.insert(p.inner);
    }
}

#[wasm_bindgen]
pub struct WebSimplexNoise;
#[wasm_bindgen]
impl WebSimplexNoise {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebSimplexNoise {
        WebSimplexNoise
    }
    pub fn noise2(&self, x: f32, y: f32) -> f32 {
        crate::SimplexNoise::noise2(x, y)
    }
}

#[wasm_bindgen]
pub struct WebMarchingCubes;
#[wasm_bindgen]
impl WebMarchingCubes {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebMarchingCubes {
        WebMarchingCubes
    }
}

// ======================================================================
//                            ALT RENDERERS
// ======================================================================

#[wasm_bindgen]
pub struct WebCss2dRenderer {
    inner: crate::Css2dRenderer,
}
#[wasm_bindgen]
impl WebCss2dRenderer {
    #[wasm_bindgen(constructor)]
    pub fn new(w: u32, h: u32) -> WebCss2dRenderer {
        WebCss2dRenderer {
            inner: crate::Css2dRenderer::new(w, h),
        }
    }
}

#[wasm_bindgen]
pub struct WebSvgRenderer {
    inner: crate::SvgRenderer,
}
#[wasm_bindgen]
impl WebSvgRenderer {
    #[wasm_bindgen(constructor)]
    pub fn new(w: u32, h: u32) -> WebSvgRenderer {
        WebSvgRenderer {
            inner: crate::SvgRenderer::new(w, h),
        }
    }

    /// `0` lit (default), `1` flat material colour, `2` wireframe.
    #[wasm_bindgen(js_name = setShading)]
    pub fn set_shading(&mut self, mode: u32) {
        self.inner.options.shading = match mode {
            1 => crate::SvgShading::Flat,
            2 => crate::SvgShading::Wireframe,
            _ => crate::SvgShading::Lit,
        };
    }

    /// Same three.js constants as
    /// [`WebRenderer::setToneMapping`](WebRenderer::set_tone_mapping): `0`
    /// NoToneMapping, `1` Linear, `4` ACESFilmic.
    #[wasm_bindgen(js_name = setToneMapping)]
    pub fn set_tone_mapping(&mut self, mode: u32, exposure: f32) {
        // three.js's constants: 0 NoToneMapping, 1 Linear, 4 ACESFilmic,
        // 6 AgX, 7 Neutral. 2 (Reinhard) and 3 (Cineon) have no curve here and
        // fall through to linear, as they always have.
        let mapping = match mode {
            0 => crate::ToneMapping::None,
            4 => crate::ToneMapping::AcesFilmic,
            6 => crate::ToneMapping::AgX,
            7 => crate::ToneMapping::Neutral,
            _ => crate::ToneMapping::Linear,
        };
        self.inner.set_tone_mapping(mapping, exposure);
    }

    /// Emit `scene.background` as a full-canvas rect. Off gives a transparent
    /// document that sits on whatever is behind it in the page.
    #[wasm_bindgen(js_name = setBackground)]
    pub fn set_background(&mut self, on: bool) {
        self.inner.options.background = on;
    }

    #[wasm_bindgen(js_name = setCullBackfaces)]
    pub fn set_cull_backfaces(&mut self, on: bool) {
        self.inner.options.cull_backfaces = on;
    }

    /// Hairline stroke per face, in pixels, that hides the light seams SVG
    /// leaves along shared edges. 0 disables it.
    #[wasm_bindgen(js_name = setSeamStroke)]
    pub fn set_seam_stroke(&mut self, px: f32) {
        self.inner.options.seam_stroke = px.max(0.0);
    }

    /// Decimal places kept on coordinates. Lower is a smaller document.
    #[wasm_bindgen(js_name = setPrecision)]
    pub fn set_precision(&mut self, places: u32) {
        self.inner.options.precision = places.min(8) as usize;
    }

    /// Draw a face's edges as Bézier curves when a straight one would miss the
    /// real surface by more than this many pixels. Pass a value of 0 or less to
    /// keep every edge straight.
    #[wasm_bindgen(js_name = setCurveTolerance)]
    pub fn set_curve_tolerance(&mut self, px: f32) {
        self.inner.options.curve_tolerance = (px > 0.0).then_some(px);
    }

    /// Split faces spanning more than this fraction of their own distance from
    /// the camera, so the depth sort has something meaningful to order. 0 or
    /// less disables splitting.
    #[wasm_bindgen(js_name = setDepthSplit)]
    pub fn set_depth_split(&mut self, tolerance: f32) {
        self.inner.options.depth_split = (tolerance > 0.0).then_some(tolerance);
    }

    /// Depth-sort faces back to front. Off only makes sense when the caller has
    /// already ordered the scene.
    #[wasm_bindgen(js_name = setSort)]
    pub fn set_sort(&mut self, on: bool) {
        self.inner.options.sort = on;
    }

    /// Resize the canvas, keeping every option set so far.
    #[wasm_bindgen(js_name = setSize)]
    pub fn set_size(&mut self, width: u32, height: u32) {
        self.inner.set_size(width, height);
    }

    #[wasm_bindgen(getter)]
    pub fn width(&self) -> u32 {
        self.inner.width
    }

    #[wasm_bindgen(getter)]
    pub fn height(&self) -> u32 {
        self.inner.height
    }

    /// Background colour as `0xRRGGBB`, overriding `scene.background`. Mirrors
    /// three.js's `setClearColor`.
    #[wasm_bindgen(js_name = setClearColor)]
    pub fn set_clear_color(&mut self, hex: u32, alpha: f32) {
        self.inner.set_clear_color(
            Some(crate::Color::from_hex(hex)),
            Some(alpha.clamp(0.0, 1.0)),
        );
    }

    /// Go back to taking the background from the scene.
    #[wasm_bindgen(js_name = clearClearColor)]
    pub fn clear_clear_color(&mut self) {
        self.inner.set_clear_color(None, None);
    }

    #[wasm_bindgen(js_name = renderToString)]
    pub fn render_to_string(&self, scene: &mut WebScene, camera: &WebCamera) -> String {
        match &camera.inner {
            CameraInner::Perspective(c) => self.inner.render_to_string(&mut scene.inner, c),
            CameraInner::Orthographic(c) => self.inner.render_to_string(&mut scene.inner, c),
        }
    }
}

/// Wrap an RGBA frame — typically read back off a canvas — in an SVG document
/// as an embedded PNG. The counterpart to [`WebSvgRenderer`] for when the scene
/// needs the real renderer's textures, shadows or post-fx and a per-face
/// painter's algorithm will not do.
#[wasm_bindgen(js_name = svgFromRgba)]
pub fn svg_from_rgba(width: u32, height: u32, rgba: &[u8]) -> Result<String, JsValue> {
    let want = width as usize * height as usize * 4;
    if rgba.len() != want {
        return Err(JsValue::from_str(&format!(
            "svgFromRgba: expected {want} bytes for {width}x{height}, got {}",
            rgba.len()
        )));
    }
    Ok(crate::svg_from_rgba(width, height, rgba))
}

// ======================================================================
//                               STATS
// ======================================================================

#[wasm_bindgen]
pub struct WebStats {
    inner: crate::Stats,
}
#[wasm_bindgen]
impl WebStats {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebStats {
        WebStats {
            inner: crate::Stats::new(),
        }
    }
    pub fn begin(&mut self) {
        self.inner.begin();
    }
    pub fn end(&mut self) {
        self.inner.end();
    }
    #[wasm_bindgen(getter)]
    pub fn fps(&self) -> f32 {
        self.inner.fps
    }
    #[wasm_bindgen(js_name = frameMs, getter)]
    pub fn frame_ms(&self) -> f32 {
        self.inner.frame_ms
    }
}

// ======================================================================
//                           RAYCASTER
// ======================================================================

#[wasm_bindgen]
pub struct WebRaycaster {
    inner: crate::Raycaster,
}
#[wasm_bindgen]
impl WebRaycaster {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebRaycaster {
        WebRaycaster {
            inner: crate::Raycaster::default(),
        }
    }
    /// three.js `setFromCamera`: the ray through NDC (`x`, `y` in -1..1, +y
    /// up), perspective or orthographic, and remembers the camera, which
    /// sprites need.
    #[wasm_bindgen(js_name = setFromCamera)]
    pub fn set_from_camera(&mut self, ndc_x: f32, ndc_y: f32, camera: &WebCamera) {
        let ndc = crate::Vector2::new(ndc_x, ndc_y);
        match &camera.inner {
            CameraInner::Perspective(c) => self.inner.set_from_camera(ndc, c),
            CameraInner::Orthographic(c) => self.inner.set_from_camera(ndc, c),
        }
    }

    /// three.js `set`: a new origin and direction. The direction is
    /// normalised here (three.js assumes the caller did).
    pub fn set(&mut self, origin: &WebVector3, direction: &WebVector3) {
        self.inner.set(origin.inner, direction.inner.normalize());
    }

    /// The ray origin.
    #[wasm_bindgen(getter)]
    pub fn origin(&self) -> WebVector3 {
        WebVector3 {
            inner: self.inner.ray.origin,
        }
    }

    /// The (unit) ray direction.
    #[wasm_bindgen(getter)]
    pub fn direction(&self) -> WebVector3 {
        WebVector3 {
            inner: self.inner.ray.direction,
        }
    }

    /// Hits nearer than this are dropped (three.js `near`, default 0).
    #[wasm_bindgen(getter)]
    pub fn near(&self) -> f32 {
        self.inner.near
    }
    #[wasm_bindgen(setter)]
    pub fn set_near(&mut self, near: f32) {
        self.inner.near = near;
    }

    /// Hits farther than this are dropped (three.js `far`, default Infinity).
    #[wasm_bindgen(getter)]
    pub fn far(&self) -> f32 {
        self.inner.far
    }
    #[wasm_bindgen(setter)]
    pub fn set_far(&mut self, far: f32) {
        self.inner.far = far;
    }

    /// three.js `params.Line.threshold`: how close (world units) the ray must
    /// pass to a line segment to hit it. Default 1.
    #[wasm_bindgen(getter, js_name = lineThreshold)]
    pub fn line_threshold(&self) -> f32 {
        self.inner.params.line.threshold
    }
    #[wasm_bindgen(js_name = setLineThreshold)]
    pub fn set_line_threshold(&mut self, threshold: f32) {
        self.inner.params.line.threshold = threshold;
    }

    /// three.js `params.Points.threshold`. Default 1.
    #[wasm_bindgen(getter, js_name = pointsThreshold)]
    pub fn points_threshold(&self) -> f32 {
        self.inner.params.points.threshold
    }
    #[wasm_bindgen(js_name = setPointsThreshold)]
    pub fn set_points_threshold(&mut self, threshold: f32) {
        self.inner.params.points.threshold = threshold;
    }

    /// Return only the nearest hit of the whole cast (three-mesh-bvh's
    /// `firstHitOnly`, applied across objects rather than per mesh), and
    /// prune the search by it.
    #[wasm_bindgen(getter, js_name = firstHitOnly)]
    pub fn first_hit_only(&self) -> bool {
        self.inner.first_hit_only
    }
    #[wasm_bindgen(setter, js_name = firstHitOnly)]
    pub fn set_first_hit_only(&mut self, on: bool) {
        self.inner.first_hit_only = on;
    }

    /// three.js `intersectObject(object, recursive)`: hits on the object with
    /// id `object_id` (`WebObjectHandle.id`, or `scene.rootId` for the whole
    /// scene) and, when `recursive` (default true), its descendants, nearest
    /// first. Invisible objects and their subtrees are skipped.
    ///
    /// Each hit is a plain object with three.js's field names: `distance`,
    /// `point`, `objectId`, and per kind `faceIndex`, `face {a, b, c, normal,
    /// materialIndex}`, `normal`, `uv`, `uv1`, `instanceId`, `index`,
    /// `distanceToRay`, plus the threers extensions `polygonIndex` and
    /// `barycoord`. A field that does not apply is absent (undefined), as in
    /// three.js. Vectors are `{x, y, z}` / `{x, y}`.
    #[wasm_bindgen(js_name = intersectObject)]
    pub fn intersect_object(
        &self,
        scene: &mut WebScene,
        object_id: f64,
        recursive: Option<bool>,
    ) -> Result<js_sys::Array, JsValue> {
        self.intersect_objects(scene, vec![object_id], recursive)
    }

    /// three.js `intersectObjects(objects, recursive)`: as `intersectObject`
    /// over every id in `object_ids`, all hits sorted together.
    #[wasm_bindgen(js_name = intersectObjects)]
    pub fn intersect_objects(
        &self,
        scene: &mut WebScene,
        object_ids: Vec<f64>,
        recursive: Option<bool>,
    ) -> Result<js_sys::Array, JsValue> {
        let ids = object_ids
            .iter()
            .map(|&id| {
                object_id_from_f64(id)
                    .filter(|id| scene.inner.arena.get(*id).is_some())
                    .ok_or_else(|| JsValue::from_str(&format!("intersectObjects: no object {id}")))
            })
            .collect::<Result<Vec<_>, _>>()?;
        scene.inner.update_world();
        let hits =
            self.inner
                .intersect_object_list(&scene.inner.arena, &ids, recursive.unwrap_or(true));
        let out = js_sys::Array::new();
        for h in &hits {
            out.push(&intersection_to_js(h));
        }
        Ok(out)
    }
}

fn js_set(obj: &js_sys::Object, key: &str, value: &JsValue) {
    let _ = js_sys::Reflect::set(obj, &JsValue::from_str(key), value);
}

fn js_vec3(v: crate::Vector3) -> JsValue {
    let o = js_sys::Object::new();
    js_set(&o, "x", &v.x.into());
    js_set(&o, "y", &v.y.into());
    js_set(&o, "z", &v.z.into());
    o.into()
}

fn js_vec2(v: crate::Vector2) -> JsValue {
    let o = js_sys::Object::new();
    js_set(&o, "x", &v.x.into());
    js_set(&o, "y", &v.y.into());
    o.into()
}

/// A hit as three.js reports it; fields that do not apply are left out.
fn intersection_to_js(h: &crate::core::Intersection) -> JsValue {
    let o = js_sys::Object::new();
    js_set(&o, "distance", &h.distance.into());
    js_set(&o, "point", &js_vec3(h.point));
    js_set(&o, "objectId", &object_id_to_f64(h.object).into());
    if let Some(f) = &h.face {
        js_set(&o, "faceIndex", &(h.face_index as f64).into());
        let face = js_sys::Object::new();
        js_set(&face, "a", &(f.a as f64).into());
        js_set(&face, "b", &(f.b as f64).into());
        js_set(&face, "c", &(f.c as f64).into());
        js_set(&face, "normal", &js_vec3(f.normal));
        js_set(&face, "materialIndex", &(f.material_index as f64).into());
        js_set(&o, "face", &face.into());
    }
    if let Some(p) = h.polygon_index {
        js_set(&o, "polygonIndex", &(p as f64).into());
    }
    if let Some(n) = h.normal {
        js_set(&o, "normal", &js_vec3(n));
    }
    if let Some(uv) = h.uv {
        js_set(&o, "uv", &js_vec2(uv));
    }
    if let Some(uv) = h.uv1 {
        js_set(&o, "uv1", &js_vec2(uv));
    }
    if let Some(b) = h.barycoord {
        js_set(&o, "barycoord", &js_vec3(b));
    }
    if let Some(i) = h.instance_id {
        js_set(&o, "instanceId", &(i as f64).into());
    }
    if let Some(i) = h.index {
        js_set(&o, "index", &(i as f64).into());
    }
    if let Some(d) = h.distance_to_ray {
        js_set(&o, "distanceToRay", &d.into());
    }
    o.into()
}

// ======================================================================
//                             CLOCK
// ======================================================================

#[wasm_bindgen]
pub struct WebClock {
    inner: crate::Clock,
}
#[wasm_bindgen]
impl WebClock {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebClock {
        WebClock {
            inner: crate::Clock::new(true),
        }
    }
    #[wasm_bindgen(js_name = getDelta)]
    pub fn get_delta(&mut self) -> f64 {
        self.inner.get_delta()
    }
    #[wasm_bindgen(js_name = getElapsedTime)]
    pub fn get_elapsed_time(&mut self) -> f64 {
        self.inner.get_elapsed_time()
    }
}

// ======================================================================
//                       OBJECT3D + NESTED OBJECTS
// ======================================================================

/// Generic Object3D handle (Group or any scene-graph node).
#[wasm_bindgen]
pub struct WebObject3D {
    pub(crate) inner: Option<crate::core::Object3D>,
}

#[wasm_bindgen]
impl WebObject3D {
    /// Empty group — three.js `new Group()` / `new Object3D()`.
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebObject3D {
        WebObject3D {
            inner: Some(crate::core::Object3D::group()),
        }
    }
}

#[wasm_bindgen]
impl WebScene {
    /// Add a generic Object3D (group, helper, etc.) to the scene.
    #[wasm_bindgen(js_name = addObject)]
    pub fn add_object(&mut self, obj: &mut WebObject3D) -> WebObjectHandle {
        let o = obj
            .inner
            .take()
            .unwrap_or_else(crate::core::Object3D::group);
        WebObjectHandle {
            id: self.inner.add(o),
        }
    }

    /// Remove an object from the scene (by handle).
    pub fn remove(&mut self, handle: &WebObjectHandle) {
        self.inner.arena.remove_child(handle.id);
    }

    /// Replace a mesh's geometry positions in place. Used for morph-target
    /// vertex blending and any dynamic vertex animation.
    #[wasm_bindgen(js_name = setMeshPositions)]
    pub fn set_mesh_positions(&mut self, handle: &WebObjectHandle, positions: Vec<f32>) {
        if let Some(obj) = self.inner.arena.get_mut(handle.id) {
            match &mut obj.kind {
                crate::core::ObjectKind::Mesh(mesh) => {
                    let mut new_geom = (*mesh.geometry).clone();
                    new_geom
                        .set_attribute("position", crate::core::BufferAttribute::new(positions, 3));
                    mesh.geometry = std::sync::Arc::new(new_geom);
                }
                crate::core::ObjectKind::SkinnedMesh(sm) => {
                    let mut new_geom = (*sm.geometry).clone();
                    new_geom
                        .set_attribute("position", crate::core::BufferAttribute::new(positions, 3));
                    sm.geometry = std::sync::Arc::new(new_geom);
                }
                _ => {}
            }
        }
    }

    /// Replace a mesh's geometry normals in place.
    #[wasm_bindgen(js_name = setMeshNormals)]
    pub fn set_mesh_normals(&mut self, handle: &WebObjectHandle, normals: Vec<f32>) {
        if let Some(obj) = self.inner.arena.get_mut(handle.id) {
            if let crate::core::ObjectKind::Mesh(mesh) = &mut obj.kind {
                let mut new_geom = (*mesh.geometry).clone();
                new_geom.set_attribute("normal", crate::core::BufferAttribute::new(normals, 3));
                mesh.geometry = std::sync::Arc::new(new_geom);
            }
        }
    }

    /// Update a skinned mesh's bone matrices. Each matrix is 16 floats
    /// (column-major); the caller passes the matrices concatenated.
    /// Re-uploaded to the storage buffer on the next render.
    #[wasm_bindgen(js_name = setBoneMatrices)]
    pub fn set_bone_matrices(&mut self, handle: &WebObjectHandle, matrices: Vec<f32>) {
        if let Some(obj) = self.inner.arena.get_mut(handle.id) {
            if let crate::core::ObjectKind::SkinnedMesh(sm) = &mut obj.kind {
                let mut new_skel = (*sm.skeleton).clone();
                let mat_count = matrices.len() / 16;
                new_skel.bone_matrices.clear();
                for i in 0..mat_count {
                    let mut e = [0.0_f32; 16];
                    e.copy_from_slice(&matrices[i * 16..(i + 1) * 16]);
                    new_skel
                        .bone_matrices
                        .push(crate::math::Matrix4 { elements: e });
                }
                sm.skeleton = std::sync::Arc::new(new_skel);
            }
        }
    }

    /// Update a skinned mesh's per-vertex joint indices.
    #[wasm_bindgen(js_name = setSkinJoints)]
    pub fn set_skin_joints(&mut self, handle: &WebObjectHandle, joints: Vec<f32>) {
        if let Some(obj) = self.inner.arena.get_mut(handle.id) {
            if let crate::core::ObjectKind::SkinnedMesh(sm) = &mut obj.kind {
                let mut new_geom = (*sm.geometry).clone();
                new_geom.set_attribute("joint", crate::core::BufferAttribute::new(joints, 4));
                sm.geometry = std::sync::Arc::new(new_geom);
            }
        }
    }

    /// Update a skinned mesh's per-vertex bone weights.
    #[wasm_bindgen(js_name = setSkinWeights)]
    pub fn set_skin_weights(&mut self, handle: &WebObjectHandle, weights: Vec<f32>) {
        if let Some(obj) = self.inner.arena.get_mut(handle.id) {
            if let crate::core::ObjectKind::SkinnedMesh(sm) = &mut obj.kind {
                let mut new_geom = (*sm.geometry).clone();
                new_geom.set_attribute("weight", crate::core::BufferAttribute::new(weights, 4));
                sm.geometry = std::sync::Arc::new(new_geom);
            }
        }
    }

    /// The scene root's object id: `raycaster.intersectObject(scene,
    /// scene.rootId, true)` tests everything in the scene.
    #[wasm_bindgen(getter, js_name = rootId)]
    pub fn root_id(&self) -> f64 {
        object_id_to_f64(self.inner.root)
    }

    /// The handle for an object id (`WebObjectHandle.id`, a hit's
    /// `objectId`), or undefined when no such object is in the scene.
    #[wasm_bindgen(js_name = handleOf)]
    pub fn handle_of(&self, id: f64) -> Option<WebObjectHandle> {
        let id = object_id_from_f64(id)?;
        self.inner.arena.get(id).map(|_| WebObjectHandle { id })
    }

    /// Find the first object whose name matches.
    #[wasm_bindgen(js_name = getObjectByName)]
    pub fn get_object_by_name(&self, name: &str) -> Option<WebObjectHandle> {
        let root = self.inner.root;
        self.inner
            .arena
            .get_object_by_name(root, name)
            .map(|id| WebObjectHandle { id })
    }

    /// Set a name on the object identified by `handle`.
    #[wasm_bindgen(js_name = setName)]
    pub fn set_name(&mut self, handle: &WebObjectHandle, name: &str) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.name = name.into();
        }
    }

    /// Apply a translation to the object's local position.
    pub fn translate(&mut self, handle: &WebObjectHandle, dx: f32, dy: f32, dz: f32) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.position = obj.position + crate::Vector3::new(dx, dy, dz);
        }
    }

    /// Set scale.
    #[wasm_bindgen(js_name = setScale)]
    pub fn set_scale(&mut self, handle: &WebObjectHandle, sx: f32, sy: f32, sz: f32) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.scale = crate::Vector3::new(sx, sy, sz);
        }
    }

    /// Set visibility.
    #[wasm_bindgen(js_name = setVisible)]
    pub fn set_visible(&mut self, handle: &WebObjectHandle, visible: bool) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.visible = visible;
        }
    }

    /// three.js Object3D.renderOrder — lower draws first within transparency class.
    #[wasm_bindgen(js_name = setRenderOrder)]
    pub fn set_render_order(&mut self, handle: &WebObjectHandle, order: i32) {
        if let Some(obj) = self.inner.get_mut(handle.id) {
            obj.render_order = order;
        }
    }

    /// three.js `lookAt`: a light turns its -Z to the world-space target,
    /// anything else its +Z, with the parent's rotation divided out.
    #[wasm_bindgen(js_name = lookAt)]
    pub fn look_at(&mut self, handle: &WebObjectHandle, x: f32, y: f32, z: f32) {
        self.inner
            .arena
            .look_at(handle.id, crate::Vector3::new(x, y, z));
    }

    /// Get the world-space position (after parent transforms).
    #[wasm_bindgen(js_name = getWorldPosition)]
    pub fn get_world_position(&mut self, handle: &WebObjectHandle) -> WebVector3 {
        self.inner.update_world();
        let p = self
            .inner
            .get(handle.id)
            .map(|o| o.world_position())
            .unwrap_or(crate::Vector3::ZERO);
        WebVector3 { inner: p }
    }
}

// ======================================================================
//                    MATH METHOD COMPLETENESS
// ======================================================================

#[wasm_bindgen]
impl WebVector3 {
    pub fn add(&mut self, o: &WebVector3) -> WebVector3 {
        self.inner = self.inner + o.inner;
        WebVector3 { inner: self.inner }
    }
    pub fn sub(&mut self, o: &WebVector3) -> WebVector3 {
        self.inner = self.inner - o.inner;
        WebVector3 { inner: self.inner }
    }
    #[wasm_bindgen(js_name = multiplyScalar)]
    pub fn multiply_scalar(&mut self, s: f32) -> WebVector3 {
        self.inner = self.inner * s;
        WebVector3 { inner: self.inner }
    }
    pub fn length(&self) -> f32 {
        self.inner.length()
    }
    #[wasm_bindgen(js_name = lengthSq)]
    pub fn length_sq(&self) -> f32 {
        self.inner.length_sq()
    }
    pub fn normalize(&mut self) -> WebVector3 {
        self.inner = self.inner.normalize();
        WebVector3 { inner: self.inner }
    }
    pub fn dot(&self, o: &WebVector3) -> f32 {
        self.inner.dot(o.inner)
    }
    pub fn cross(&mut self, o: &WebVector3) -> WebVector3 {
        self.inner = self.inner.cross(o.inner);
        WebVector3 { inner: self.inner }
    }
    #[wasm_bindgen(js_name = distanceTo)]
    pub fn distance_to(&self, o: &WebVector3) -> f32 {
        self.inner.distance_to(o.inner)
    }
    pub fn lerp(&mut self, o: &WebVector3, t: f32) -> WebVector3 {
        self.inner = self.inner.lerp(o.inner, t);
        WebVector3 { inner: self.inner }
    }
    #[wasm_bindgen(js_name = applyMatrix4)]
    pub fn apply_matrix4(&mut self, m: &WebMatrix4) -> WebVector3 {
        self.inner = self.inner.apply_matrix4(&m.inner);
        WebVector3 { inner: self.inner }
    }
    #[wasm_bindgen(js_name = applyQuaternion)]
    pub fn apply_quaternion(&mut self, q: &WebQuaternion) -> WebVector3 {
        let qq = crate::Quaternion::new(q.x, q.y, q.z, q.w);
        self.inner = self.inner.apply_quaternion(qq);
        WebVector3 { inner: self.inner }
    }
}

#[wasm_bindgen]
impl WebColor {
    pub fn r(&self) -> f32 {
        self.inner.r
    }
    pub fn g(&self) -> f32 {
        self.inner.g
    }
    pub fn b(&self) -> f32 {
        self.inner.b
    }
    #[wasm_bindgen(js_name = setRGB)]
    pub fn set_rgb(&mut self, r: f32, g: f32, b: f32) -> WebColor {
        self.inner = crate::Color::new(r, g, b);
        *self
    }
    #[wasm_bindgen(js_name = setHex)]
    pub fn set_hex(&mut self, h: u32) -> WebColor {
        self.inner = crate::Color::from_hex(h);
        *self
    }
    pub fn lerp(&mut self, other: &WebColor, t: f32) -> WebColor {
        let r = self.inner.r + (other.inner.r - self.inner.r) * t;
        let g = self.inner.g + (other.inner.g - self.inner.g) * t;
        let b = self.inner.b + (other.inner.b - self.inner.b) * t;
        self.inner = crate::Color::new(r, g, b);
        *self
    }
    #[wasm_bindgen(js_name = getHex)]
    pub fn get_hex(&self) -> u32 {
        let r = (self.inner.r.clamp(0.0, 1.0) * 255.0) as u32;
        let g = (self.inner.g.clamp(0.0, 1.0) * 255.0) as u32;
        let b = (self.inner.b.clamp(0.0, 1.0) * 255.0) as u32;
        (r << 16) | (g << 8) | b
    }
}

#[wasm_bindgen]
impl WebMatrix4 {
    pub fn multiply(&mut self, m: &WebMatrix4) -> WebMatrix4 {
        self.inner = self.inner.multiply(&m.inner);
        WebMatrix4 { inner: self.inner }
    }
    #[wasm_bindgen(js_name = makeTranslation)]
    pub fn make_translation(x: f32, y: f32, z: f32) -> WebMatrix4 {
        WebMatrix4 {
            inner: crate::Matrix4::translation(crate::Vector3::new(x, y, z)),
        }
    }
    #[wasm_bindgen(js_name = makeScale)]
    pub fn make_scale(x: f32, y: f32, z: f32) -> WebMatrix4 {
        WebMatrix4 {
            inner: crate::Matrix4::scale(crate::Vector3::new(x, y, z)),
        }
    }
    #[wasm_bindgen(js_name = lookAt)]
    pub fn look_at(eye: &WebVector3, target: &WebVector3, up: &WebVector3) -> WebMatrix4 {
        WebMatrix4 {
            inner: crate::Matrix4::look_at(eye.inner, target.inner, up.inner),
        }
    }
    pub fn determinant(&self) -> f32 {
        self.inner.determinant()
    }
}

#[wasm_bindgen]
impl WebQuaternion {
    pub fn normalize(&mut self) -> WebQuaternion {
        let q = crate::Quaternion::new(self.x, self.y, self.z, self.w).normalize();
        self.x = q.x;
        self.y = q.y;
        self.z = q.z;
        self.w = q.w;
        *self
    }
    pub fn invert(&mut self) -> WebQuaternion {
        let q = crate::Quaternion::new(self.x, self.y, self.z, self.w).invert();
        self.x = q.x;
        self.y = q.y;
        self.z = q.z;
        self.w = q.w;
        *self
    }
    pub fn multiply(&mut self, o: &WebQuaternion) -> WebQuaternion {
        let a = crate::Quaternion::new(self.x, self.y, self.z, self.w);
        let b = crate::Quaternion::new(o.x, o.y, o.z, o.w);
        let c = a.multiply(b);
        self.x = c.x;
        self.y = c.y;
        self.z = c.z;
        self.w = c.w;
        *self
    }
    pub fn slerp(&mut self, o: &WebQuaternion, t: f32) -> WebQuaternion {
        let a = crate::Quaternion::new(self.x, self.y, self.z, self.w);
        let b = crate::Quaternion::new(o.x, o.y, o.z, o.w);
        let c = a.slerp(b, t);
        self.x = c.x;
        self.y = c.y;
        self.z = c.z;
        self.w = c.w;
        *self
    }
    pub fn dot(&self, o: &WebQuaternion) -> f32 {
        let a = crate::Quaternion::new(self.x, self.y, self.z, self.w);
        let b = crate::Quaternion::new(o.x, o.y, o.z, o.w);
        a.dot(b)
    }
    #[wasm_bindgen(js_name = setFromAxisAngle)]
    pub fn set_from_axis_angle(&mut self, axis: &WebVector3, angle: f32) -> WebQuaternion {
        let q = crate::Quaternion::from_axis_angle(axis.inner, angle);
        self.x = q.x;
        self.y = q.y;
        self.z = q.z;
        self.w = q.w;
        *self
    }
}

// ======================================================================
//                     MATH UTILITIES (THREE.MathUtils)
// ======================================================================

#[wasm_bindgen]
pub struct WebMathUtils;

#[wasm_bindgen]
impl WebMathUtils {
    pub fn clamp(v: f32, min: f32, max: f32) -> f32 {
        v.clamp(min, max)
    }
    pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
        a + (b - a) * t
    }
    #[wasm_bindgen(js_name = degToRad)]
    pub fn deg_to_rad(d: f32) -> f32 {
        d.to_radians()
    }
    #[wasm_bindgen(js_name = radToDeg)]
    pub fn rad_to_deg(r: f32) -> f32 {
        r.to_degrees()
    }
    #[wasm_bindgen(js_name = mapLinear)]
    pub fn map_linear(x: f32, a1: f32, a2: f32, b1: f32, b2: f32) -> f32 {
        b1 + (x - a1) * (b2 - b1) / (a2 - a1)
    }
    #[wasm_bindgen(js_name = smoothstep)]
    pub fn smoothstep(x: f32, min: f32, max: f32) -> f32 {
        if x <= min {
            return 0.0;
        }
        if x >= max {
            return 1.0;
        }
        let t = (x - min) / (max - min);
        t * t * (3.0 - 2.0 * t)
    }
    #[wasm_bindgen(js_name = euclideanModulo)]
    pub fn euclidean_modulo(n: f32, m: f32) -> f32 {
        ((n % m) + m) % m
    }
    #[wasm_bindgen(js_name = isPowerOfTwo)]
    pub fn is_power_of_two(n: u32) -> bool {
        n != 0 && (n & (n - 1)) == 0
    }
}

// ======================================================================
//                  BUFFER GEOMETRY + BUFFER ATTRIBUTE
// ======================================================================

#[wasm_bindgen]
pub struct WebBufferAttribute {
    pub(crate) inner: crate::BufferAttribute,
}

#[wasm_bindgen]
impl WebBufferAttribute {
    #[wasm_bindgen(constructor)]
    pub fn new(array: Vec<f32>, item_size: usize) -> WebBufferAttribute {
        WebBufferAttribute {
            inner: crate::BufferAttribute::new(array, item_size),
        }
    }
    pub fn count(&self) -> usize {
        self.inner.count()
    }
    #[wasm_bindgen(js_name = itemSize, getter)]
    pub fn item_size(&self) -> usize {
        self.inner.item_size
    }
    pub fn array(&self) -> Vec<f32> {
        self.inner.array.clone()
    }
}

#[wasm_bindgen]
pub struct WebBufferGeometry {
    pub(crate) inner: Arc<crate::BufferGeometry>,
}

#[wasm_bindgen]
impl WebBufferGeometry {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebBufferGeometry {
        WebBufferGeometry {
            inner: Arc::new(crate::BufferGeometry::new()),
        }
    }
    #[wasm_bindgen(js_name = setAttribute)]
    pub fn set_attribute(&mut self, name: &str, attr: WebBufferAttribute) {
        Arc::make_mut(&mut self.inner).set_attribute(name, attr.inner);
    }
    #[wasm_bindgen(js_name = setIndex)]
    pub fn set_index(&mut self, indices: Vec<u32>) {
        Arc::make_mut(&mut self.inner).set_index(indices);
    }
    #[wasm_bindgen(js_name = computeBoundingBox)]
    pub fn compute_bounding_box(&mut self) -> WebBox3 {
        WebBox3 {
            inner: Arc::make_mut(&mut self.inner).compute_bounding_box(),
        }
    }
    #[wasm_bindgen(js_name = computeBoundingSphere)]
    pub fn compute_bounding_sphere(&mut self) -> WebSphere {
        WebSphere {
            inner: Arc::make_mut(&mut self.inner).compute_bounding_sphere(),
        }
    }
    #[wasm_bindgen(js_name = computeVertexNormals)]
    pub fn compute_vertex_normals(&mut self) {
        crate::compute_vertex_normals(Arc::make_mut(&mut self.inner));
    }
    #[wasm_bindgen(js_name = hasAttribute)]
    pub fn has_attribute(&self, name: &str) -> bool {
        self.inner.get_attribute(name).is_some()
    }
    #[wasm_bindgen(js_name = drawCount)]
    pub fn draw_count(&self) -> usize {
        self.inner.draw_count()
    }

    /// Group triangles into polygons: `counts[i]` consecutive triangles, in
    /// index order, came from source polygon `i` (a quad is `2`). Wireframes
    /// then outline the polygons instead of drawing the fan diagonals. See
    /// `BufferGeometry::polygons`.
    ///
    /// Call after the last `setIndex` / `position` write — both drop the
    /// grouping. Throws unless every count is at least one and they sum to the
    /// geometry's triangle count; the geometry is left ungrouped then.
    #[wasm_bindgen(js_name = setPolygons)]
    pub fn set_polygons(&mut self, counts: Vec<u32>) -> Result<(), JsValue> {
        let triangles = self.inner.triangle_count();
        let sum: u64 = counts.iter().map(|&n| n as u64).sum();
        let geometry = Arc::make_mut(&mut self.inner);
        if let Some(i) = counts.iter().position(|&n| n == 0) {
            geometry.polygons = None;
            return Err(JsValue::from_str(&format!(
                "setPolygons: polygon {i} has zero triangles"
            )));
        }
        if sum != triangles as u64 {
            geometry.polygons = None;
            return Err(JsValue::from_str(&format!(
                "setPolygons: counts sum to {sum} triangles but the geometry draws {triangles}"
            )));
        }
        geometry.set_polygons(counts);
        Ok(())
    }

    /// Triangles per polygon, or `undefined` when there is no grouping (or
    /// the one set no longer covers the triangles).
    #[wasm_bindgen(js_name = polygonCounts)]
    pub fn polygon_counts(&self) -> Option<Vec<u32>> {
        self.inner.polygon_counts().map(|p| p.to_vec())
    }

    /// threers extension: pair adjacent triangles back into quads (Blender's
    /// "Tris to Quads") — for glTF/STL imports, which carry triangles only.
    /// Reorders the index so each quad's triangles are consecutive and sets
    /// the polygon grouping; no vertex changes. Angles in radians, both
    /// defaulting to 40°. Returns how many quads were formed. See
    /// `BufferGeometry::infer_quads`.
    #[wasm_bindgen(js_name = inferQuads)]
    pub fn infer_quads(
        &mut self,
        max_face_angle: Option<f32>,
        max_shape_angle: Option<f32>,
    ) -> u32 {
        let d = crate::core::DEFAULT_INFER_QUADS_ANGLE;
        Arc::make_mut(&mut self.inner)
            .infer_quads(max_face_angle.unwrap_or(d), max_shape_angle.unwrap_or(d)) as u32
    }

    /// threers extension: Catmull–Clark subdivision, `levels` rounds (default
    /// 1, at most 6 — each multiplies the face count by about 4). Returns a
    /// new geometry: indexed, every face a quad grouped as a polygon, with
    /// `position` and smooth `normal` only (UVs and other attributes are
    /// dropped). The cage is this geometry's polygons — its triangles where
    /// there is no grouping — welded by position. `sharpBoundary` (default
    /// true) holds open borders in place. See `BufferGeometry::subdivide_with`.
    #[wasm_bindgen(js_name = subdivide)]
    pub fn subdivide(
        &self,
        levels: Option<u32>,
        sharp_boundary: Option<bool>,
    ) -> Result<WebBufferGeometry, JsValue> {
        const MAX_LEVELS: u32 = 6;
        let levels = levels.unwrap_or(1);
        if levels > MAX_LEVELS {
            return Err(JsValue::from_str(&format!(
                "subdivide: levels must be 0..={MAX_LEVELS}, got {levels}"
            )));
        }
        let options = crate::geometries::SubdivisionOptions {
            sharp_boundary: sharp_boundary.unwrap_or(true),
            ..Default::default()
        };
        Ok(WebBufferGeometry {
            inner: Arc::new(self.inner.subdivide_with(levels as usize, &options)),
        })
    }

    /// The faces a polygon-capable writer emits (`BufferGeometry::faces`),
    /// flattened as `[n, v0 … v(n-1), n, …]`: one corner loop per polygon whose
    /// outline is recoverable, its triangles one by one otherwise, and every
    /// triangle on its own without a grouping. Corners are vertex indices.
    #[wasm_bindgen(js_name = faces)]
    pub fn faces(&self) -> Vec<u32> {
        let mut out = Vec::with_capacity(self.inner.triangle_count() * 4);
        for face in self.inner.faces() {
            out.push(face.len() as u32);
            out.extend_from_slice(&face);
        }
        out
    }
}

// Readback accessors. Not feature-gated: the shim's `QuadGeometry` and
// `computeVertexNormals` read generated buffers back in every build, not only
// in builds with `mesh-bvh`.
#[wasm_bindgen]
impl WebBufferGeometry {
    #[wasm_bindgen(js_name = getAttributeArray)]
    pub fn get_attribute_array(&self, name: &str) -> Option<Vec<f32>> {
        self.inner.get_attribute(name).map(|a| a.array.clone())
    }

    #[wasm_bindgen(js_name = getAttributeItemSize)]
    pub fn get_attribute_item_size(&self, name: &str) -> Option<usize> {
        self.inner.get_attribute(name).map(|a| a.item_size)
    }

    #[wasm_bindgen(js_name = getIndexArray)]
    pub fn get_index_array(&self) -> Option<Vec<u32>> {
        self.inner.index.clone()
    }

    /// Every attribute's name, sorted, so a reader can copy all of them.
    #[wasm_bindgen(js_name = attributeNames)]
    pub fn attribute_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.inner.attributes.keys().cloned().collect();
        names.sort();
        names
    }

    /// three.js `groups`, flattened as `[start, count, materialIndex, …]`.
    #[wasm_bindgen(js_name = groupsArray)]
    pub fn groups_array(&self) -> Vec<u32> {
        self.inner
            .groups
            .iter()
            .flat_map(|g| [g.start, g.count, g.material_index])
            .collect()
    }
}

// Convert a user-built BufferGeometry into a WebGeometry handle.
#[wasm_bindgen]
impl WebGeometry {
    #[wasm_bindgen(js_name = fromBufferGeometry)]
    pub fn from_buffer_geometry(g: WebBufferGeometry) -> WebGeometry {
        WebGeometry { inner: g.inner }
    }
}

// ======================================================================
//                         MESH BVH (feature mesh-bvh)
// ======================================================================

#[cfg(all(target_arch = "wasm32", feature = "mesh-bvh"))]
#[wasm_bindgen]
pub struct WebMeshBvh {
    pub(crate) inner: Arc<crate::mesh_bvh::MeshBvh>,
}

#[cfg(all(target_arch = "wasm32", feature = "mesh-bvh"))]
#[wasm_bindgen]
impl WebMeshBvh {
    #[wasm_bindgen(constructor)]
    pub fn new(geometry: &WebBufferGeometry) -> Result<WebMeshBvh, JsValue> {
        Self::new_with_options(geometry, 40, 10)
    }

    #[wasm_bindgen(js_name = newWithOptions)]
    pub fn new_with_options(
        geometry: &WebBufferGeometry,
        max_depth: u32,
        max_leaf_tris: u32,
    ) -> Result<WebMeshBvh, JsValue> {
        Self::new_with_options_full(
            geometry,
            max_depth,
            max_leaf_tris,
            crate::mesh_bvh::CENTER,
            0,
            0,
            false,
        )
    }

    #[wasm_bindgen(js_name = newWithOptionsFull)]
    pub fn new_with_options_full(
        geometry: &WebBufferGeometry,
        max_depth: u32,
        max_leaf_tris: u32,
        strategy: u32,
        offset: u32,
        count: u32,
        indirect: bool,
    ) -> Result<WebMeshBvh, JsValue> {
        // Spread the default rather than listing every field: this broke once
        // already, when `split_degenerate` was added to the struct and only the
        // wasm construction was left behind — so the browser build of mesh-BVH
        // stopped compiling while every native check stayed green. The default
        // is also what keeps these APIs behaving as the native ones do, which is
        // the point of mirroring three-mesh-bvh's interface.
        let options = crate::mesh_bvh::BuildOptions {
            strategy,
            max_depth,
            max_leaf_tris,
            offset,
            count,
            indirect,
            ..Default::default()
        };
        let bvh = crate::mesh_bvh::MeshBvh::build(&geometry.inner, options)
            .ok_or_else(|| JsValue::from_str("failed to build MeshBVH"))?;
        Ok(WebMeshBvh {
            inner: Arc::new(bvh),
        })
    }

    /// Packed hits: per entry `[distance, px, py, pz, face_index, u, v]`.
    pub fn raycast(
        &self,
        ox: f32,
        oy: f32,
        oz: f32,
        dx: f32,
        dy: f32,
        dz: f32,
        near: f32,
        far: f32,
    ) -> Vec<f32> {
        let ray = crate::Ray::new(
            crate::Vector3::new(ox, oy, oz),
            crate::Vector3::new(dx, dy, dz),
        );
        let hits = self.inner.raycast(&ray, near, far, true);
        pack_hits(&hits)
    }

    /// Closest hit packed as `[distance, px, py, pz, face_index, u, v]`, or empty vec.
    #[wasm_bindgen(js_name = raycastFirst)]
    pub fn raycast_first(
        &self,
        ox: f32,
        oy: f32,
        oz: f32,
        dx: f32,
        dy: f32,
        dz: f32,
        near: f32,
        far: f32,
        side: u32,
    ) -> Vec<f32> {
        let ray = crate::Ray::new(
            crate::Vector3::new(ox, oy, oz),
            crate::Vector3::new(dx, dy, dz),
        );
        match self.inner.raycast_first_with_side(&ray, near, far, side) {
            Some(h) => pack_hits(&[h]),
            None => Vec::new(),
        }
    }

    #[wasm_bindgen(js_name = resolveTriangleIndex)]
    pub fn resolve_triangle_index(&self, bvh_triangle_index: u32) -> i32 {
        match self
            .inner
            .resolve_triangle_index(bvh_triangle_index as usize)
        {
            Some(i) => i as i32,
            None => -1,
        }
    }

    /// Packed triangle pairs: `[ia, ib, ia, ib, ...]` (BVH-layout indices).
    #[wasm_bindgen(js_name = bvhcast)]
    pub fn bvhcast(&self, other: &WebMeshBvh, matrix: &[f32]) -> Vec<u32> {
        if matrix.len() < 16 {
            return Vec::new();
        }
        let mut elems = [0.0f32; 16];
        elems.copy_from_slice(&matrix[..16]);
        let m = crate::Matrix4 { elements: elems };
        let pairs = self.inner.bvhcast(&other.inner, &m);
        let mut out = Vec::with_capacity(pairs.len() * 2);
        for (a, b) in pairs {
            out.push(a as u32);
            out.push(b as u32);
        }
        out
    }

    #[wasm_bindgen(js_name = getBoundingBox)]
    pub fn get_bounding_box(&self) -> WebBox3 {
        WebBox3 {
            inner: self.inner.bounding_box(),
        }
    }

    #[wasm_bindgen(js_name = nodeBuffer)]
    pub fn node_buffer(&self) -> Vec<f32> {
        self.inner.node_buffer().to_vec()
    }

    #[wasm_bindgen(js_name = nodeCount)]
    pub fn node_count(&self) -> usize {
        self.inner.node_count()
    }

    #[wasm_bindgen(js_name = triangleCount)]
    pub fn triangle_count(&self) -> usize {
        self.inner.triangle_count()
    }

    #[wasm_bindgen(js_name = triangleIndices)]
    pub fn triangle_indices(&self) -> Vec<u32> {
        self.inner
            .triangle_indices()
            .iter()
            .flat_map(|(a, b, c)| [*a, *b, *c])
            .collect()
    }

    pub fn positions(&self) -> Vec<f32> {
        self.inner.positions().to_vec()
    }

    #[wasm_bindgen(js_name = triangleOrder)]
    pub fn triangle_order(&self) -> Vec<u32> {
        self.inner
            .triangle_order()
            .iter()
            .map(|&i| i as u32)
            .collect()
    }

    #[wasm_bindgen(js_name = refit)]
    pub fn refit(&mut self, positions: &[f32]) {
        Arc::make_mut(&mut self.inner).refit(positions);
    }

    #[wasm_bindgen(js_name = intersectsBox)]
    pub fn intersects_box(
        &self,
        min_x: f32,
        min_y: f32,
        min_z: f32,
        max_x: f32,
        max_y: f32,
        max_z: f32,
    ) -> bool {
        let b = crate::Box3::new(
            crate::Vector3::new(min_x, min_y, min_z),
            crate::Vector3::new(max_x, max_y, max_z),
        );
        self.inner.intersects_box(&b)
    }

    #[wasm_bindgen(js_name = intersectsSphere)]
    pub fn intersects_sphere(&self, cx: f32, cy: f32, cz: f32, radius: f32) -> bool {
        let s = crate::Sphere::new(crate::Vector3::new(cx, cy, cz), radius);
        self.inner.intersects_sphere(&s)
    }

    /// Closest point: `[px, py, pz, distance, face_index]`.
    #[wasm_bindgen(js_name = closestPointToPoint)]
    pub fn closest_point_to_point(&self, px: f32, py: f32, pz: f32) -> Vec<f32> {
        let (point, dist, tri) = self
            .inner
            .closest_point_to_point(crate::Vector3::new(px, py, pz));
        vec![point.x, point.y, point.z, dist, tri as f32]
    }

    /// Serialize to flat arrays for JS: version, nodeBuffer, triangleOrder, triangleIndices, positions.
    #[wasm_bindgen(js_name = serialize)]
    pub fn serialize(&self) -> js_sys::Array {
        let data = self.inner.serialize();
        let arr = js_sys::Array::new();
        arr.push(&JsValue::from_f64(data.version as f64));
        arr.push(&js_sys::Float32Array::from(data.node_buffer.as_slice()).into());
        arr.push(&js_sys::Uint32Array::from(data.triangle_order.as_slice()).into());
        arr.push(&js_sys::Uint32Array::from(data.triangle_indices.as_slice()).into());
        arr.push(&js_sys::Float32Array::from(data.positions.as_slice()).into());
        arr
    }

    #[wasm_bindgen(js_name = deserialize)]
    pub fn deserialize(
        version: u32,
        node_buffer: &[f32],
        triangle_order: &[u32],
        triangle_indices: &[u32],
        positions: &[f32],
    ) -> Result<WebMeshBvh, JsValue> {
        let data = crate::mesh_bvh::SerializedMeshBvh {
            version,
            node_buffer: node_buffer.to_vec(),
            triangle_order: triangle_order.to_vec(),
            triangle_indices: triangle_indices.to_vec(),
            positions: positions.to_vec(),
        };
        let bvh = crate::mesh_bvh::MeshBvh::deserialize(data)
            .ok_or_else(|| JsValue::from_str("failed to deserialize MeshBVH"))?;
        Ok(WebMeshBvh {
            inner: Arc::new(bvh),
        })
    }
}

#[cfg(all(target_arch = "wasm32", feature = "mesh-bvh"))]
fn pack_hits(hits: &[crate::mesh_bvh::BvhHit]) -> Vec<f32> {
    let mut out = Vec::with_capacity(hits.len() * 7);
    for h in hits {
        out.push(h.distance);
        out.push(h.point.x);
        out.push(h.point.y);
        out.push(h.point.z);
        out.push(h.face_index as f32);
        out.push(h.uv.x);
        out.push(h.uv.y);
    }
    out
}

#[cfg(all(target_arch = "wasm32", feature = "mesh-bvh"))]
#[wasm_bindgen]
impl WebBufferGeometry {
    #[wasm_bindgen(js_name = computeBoundsTree)]
    pub fn compute_bounds_tree(
        &mut self,
        max_depth: u32,
        max_leaf_tris: u32,
    ) -> Result<WebMeshBvh, JsValue> {
        self.compute_bounds_tree_full(
            max_depth,
            max_leaf_tris,
            crate::mesh_bvh::CENTER,
            0,
            0,
            false,
        )
    }

    #[wasm_bindgen(js_name = computeBoundsTreeFull)]
    pub fn compute_bounds_tree_full(
        &mut self,
        max_depth: u32,
        max_leaf_tris: u32,
        strategy: u32,
        offset: u32,
        count: u32,
        indirect: bool,
    ) -> Result<WebMeshBvh, JsValue> {
        // Spread the default rather than listing every field: this broke once
        // already, when `split_degenerate` was added to the struct and only the
        // wasm construction was left behind — so the browser build of mesh-BVH
        // stopped compiling while every native check stayed green. The default
        // is also what keeps these APIs behaving as the native ones do, which is
        // the point of mirroring three-mesh-bvh's interface.
        let options = crate::mesh_bvh::BuildOptions {
            strategy,
            max_depth,
            max_leaf_tris,
            offset,
            count,
            indirect,
            ..Default::default()
        };
        let bvh = Arc::make_mut(&mut self.inner)
            .compute_bounds_tree(options)
            .ok_or_else(|| JsValue::from_str("failed to build bounds tree"))?;
        Ok(WebMeshBvh { inner: bvh })
    }

    #[wasm_bindgen(js_name = disposeBoundsTree)]
    pub fn dispose_bounds_tree(&mut self) {
        Arc::make_mut(&mut self.inner).dispose_bounds_tree();
    }

    #[wasm_bindgen(js_name = hasBoundsTree)]
    pub fn has_bounds_tree(&self) -> bool {
        self.inner.bounds_tree.is_some()
    }
}

#[cfg(all(target_arch = "wasm32", feature = "mesh-bvh"))]
#[wasm_bindgen(js_name = mergeGeometries)]
pub fn merge_geometries(geometries: Vec<WebBufferGeometry>) -> Result<WebBufferGeometry, JsValue> {
    if geometries.is_empty() {
        return Err(JsValue::from_str("mergeGeometries: empty input"));
    }
    let refs: Vec<crate::BufferGeometry> = geometries.iter().map(|g| (*g.inner).clone()).collect();
    let merged = crate::merge_geometries(&refs)
        .ok_or_else(|| JsValue::from_str("mergeGeometries: incompatible geometries"))?;
    Ok(WebBufferGeometry {
        inner: Arc::new(merged),
    })
}

// ---------------------------------------------------------------------------
// Browser animation export (native-codec): GIF / APNG / WebM / MP4 from RGBA frames
// ---------------------------------------------------------------------------

#[cfg(feature = "native-codec")]
fn js_rgba_frames(frames: &js_sys::Array) -> Result<Vec<Vec<u8>>, JsValue> {
    let n = frames.length() as usize;
    if n == 0 {
        return Err(JsValue::from_str("encode: need at least one frame"));
    }
    let mut out = Vec::with_capacity(n);
    for i in 0..frames.length() {
        let v = frames.get(i);
        let u8a = js_sys::Uint8Array::new(&v);
        let mut buf = vec![0u8; u8a.length() as usize];
        u8a.copy_to(&mut buf);
        out.push(buf);
    }
    Ok(out)
}

#[cfg(feature = "native-codec")]
fn encode_browser_animation(
    width: u32,
    height: u32,
    fps: u32,
    codec: crate::BrowserCodec,
    transparent: bool,
    gif_colors: u16,
    frames: &js_sys::Array,
) -> Result<js_sys::Uint8Array, JsValue> {
    let collected = js_rgba_frames(frames)?;
    let opts = crate::AnimationEncodeOptions {
        width,
        height,
        fps: fps.max(1),
        codec,
        transparent,
        gif_colors: gif_colors.clamp(2, 256),
    };
    let bytes = crate::encode_animation_rgba(&opts, collected)
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
    Ok(js_sys::Uint8Array::from(bytes.as_slice()))
}

/// Encode RGBA frames to an animated GIF (`native-codec` feature).
#[cfg(feature = "native-codec")]
#[wasm_bindgen(js_name = encodeGifRgba)]
pub fn encode_gif_rgba(
    width: u32,
    height: u32,
    fps: u32,
    colors: u16,
    transparent: bool,
    frames: js_sys::Array,
) -> Result<js_sys::Uint8Array, JsValue> {
    encode_browser_animation(
        width,
        height,
        fps,
        crate::BrowserCodec::Gif,
        transparent,
        colors,
        &frames,
    )
}

/// Encode RGBA frames to an animated PNG (`native-codec` feature).
#[cfg(feature = "native-codec")]
#[wasm_bindgen(js_name = encodeApngRgba)]
pub fn encode_apng_rgba(
    width: u32,
    height: u32,
    fps: u32,
    transparent: bool,
    frames: js_sys::Array,
) -> Result<js_sys::Uint8Array, JsValue> {
    encode_browser_animation(
        width,
        height,
        fps,
        crate::BrowserCodec::Apng,
        transparent,
        256,
        &frames,
    )
}

/// Encode RGBA frames to a VP9 WebM (`native-codec` feature).
/// Width and height must be multiples of 8.
#[cfg(feature = "native-codec")]
#[wasm_bindgen(js_name = encodeWebmRgba)]
pub fn encode_webm_rgba(
    width: u32,
    height: u32,
    fps: u32,
    transparent: bool,
    frames: js_sys::Array,
) -> Result<js_sys::Uint8Array, JsValue> {
    encode_browser_animation(
        width,
        height,
        fps,
        crate::BrowserCodec::Webm,
        transparent,
        256,
        &frames,
    )
}

/// Encode RGBA frames to an H.264 MP4 (`native-codec` feature).
/// Width and height must be even; transparency is not supported.
#[cfg(feature = "native-codec")]
#[wasm_bindgen(js_name = encodeMp4Rgba)]
pub fn encode_mp4_rgba(
    width: u32,
    height: u32,
    fps: u32,
    frames: js_sys::Array,
) -> Result<js_sys::Uint8Array, JsValue> {
    encode_browser_animation(
        width,
        height,
        fps,
        crate::BrowserCodec::Mp4,
        false,
        256,
        &frames,
    )
}

// ---------------------------------------------------------------------------
// OpenSCAD front end → geometry, for the in-browser gallery. Gated on the
// `openscad` feature (which pulls in the exact CSG kernel + bvh-csg fallback).
// ---------------------------------------------------------------------------

/// A parsed OpenSCAD model as a flat, flat-shaded triangle soup: `positions` and
/// per-face `normals` (9 floats per triangle each), ready to drop straight into a
/// `BufferGeometry`. `error` is set (and the arrays empty) when parsing fails.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub struct ScadGeometry {
    positions: Vec<f32>,
    normals: Vec<f32>,
    triangles: u32,
    error: Option<String>,
}

#[cfg(feature = "openscad")]
#[wasm_bindgen]
impl ScadGeometry {
    #[wasm_bindgen(getter)]
    pub fn positions(&self) -> Vec<f32> {
        self.positions.clone()
    }
    #[wasm_bindgen(getter)]
    pub fn normals(&self) -> Vec<f32> {
        self.normals.clone()
    }
    #[wasm_bindgen(getter)]
    pub fn triangles(&self) -> u32 {
        self.triangles
    }
    #[wasm_bindgen(getter)]
    pub fn error(&self) -> Option<String> {
        self.error.clone()
    }
}

/// Register an in-memory file (text) so `surface`/`import`/`include`/`use` can
/// read it — the browser has no filesystem, so height-fields, meshes, etc. must
/// be supplied this way before calling `scad_geometry`.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub fn scad_register_file(name: &str, contents: &str) {
    crate::register_file(name, contents.as_bytes().to_vec());
}

/// Register an in-memory file from raw bytes (e.g. a binary STL to `import`).
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub fn scad_register_file_bytes(name: &str, bytes: &[u8]) {
    crate::register_file(name, bytes.to_vec());
}

/// Drop every registered in-memory file.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub fn scad_clear_files() {
    crate::clear_files();
}

/// Parse OpenSCAD source and build its solid with the exact CSG kernel (float
/// fallback behind the never-wrong gate), returning a flat-shaded triangle soup.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub fn scad_geometry(src: &str) -> ScadGeometry {
    let solid = match crate::parse_scad(src) {
        Ok(s) => s,
        Err(e) => {
            return ScadGeometry {
                positions: vec![],
                normals: vec![],
                triangles: 0,
                error: Some(e),
            }
        }
    };
    let (positions, normals) = flat_soup(&solid.to_geometry_exact());
    let tris = (positions.len() / 9) as u32;
    ScadGeometry {
        positions,
        normals,
        triangles: tris,
        error: None,
    }
}

/// Parse OpenSCAD source and encode its solid in a mesh format for download.
/// `format` is one of `stl` / `obj` / `off` / `3mf` / `glb` / `fcstd`; returns
/// the encoded bytes (empty on parse error or unknown format).
#[cfg(feature = "openscad")]
#[wasm_bindgen(js_name = scadExport)]
pub fn scad_export(src: &str, format: &str) -> Vec<u8> {
    let solid = match crate::parse_scad(src) {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };
    let g = solid.to_geometry_exact();
    match format {
        "stl" => crate::geometry_to_stl(&g),
        "obj" => crate::geometry_to_obj(&g).into_bytes(),
        "off" => crate::geometry_to_off(&g).into_bytes(),
        "3mf" => crate::geometry_to_3mf(&g),
        "glb" => crate::geometry_to_glb(&g),
        "fcstd" => crate::geometry_to_fcstd(&g, "Model"),
        _ => Vec::new(),
    }
}

/// A geometry as a flat-shaded triangle soup: `(positions, per-face normals)`,
/// 9 floats per triangle each. Expands the index buffer when present.
#[cfg(feature = "openscad")]
fn flat_soup(g: &crate::BufferGeometry) -> (Vec<f32>, Vec<f32>) {
    let verts: Vec<[f32; 3]> = match g.positions() {
        Some(it) => it.map(|v| [v.x, v.y, v.z]).collect(),
        None => Vec::new(),
    };
    let soup: Vec<[f32; 3]> = match &g.index {
        Some(idx) => idx.iter().map(|&i| verts[i as usize]).collect(),
        None => verts,
    };
    let (mut positions, mut normals) = (
        Vec::with_capacity(soup.len() * 3),
        Vec::with_capacity(soup.len() * 3),
    );
    for t in soup.chunks_exact(3) {
        let (a, b, c) = (t[0], t[1], t[2]);
        let (u, v) = (
            [b[0] - a[0], b[1] - a[1], b[2] - a[2]],
            [c[0] - a[0], c[1] - a[1], c[2] - a[2]],
        );
        let mut n = [
            u[1] * v[2] - u[2] * v[1],
            u[2] * v[0] - u[0] * v[2],
            u[0] * v[1] - u[1] * v[0],
        ];
        let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
        if len > 1e-20 {
            n = [n[0] / len, n[1] / len, n[2] / len];
        }
        for vtx in t {
            positions.extend_from_slice(vtx);
            normals.extend_from_slice(&n);
        }
    }
    (positions, normals)
}

// ---------------------------------------------------------------------------
// Parametric 3D-printer assembly (see examples/printer_assembly.rs). Returned to
// JS as a list of flat-shaded, coloured parts — one mesh each, no cross-part CSG.
// ---------------------------------------------------------------------------

/// A parametric printer as a list of coloured parts. `positions(i)`/`normals(i)`
/// are flat-shaded soups; `color(i)` is an `[r,g,b]`.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub struct PrinterScene {
    parts: Vec<(Vec<f32>, Vec<f32>, [f32; 3])>,
}

#[cfg(feature = "openscad")]
#[wasm_bindgen]
impl PrinterScene {
    #[wasm_bindgen(getter)]
    pub fn count(&self) -> usize {
        self.parts.len()
    }
    pub fn positions(&self, i: usize) -> Vec<f32> {
        self.parts.get(i).map(|p| p.0.clone()).unwrap_or_default()
    }
    pub fn normals(&self, i: usize) -> Vec<f32> {
        self.parts.get(i).map(|p| p.1.clone()).unwrap_or_default()
    }
    pub fn color(&self, i: usize) -> Vec<f32> {
        self.parts.get(i).map(|p| p.2.to_vec()).unwrap_or_default()
    }
}

/// Build the parametric printer (all lengths in mm). Mirrors the native
/// `examples/printer_assembly.rs`.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub fn printer_scene(
    bed_x: f32,
    bed_y: f32,
    z_travel: f32,
    ext: f32,
    gantry_z: f32,
    carriage: f32,
    bed_pos: f32,
) -> PrinterScene {
    let parts = crate::build_printer(bed_x, bed_y, z_travel, ext, gantry_z, carriage, bed_pos)
        .into_iter()
        .map(|(g, c)| {
            let (p, n) = flat_soup(&g);
            (p, n, c)
        })
        .collect();
    PrinterScene { parts }
}

/// Build the detailed NEMA 17 motor (see `examples/nema17.rs`) as coloured parts.
#[cfg(feature = "openscad")]
#[wasm_bindgen]
pub fn nema17_scene() -> PrinterScene {
    let parts = crate::build_nema17()
        .into_iter()
        .map(|(g, c)| {
            let (p, n) = flat_soup(&g);
            (p, n, c)
        })
        .collect();
    PrinterScene { parts }
}

// ---------------------------------------------------------------------------
// Subtitles and captions
// ---------------------------------------------------------------------------

/// A timed-text track — the JS face of [`crate::captions::CaptionTrack`].
///
/// ```js
/// const track = CaptionTrack.parse(await (await fetch('dialogue.vtt')).text());
/// const overlay = new CaptionOverlay(track);
/// overlay.setAutoScale(true);
/// // ...then each frame:
/// renderer.renderWithCaptions(scene, camera, overlay, video.currentTime);
/// ```
#[cfg(feature = "captions")]
#[wasm_bindgen]
pub struct WebCaptionTrack {
    inner: crate::captions::CaptionTrack,
}

#[cfg(feature = "captions")]
#[wasm_bindgen]
impl WebCaptionTrack {
    /// An empty track.
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebCaptionTrack {
        WebCaptionTrack {
            inner: crate::captions::CaptionTrack::new(),
        }
    }

    /// Parse SubRip or WebVTT, sniffing the `WEBVTT` magic.
    pub fn parse(text: &str) -> Result<WebCaptionTrack, JsValue> {
        crate::captions::CaptionTrack::parse(text)
            .map(|inner| WebCaptionTrack { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Parse SubRip (`.srt`).
    #[wasm_bindgen(js_name = parseSrt)]
    pub fn parse_srt(text: &str) -> Result<WebCaptionTrack, JsValue> {
        crate::captions::CaptionTrack::parse_srt(text)
            .map(|inner| WebCaptionTrack { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Parse WebVTT (`.vtt`) — what a `<track>` element takes.
    #[wasm_bindgen(js_name = parseVtt)]
    pub fn parse_vtt(text: &str) -> Result<WebCaptionTrack, JsValue> {
        crate::captions::CaptionTrack::parse_vtt(text)
            .map(|inner| WebCaptionTrack { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Append a cue, in seconds.
    #[wasm_bindgen(js_name = addCue)]
    pub fn add_cue(&mut self, start: f64, end: f64, text: &str) {
        self.inner.push(crate::captions::Cue::new(start, end, text));
    }

    /// BCP-47 language tag (`"en"`, `"pt-BR"`).
    #[wasm_bindgen(js_name = setLanguage)]
    pub fn set_language(&mut self, language: &str) {
        self.inner.language = language.to_string();
    }

    /// Human-readable name shown in player menus.
    #[wasm_bindgen(js_name = setLabel)]
    pub fn set_label(&mut self, label: &str) {
        self.inner.label = label.to_string();
    }

    /// Shift every cue by `seconds` (negative moves earlier).
    pub fn shift(&mut self, seconds: f64) {
        self.inner.shift(seconds);
    }

    /// Number of cues.
    #[wasm_bindgen(getter)]
    pub fn length(&self) -> usize {
        self.inner.len()
    }

    /// End time of the last cue, in seconds.
    pub fn duration(&self) -> f64 {
        self.inner.duration()
    }

    /// Text showing at `time` seconds, markup stripped. Empty when nothing is.
    #[wasm_bindgen(js_name = textAt)]
    pub fn text_at(&self, time: f64) -> String {
        self.inner.text_at(time)
    }

    /// Serialize to SubRip.
    #[wasm_bindgen(js_name = toSrt)]
    pub fn to_srt(&self) -> String {
        self.inner.to_srt()
    }

    /// Serialize to WebVTT — feed this to a `<track>` via a Blob URL.
    #[wasm_bindgen(js_name = toVtt)]
    pub fn to_vtt(&self) -> String {
        self.inner.to_vtt()
    }
}

#[cfg(feature = "captions")]
impl Default for WebCaptionTrack {
    fn default() -> Self {
        Self::new()
    }
}

/// A frame-sized caption overlay — the JS face of
/// [`crate::captions::CaptionOverlay`].
///
/// Pass it to [`WebRenderer::render_with_captions`] to have the GPU blend it
/// over the 3D image, or read [`rgba`](Self::rgba) to composite it yourself
/// (e.g. into a 2D canvas `ImageData`).
#[cfg(feature = "captions")]
#[wasm_bindgen]
pub struct WebCaptionOverlay {
    inner: crate::captions::CaptionOverlay,
}

#[cfg(feature = "captions")]
#[wasm_bindgen]
impl WebCaptionOverlay {
    /// An overlay for `track`, using the built-in bitmap face.
    #[wasm_bindgen(constructor)]
    pub fn new(track: &WebCaptionTrack) -> WebCaptionOverlay {
        WebCaptionOverlay {
            inner: crate::captions::CaptionOverlay::new(track.inner.clone()),
        }
    }

    /// Replace the cues.
    #[wasm_bindgen(js_name = setTrack)]
    pub fn set_track(&mut self, track: &WebCaptionTrack) {
        self.inner.set_track(track.inner.clone());
    }

    /// Use a TrueType font for the text (`.ttf` bytes, `glyf` outlines).
    #[wasm_bindgen(js_name = setFont)]
    pub fn set_font(&mut self, ttf: &[u8]) -> Result<(), JsValue> {
        let font = crate::captions::CaptionFont::from_ttf_bytes(ttf)
            .map_err(|e| JsValue::from_str(&format!("font could not be parsed: {e:?}")))?;
        self.inner.painter.font = font;
        self.inner.invalidate();
        Ok(())
    }

    /// Rescale the style with the frame height, treating the current values as
    /// authored for 1080p. Off by default.
    #[wasm_bindgen(js_name = setAutoScale)]
    pub fn set_auto_scale(&mut self, enabled: bool) {
        self.inner.set_auto_scale(enabled);
    }

    /// Type size in pixels.
    #[wasm_bindgen(js_name = setFontSize)]
    pub fn set_font_size(&mut self, px: f32) {
        self.restyle(|s| s.font_size(px));
    }

    /// Text fill color, 0–255 per channel.
    #[wasm_bindgen(js_name = setColor)]
    pub fn set_color(&mut self, r: u8, g: u8, b: u8, a: u8) {
        self.restyle(|s| s.color([r, g, b, a]));
    }

    /// Outline color and half-width in pixels. Width `0` removes it.
    #[wasm_bindgen(js_name = setOutline)]
    pub fn set_outline(&mut self, r: u8, g: u8, b: u8, a: u8, width: f32) {
        self.restyle(|s| s.outline([r, g, b, a], width));
    }

    /// Background box color. Alpha `0` removes the box.
    #[wasm_bindgen(js_name = setBackground)]
    pub fn set_background(&mut self, r: u8, g: u8, b: u8, a: u8) {
        self.restyle(|s| s.background([r, g, b, a]));
    }

    /// Drop shadow color and offset in pixels. Alpha `0` removes it.
    #[wasm_bindgen(js_name = setShadow)]
    pub fn set_shadow(&mut self, r: u8, g: u8, b: u8, a: u8, dx: f32, dy: f32) {
        self.restyle(|s| s.shadow([r, g, b, a], dx, dy));
    }

    /// Distance from the anchored frame edge, in pixels.
    #[wasm_bindgen(js_name = setMargin)]
    pub fn set_margin(&mut self, px: f32) {
        self.restyle(|s| s.margin(px));
    }

    /// Padding inside the background box, in pixels.
    #[wasm_bindgen(js_name = setPadding)]
    pub fn set_padding(&mut self, px: f32) {
        self.restyle(|s| s.padding(px));
    }

    /// Line advance as a multiple of the type size.
    #[wasm_bindgen(js_name = setLineHeight)]
    pub fn set_line_height(&mut self, factor: f32) {
        self.restyle(|s| s.line_height(factor));
    }

    /// Wrap width as a fraction (`0..=1`) of the frame width.
    #[wasm_bindgen(js_name = setMaxWidth)]
    pub fn set_max_width(&mut self, fraction: f32) {
        self.restyle(|s| s.max_width(fraction));
    }

    /// Horizontal alignment: `"left"`, `"center"`, or `"right"`.
    #[wasm_bindgen(js_name = setAlign)]
    pub fn set_align(&mut self, align: &str) {
        let align = match align {
            "left" | "start" => crate::captions::CaptionAlign::Left,
            "right" | "end" => crate::captions::CaptionAlign::Right,
            _ => crate::captions::CaptionAlign::Center,
        };
        self.restyle(|s| s.align(align));
    }

    /// Frame edge to anchor to: `"top"`, `"middle"`, or `"bottom"`.
    #[wasm_bindgen(js_name = setAnchor)]
    pub fn set_anchor(&mut self, anchor: &str) {
        let anchor = match anchor {
            "top" => crate::captions::CaptionAnchor::Top,
            "middle" | "center" => crate::captions::CaptionAnchor::Middle,
            _ => crate::captions::CaptionAnchor::Bottom,
        };
        self.restyle(|s| s.anchor(anchor));
    }

    /// Overlay resolution. [`WebRenderer::render_with_captions`] sets this for
    /// you; call it directly only when compositing by hand.
    #[wasm_bindgen(js_name = setSize)]
    pub fn set_size(&mut self, width: u32, height: u32) {
        self.inner.set_size(width, height);
    }

    /// Rasterize for `time` seconds if needed. Returns whether the buffer
    /// changed — the cue to skip re-uploading on unchanged frames.
    pub fn update(&mut self, time: f64) -> bool {
        self.inner.update(time)
    }

    /// Whether a cue is currently showing.
    #[wasm_bindgen(js_name = isVisible)]
    pub fn is_visible(&self) -> bool {
        self.inner.is_visible()
    }

    /// The RGBA8 overlay buffer, transparent where there is no caption.
    /// Copy it into an `ImageData` to composite in a 2D canvas.
    pub fn rgba(&self) -> Vec<u8> {
        self.inner.rgba().to_vec()
    }
}

#[cfg(feature = "captions")]
impl WebCaptionOverlay {
    /// Apply a style builder and invalidate the cached raster.
    fn restyle(
        &mut self,
        f: impl FnOnce(crate::captions::CaptionStyle) -> crate::captions::CaptionStyle,
    ) {
        // Style off the authored values, not the auto-scaled ones, so
        // repeated setter calls do not compound the rescale.
        let style = f(self.inner.style().clone());
        self.inner.set_style(style);
    }
}

// ---------------------------------------------------------------------------
// NURBS (feature = "nurbs")
// ---------------------------------------------------------------------------
//
// The three.js parity types in `curves::nurbs` were never reachable from JS at
// all — no binding, no shim export. These are the f64 kernel types, which is
// what a caller actually wants on the web side too: exact circles, analytic
// normals, and a tessellator that answers to a tolerance instead of a segment
// count.
//
// Flat `Float64Array`s rather than arrays-of-arrays throughout: one copy across
// the wasm boundary instead of an allocation per control point.

#[cfg(feature = "nurbs")]
#[wasm_bindgen]
pub struct WebNurbsCurve {
    inner: crate::nurbs::NurbsCurve,
}

#[cfg(feature = "nurbs")]
#[wasm_bindgen]
impl WebNurbsCurve {
    /// Build from Cartesian control points (flat `xyz`) and optional weights.
    #[wasm_bindgen(constructor)]
    pub fn new(
        degree: usize,
        knots: Vec<f64>,
        points: Vec<f64>,
        weights: Option<Vec<f64>>,
    ) -> Result<WebNurbsCurve, JsValue> {
        let pts: Vec<[f64; 3]> = points.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect();
        crate::nurbs::NurbsCurve::new(degree, knots, &pts, weights.as_deref())
            .map(|inner| WebNurbsCurve { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// Build from control points already in homogeneous form (flat `xyzw`) —
    /// the layout three.js's `NURBSCurve` and STEP both use.
    #[wasm_bindgen(js_name = fromHomogeneous)]
    pub fn from_homogeneous(
        degree: usize,
        knots: Vec<f64>,
        control: Vec<f64>,
    ) -> Result<WebNurbsCurve, JsValue> {
        let cw: Vec<[f64; 4]> = control
            .chunks_exact(4)
            .map(|c| [c[0], c[1], c[2], c[3]])
            .collect();
        crate::nurbs::NurbsCurve::from_homogeneous(degree, knots, cw)
            .map(|inner| WebNurbsCurve { inner })
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    pub fn degree(&self) -> usize {
        self.inner.degree()
    }

    pub fn knots(&self) -> Vec<f64> {
        self.inner.knots().to_vec()
    }

    #[wasm_bindgen(js_name = controlCount)]
    pub fn control_count(&self) -> usize {
        self.inner.n_control()
    }

    /// `[u_min, u_max]`.
    pub fn domain(&self) -> Vec<f64> {
        let (a, b) = self.inner.domain();
        vec![a, b]
    }

    /// Point at parameter `u` (clamped to the domain) as `[x, y, z]`.
    pub fn point(&self, u: f64) -> Vec<f64> {
        self.inner.point(u).to_vec()
    }

    /// Point at normalized `t ∈ [0, 1]`.
    #[wasm_bindgen(js_name = pointAt)]
    pub fn point_at(&self, t: f64) -> Vec<f64> {
        self.inner.point(self.inner.param_at(t)).to_vec()
    }

    /// Derivatives 0..=`k`, flattened: `[C, C', C'', …]`.
    pub fn derivatives(&self, u: f64, k: usize) -> Vec<f64> {
        self.inner.derivatives(u, k).into_iter().flatten().collect()
    }

    /// Unit tangent, or an empty array at a cusp where none exists.
    pub fn tangent(&self, u: f64) -> Vec<f64> {
        self.inner
            .tangent(u)
            .map(|t| t.to_vec())
            .unwrap_or_default()
    }

    /// Adaptive polyline honouring `tolerance`, flattened `xyz`.
    pub fn tessellate(&self, tolerance: f64) -> Vec<f64> {
        let opts = crate::nurbs::TessellationOptions::with_tolerance(tolerance);
        crate::nurbs::tessellate_curve(&self.inner, &opts)
            .into_iter()
            .flatten()
            .collect()
    }
}

#[cfg(feature = "nurbs")]
#[wasm_bindgen]
pub struct WebNurbsSurface {
    inner: crate::nurbs::NurbsSurface,
}

#[cfg(feature = "nurbs")]
#[wasm_bindgen]
impl WebNurbsSurface {
    /// Build from a Cartesian control grid (flat `xyz`, **u-major**: index
    /// `i * n_v + j`) and optional weights.
    #[wasm_bindgen(constructor)]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        degree_u: usize,
        degree_v: usize,
        knots_u: Vec<f64>,
        knots_v: Vec<f64>,
        n_u: usize,
        n_v: usize,
        points: Vec<f64>,
        weights: Option<Vec<f64>>,
    ) -> Result<WebNurbsSurface, JsValue> {
        let pts: Vec<[f64; 3]> = points.chunks_exact(3).map(|c| [c[0], c[1], c[2]]).collect();
        crate::nurbs::NurbsSurface::new(
            degree_u,
            degree_v,
            knots_u,
            knots_v,
            n_u,
            n_v,
            &pts,
            weights.as_deref(),
        )
        .map(|inner| WebNurbsSurface { inner })
        .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    #[wasm_bindgen(js_name = degreeU)]
    pub fn degree_u(&self) -> usize {
        self.inner.degree_u()
    }

    #[wasm_bindgen(js_name = degreeV)]
    pub fn degree_v(&self) -> usize {
        self.inner.degree_v()
    }

    /// `[u_min, u_max, v_min, v_max]`.
    pub fn domain(&self) -> Vec<f64> {
        let (u0, u1) = self.inner.domain_u();
        let (v0, v1) = self.inner.domain_v();
        vec![u0, u1, v0, v1]
    }

    /// Point at `(u, v)` as `[x, y, z]`.
    pub fn point(&self, u: f64, v: f64) -> Vec<f64> {
        self.inner.point(u, v).to_vec()
    }

    /// Point at normalized `(s, t) ∈ [0, 1]²`.
    #[wasm_bindgen(js_name = pointAt)]
    pub fn point_at(&self, s: f64, t: f64) -> Vec<f64> {
        let (u, v) = self.inner.param_at(s, t);
        self.inner.point(u, v).to_vec()
    }

    /// Analytic unit normal. Empty only if the surface is degenerate over a
    /// whole neighbourhood — poles are handled and do return a normal.
    pub fn normal(&self, u: f64, v: f64) -> Vec<f64> {
        self.inner
            .normal(u, v)
            .map(|n| n.to_vec())
            .unwrap_or_default()
    }

    /// Tessellate to a `BufferGeometry` at the given chord tolerance.
    pub fn tessellate(&self, tolerance: f64) -> WebBufferGeometry {
        WebBufferGeometry {
            inner: Arc::new(crate::geometries::NurbsGeometry::with_tolerance(
                &self.inner,
                tolerance,
            )),
        }
    }

    /// Tessellate on a fixed `u_segments × v_segments` grid.
    #[wasm_bindgen(js_name = tessellateGrid)]
    pub fn tessellate_grid(&self, u_segments: usize, v_segments: usize) -> WebBufferGeometry {
        WebBufferGeometry {
            inner: Arc::new(crate::geometries::NurbsGeometry::with_segments(
                &self.inner,
                u_segments,
                v_segments,
            )),
        }
    }

    /// Did the sampler actually reach `tolerance`, or did its sample ceiling
    /// bind first? A truncated grid otherwise looks identical to a converged one.
    #[wasm_bindgen(js_name = meetsTolerance)]
    pub fn meets_tolerance(&self, tolerance: f64) -> bool {
        let opts = crate::nurbs::TessellationOptions::with_tolerance(tolerance);
        let (pu, pv) = crate::nurbs::tessellate::sample_grid(&self.inner, &opts);
        crate::nurbs::tessellate::sample_grid_meets_tolerance(&self.inner, &pu, &pv, tolerance)
    }

    /// Sweep this surface's defining profile — see the free `nurbs*` builders
    /// for the constructors that produce exact quadrics.
    #[wasm_bindgen(js_name = isRational)]
    pub fn is_rational(&self) -> bool {
        self.inner.is_rational()
    }
}

/// An exact circle as a rational quadratic — not a polyline approximation.
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsCircle)]
pub fn nurbs_circle(cx: f64, cy: f64, cz: f64, radius: f64) -> WebNurbsCurve {
    WebNurbsCurve {
        inner: crate::nurbs::construct::circle(
            [cx, cy, cz],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            radius,
        ),
    }
}

/// An exact circular arc from `start` to `end` radians in the xy-plane.
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsArc)]
pub fn nurbs_arc(cx: f64, cy: f64, cz: f64, radius: f64, start: f64, end: f64) -> WebNurbsCurve {
    WebNurbsCurve {
        inner: crate::nurbs::construct::arc(
            [cx, cy, cz],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            radius,
            start,
            end,
        ),
    }
}

/// An exact sphere. Sampling it reproduces the radius to ~1e-15 at every
/// parameter, unlike a `SphereGeometry` at any segment count.
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsSphere)]
pub fn nurbs_sphere(cx: f64, cy: f64, cz: f64, radius: f64) -> WebNurbsSurface {
    WebNurbsSurface {
        inner: crate::nurbs::construct::sphere([cx, cy, cz], radius),
    }
}

/// An exact cylindrical side surface about `+Z` (no caps).
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsCylinder)]
pub fn nurbs_cylinder(cx: f64, cy: f64, cz: f64, radius: f64, height: f64) -> WebNurbsSurface {
    WebNurbsSurface {
        inner: crate::nurbs::construct::cylinder([cx, cy, cz], [0.0, 0.0, 1.0], radius, height),
    }
}

/// An exact conical side surface about `+Z` (no cap).
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsCone)]
pub fn nurbs_cone(
    apex_x: f64,
    apex_y: f64,
    apex_z: f64,
    base_radius: f64,
    height: f64,
) -> WebNurbsSurface {
    WebNurbsSurface {
        inner: crate::nurbs::construct::cone(
            [apex_x, apex_y, apex_z],
            [0.0, 0.0, 1.0],
            base_radius,
            height,
        ),
    }
}

/// An exact torus about `+Z`.
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsTorus)]
pub fn nurbs_torus(cx: f64, cy: f64, cz: f64, major: f64, minor: f64) -> WebNurbsSurface {
    WebNurbsSurface {
        inner: crate::nurbs::construct::torus([cx, cy, cz], [0.0, 0.0, 1.0], major, minor),
    }
}

/// Revolve a profile curve about an axis through `(px, py, pz)` in direction
/// `(dx, dy, dz)`, sweeping `angle` radians (0 means a full turn).
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsRevolve)]
#[allow(clippy::too_many_arguments)]
pub fn nurbs_revolve(
    profile: &WebNurbsCurve,
    px: f64,
    py: f64,
    pz: f64,
    dx: f64,
    dy: f64,
    dz: f64,
    angle: f64,
) -> WebNurbsSurface {
    WebNurbsSurface {
        inner: crate::nurbs::construct::revolve(&profile.inner, [px, py, pz], [dx, dy, dz], angle),
    }
}

/// Linearly sweep a profile curve along `(dx, dy, dz)`.
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsExtrude)]
pub fn nurbs_extrude(profile: &WebNurbsCurve, dx: f64, dy: f64, dz: f64) -> WebNurbsSurface {
    WebNurbsSurface {
        inner: crate::nurbs::construct::extrude(&profile.inner, [dx, dy, dz]),
    }
}

/// The ruled surface between two curves, made compatible first (they may differ
/// in degree and knot vector).
#[cfg(feature = "nurbs")]
#[wasm_bindgen(js_name = nurbsRuled)]
pub fn nurbs_ruled(a: &WebNurbsCurve, b: &WebNurbsCurve) -> Result<WebNurbsSurface, JsValue> {
    crate::nurbs::construct::ruled(&a.inner, &b.inner)
        .map(|inner| WebNurbsSurface { inner })
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

// ── RLX bridge ──────────────────────────────────────────────────────────
//
// The browser half of `threers::rlx`. Everything the bridge does is pure data
// in and pure data out, so the bindings are plain typed arrays: JS hands over
// an `Uint8Array` of pixels or a `Float32Array` of positions and gets one
// back. `RLX=1 web/build.sh` turns them on; `RLX_GEO=1` adds the geometry set.
//
// Which devices a browser build finds is rlx's answer, not this crate's — ask
// `rlxDevices()` at startup rather than assuming.

/// The rlx backends this build found, comma-separated (e.g. `"WebGpu,Cpu"`).
/// Empty when rlx has none, in which case every call below will fail.
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxDevices)]
pub fn rlx_devices() -> String {
    ::rlx::available_devices()
        .iter()
        .map(|d| format!("{d:?}"))
        .collect::<Vec<_>>()
        .join(",")
}

/// Convolve an RGBA8 frame with a named 3×3 kernel: `box`, `gaussian`,
/// `sharpen`, `laplacian`, `sobel-x`, `sobel-y` or `emboss`.
///
/// Alpha is carried through, and the edges are replicated rather than
/// zero-padded — see [`crate::rlx::ConvFilter`].
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxConvolve)]
pub fn rlx_convolve(
    rgba: &[u8],
    width: u32,
    height: u32,
    kernel: &str,
) -> Result<Vec<u8>, JsValue> {
    use crate::rlx::{preferred_device, ConvFilter, Kernel3x3};
    let kernel = match kernel {
        "box" => Kernel3x3::BOX_BLUR,
        "gaussian" => Kernel3x3::GAUSSIAN,
        "sharpen" => Kernel3x3::SHARPEN,
        "laplacian" => Kernel3x3::LAPLACIAN,
        "sobel-x" => Kernel3x3::SOBEL_X,
        "sobel-y" => Kernel3x3::SOBEL_Y,
        "emboss" => Kernel3x3::EMBOSS,
        other => return Err(JsValue::from_str(&format!("unknown kernel {other}"))),
    };
    ConvFilter::new(width, height, kernel, preferred_device())
        .apply(rgba)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Run `iterations` diffusion passes over a single-channel height grid.
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxDiffuse)]
pub fn rlx_diffuse(
    field: &[f32],
    width: u32,
    height: u32,
    rate: f32,
    iterations: u32,
) -> Result<Vec<f32>, JsValue> {
    use crate::rlx::{preferred_device, Diffusion};
    Diffusion::new(width, height, rate, preferred_device())
        .run(field, iterations as usize)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Smooth a mesh, returning new positions (`[x, y, z, …]`).
///
/// A negative `mu` runs Taubin's λ|μ filter, which keeps the volume; pass 0 for
/// plain Laplacian smoothing, which does not.
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxSmoothMesh)]
pub fn rlx_smooth_mesh(
    positions: &[f32],
    index: &[u32],
    iterations: u32,
    lambda: f32,
    mu: f32,
) -> Result<Vec<f32>, JsValue> {
    use crate::core::{BufferAttribute, BufferGeometry};
    use crate::rlx::{mesh, preferred_device};

    let mut geometry = BufferGeometry::new();
    geometry.set_attribute("position", BufferAttribute::new(positions.to_vec(), 3));
    geometry.set_index(index.to_vec());

    let device = preferred_device();
    let result = if mu < 0.0 {
        mesh::taubin_smooth(&mut geometry, iterations as usize, lambda, mu, device)
    } else {
        mesh::laplacian_smooth(&mut geometry, iterations as usize, lambda, device)
    };
    result.map_err(|e| JsValue::from_str(&e.to_string()))?;
    Ok(geometry
        .get_attribute("position")
        .map(|a| a.array.clone())
        .unwrap_or_default())
}

/// Fit a colour grade carrying `source` onto `target`, both RGBA8 frames of the
/// same size. Returns twelve numbers: the 3×3 matrix row-major, then the bias.
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxFitGrade)]
pub fn rlx_fit_grade(source: &[u8], target: &[u8]) -> Result<Vec<f32>, JsValue> {
    use crate::rlx::{preferred_device, ColorGrade, FitOptions};
    let report = ColorGrade::fit(source, target, &FitOptions::default(), preferred_device())
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
    let mut out = Vec::with_capacity(12);
    for row in report.grade.matrix {
        out.extend_from_slice(&row);
    }
    out.extend_from_slice(&report.grade.bias);
    Ok(out)
}

/// Apply a grade in the twelve-number form [`rlx_fit_grade`] returns.
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxApplyGrade)]
pub fn rlx_apply_grade(rgba: &[u8], grade: &[f32]) -> Result<Vec<u8>, JsValue> {
    use crate::rlx::ColorGrade;
    if grade.len() != 12 {
        return Err(JsValue::from_str("a grade is 9 matrix values then 3 bias"));
    }
    let grade = ColorGrade {
        matrix: [
            [grade[0], grade[1], grade[2]],
            [grade[3], grade[4], grade[5]],
            [grade[6], grade[7], grade[8]],
        ],
        bias: [grade[9], grade[10], grade[11]],
    };
    Ok(grade.apply(rgba))
}

/// Cluster a frame into `count` colours, returned as sRGB `[r, g, b, …]`
/// bytes. May be shorter than asked for — see [`crate::rlx::Palette::extract`].
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxPalette)]
pub fn rlx_palette(rgba: &[u8], count: u32) -> Result<Vec<u8>, JsValue> {
    use crate::rlx::{preferred_device, Palette, PaletteOptions};
    let palette = Palette::extract(
        rgba,
        count as usize,
        &PaletteOptions::default(),
        preferred_device(),
    )
    .map_err(|e| JsValue::from_str(&e.to_string()))?;
    Ok(palette
        .colors
        .iter()
        .flat_map(|c| {
            let e = |v: f32| {
                let s = if v <= 0.0031308 {
                    v * 12.92
                } else {
                    1.055 * v.powf(1.0 / 2.4) - 0.055
                };
                (s.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
            };
            [e(c.r), e(c.g), e(c.b)]
        })
        .collect())
}

/// Snap every pixel of a frame to its nearest entry of a `count`-colour
/// palette extracted from that same frame.
#[cfg(feature = "rlx")]
#[wasm_bindgen(js_name = rlxPosterize)]
pub fn rlx_posterize(rgba: &[u8], count: u32) -> Result<Vec<u8>, JsValue> {
    use crate::rlx::{preferred_device, Palette, PaletteOptions};
    let device = preferred_device();
    let palette = Palette::extract(rgba, count as usize, &PaletteOptions::default(), device)
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
    palette
        .posterize(rgba, device)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// A triangulated height field, ready to hand to `BufferGeometry`.
#[cfg(feature = "rlx-geo")]
#[wasm_bindgen]
pub struct GeoGeometry {
    positions: Vec<f32>,
    normals: Vec<f32>,
    uvs: Vec<f32>,
    index: Vec<u32>,
}

#[cfg(feature = "rlx-geo")]
#[wasm_bindgen]
impl GeoGeometry {
    #[wasm_bindgen(getter)]
    pub fn positions(&self) -> Vec<f32> {
        self.positions.clone()
    }
    #[wasm_bindgen(getter)]
    pub fn normals(&self) -> Vec<f32> {
        self.normals.clone()
    }
    #[wasm_bindgen(getter)]
    pub fn uvs(&self) -> Vec<f32> {
        self.uvs.clone()
    }
    #[wasm_bindgen(getter)]
    pub fn index(&self) -> Vec<u32> {
        self.index.clone()
    }
}

/// Exact Delaunay triangulation of `[x, y, …]` pairs, as triangle indices.
#[cfg(feature = "rlx-geo")]
#[wasm_bindgen(js_name = geoDelaunay)]
pub fn geo_delaunay(points: &[f32]) -> Result<Vec<u32>, JsValue> {
    use crate::math::Vector2;
    let points: Vec<Vector2> = points
        .chunks_exact(2)
        .map(|p| Vector2::new(p[0], p[1]))
        .collect();
    crate::rlx::geo::delaunay_indices(&points).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Scattered `[x, y, z, …]` samples triangulated in xz, with y as the height.
#[cfg(feature = "rlx-geo")]
#[wasm_bindgen(js_name = geoHeightfield)]
pub fn geo_heightfield(points: &[f32]) -> Result<GeoGeometry, JsValue> {
    use crate::math::Vector3;
    let points: Vec<Vector3> = points
        .chunks_exact(3)
        .map(|p| Vector3::new(p[0], p[1], p[2]))
        .collect();
    let geometry = crate::rlx::geo::heightfield_geometry(&points)
        .map_err(|e| JsValue::from_str(&e.to_string()))?;
    let attribute = |name: &str| {
        geometry
            .get_attribute(name)
            .map(|a| a.array.clone())
            .unwrap_or_default()
    };
    Ok(GeoGeometry {
        positions: attribute("position"),
        normals: attribute("normal"),
        uvs: attribute("uv"),
        index: geometry.index.clone().unwrap_or_default(),
    })
}

/// Which site owns each pixel, for sites given as `[x, y, …]` in pixels.
#[cfg(feature = "rlx-geo")]
#[wasm_bindgen(js_name = geoVoronoiLabels)]
pub fn geo_voronoi_labels(sites: &[f32], width: u32, height: u32) -> Vec<u32> {
    use crate::math::Vector2;
    let sites: Vec<Vector2> = sites
        .chunks_exact(2)
        .map(|s| Vector2::new(s[0], s[1]))
        .collect();
    crate::rlx::geo::voronoi_labels(&sites, width, height)
}

/// Distance from every pixel to the nearest cell wall — the field cell
/// textures want. Cost is pixels × sites; keep the site count in the hundreds.
#[cfg(feature = "rlx-geo")]
#[wasm_bindgen(js_name = geoVoronoiWallDistance)]
pub fn geo_voronoi_wall_distance(sites: &[f32], width: u32, height: u32) -> Vec<f32> {
    use crate::math::Vector2;
    let sites: Vec<Vector2> = sites
        .chunks_exact(2)
        .map(|s| Vector2::new(s[0], s[1]))
        .collect();
    crate::rlx::geo::voronoi_wall_distance(&sites, width, height)
}

/// A height grid as a tangent-space normal map, RGBA8 and linear.
#[cfg(feature = "rlx-geo")]
#[wasm_bindgen(js_name = geoNormalMap)]
pub fn geo_normal_map(field: &[f32], width: u32, height: u32, strength: f32) -> Vec<u8> {
    let texture = crate::rlx::geo::normal_map_from_height(field, width, height, strength);
    texture.data.as_ref().clone()
}

// ---------------------------------------------------------------------------
// IK + geared servo plant (planar 3R) — bodies, joints, contacts, materials.
// ---------------------------------------------------------------------------

/// One planar 3R arm with geometric IK, actuator plant, capsule solids,
/// joint reports, and world contacts (floor + obstacle).
///
/// `kind`: `"direct"` | `"qdd"` | `"high"` | `"hydraulic"` | `"tendon"`.
/// Lengths are millimetres.
#[wasm_bindgen]
pub struct WebIkServoPlant {
    world: crate::kinematics::ArmWorld,
    ik: crate::kinematics::Ik,
    q_ik: Vec<f64>,
    label: String,
}

fn ik_for_chain(chain: &crate::kinematics::SerialChain) -> crate::kinematics::Ik {
    crate::kinematics::Ik {
        limits: (-179.0, 179.0),
        max_iters: 120,
        joint_limits: chain.joints.iter().map(|j| j.limits).collect(),
        ..Default::default()
    }
}

fn drive_for_kind(kind: &str) -> Result<crate::kinematics::Drive, JsValue> {
    use crate::kinematics::Drive;
    Ok(match kind {
        "direct" | "dd" => Drive::direct(),
        "qdd" | "qdd-15:1" => Drive::qdd(),
        "high" | "servo" | "servo-288:1" => Drive::high_ratio(),
        "hydraulic" | "hyd" => Drive::hydraulic(),
        "tendon" | "cable" | "string" => Drive::tendon(),
        other => {
            return Err(JsValue::from_str(&format!(
                "unknown drive '{other}' (use direct|qdd|high|hydraulic|tendon)"
            )))
        }
    })
}

#[wasm_bindgen]
impl WebIkServoPlant {
    #[wasm_bindgen(constructor)]
    pub fn new(kind: &str) -> Result<WebIkServoPlant, JsValue> {
        let chain = crate::kinematics::SerialChain::planar_3r();
        let drive = drive_for_kind(kind)?;
        let label = drive.label().to_string();
        let ik = ik_for_chain(&chain);
        let mut plant = crate::kinematics::ArmPlant::from_drive(chain, drive);
        let seed = vec![-2.8, 88.9, 93.9];
        plant.seed(&seed);
        let mut world = crate::kinematics::ArmWorld::from_plant(plant);
        world.last_cmd = seed.clone();
        world.update_contacts();
        Ok(Self {
            world,
            ik,
            q_ik: seed,
            label,
        })
    }

    pub fn seed(&mut self, q_deg: &[f64]) -> Result<(), JsValue> {
        if q_deg.len() != self.world.plant.servos.len() {
            return Err(JsValue::from_str("seed length must match joint count"));
        }
        self.world.plant.seed(q_deg);
        self.q_ik = q_deg.to_vec();
        self.world.last_cmd = q_deg.to_vec();
        self.world.update_contacts();
        Ok(())
    }

    /// IK + plant step. Returns tip position error in millimetres.
    pub fn step(&mut self, tx: f64, ty: f64, tz: f64, ax: f64, ay: f64, az: f64, dt: f64) -> f64 {
        use crate::kinematics::Goal;
        let goal = Goal::PointAlong {
            at: [tx, ty, tz],
            along: [ax, ay, az],
        };
        let sol = self
            .ik
            .solve_chain(&self.q_ik, &goal, &self.world.plant.chain);
        self.q_ik = sol.joints.clone();
        self.world.last_cmd = sol.joints.clone();
        self.world.plant.step(&sol.joints, dt.max(1e-4));
        self.world.update_contacts();
        let q_act = self.world.plant.q_deg();
        let (p, _) = self.world.plant.chain.tool(&q_act);
        let dx = p[0] - tx;
        let dy = p[1] - ty;
        let dz = p[2] - tz;
        (dx * dx + dy * dy + dz * dz).sqrt()
    }

    #[wasm_bindgen(getter)]
    pub fn label(&self) -> String {
        self.label.clone()
    }

    #[wasm_bindgen(getter, js_name = jointCount)]
    pub fn joint_count(&self) -> usize {
        self.world.plant.servos.len()
    }

    #[wasm_bindgen(getter, js_name = bodyCount)]
    pub fn body_count(&self) -> usize {
        self.world.plant.chain.n()
    }

    #[wasm_bindgen(getter, js_name = contactCount)]
    pub fn contact_count(&self) -> usize {
        self.world.contacts.len()
    }

    #[wasm_bindgen(js_name = qAct)]
    pub fn q_act(&self) -> Vec<f64> {
        self.world.plant.q_deg()
    }

    #[wasm_bindgen(js_name = qCmd)]
    pub fn q_cmd(&self) -> Vec<f64> {
        self.world.last_cmd.clone()
    }

    #[wasm_bindgen(js_name = skeletonAct)]
    pub fn skeleton_act(&self) -> Vec<f64> {
        flat_skeleton(&self.world.plant.chain, &self.world.plant.q_deg())
    }

    #[wasm_bindgen(js_name = skeletonCmd)]
    pub fn skeleton_cmd(&self) -> Vec<f64> {
        flat_skeleton(&self.world.plant.chain, &self.world.last_cmd)
    }

    #[wasm_bindgen(js_name = hingesAct)]
    pub fn hinges_act(&self) -> Vec<f64> {
        flat_hinges(&self.world.plant.chain, &self.world.plant.q_deg())
    }

    #[wasm_bindgen(js_name = tipAct)]
    pub fn tip_act(&self) -> Vec<f64> {
        let (p, _) = self.world.plant.chain.tool(&self.world.plant.q_deg());
        p.to_vec()
    }

    #[wasm_bindgen(js_name = tipCmd)]
    pub fn tip_cmd(&self) -> Vec<f64> {
        let (p, _) = self.world.plant.chain.tool(&self.world.last_cmd);
        p.to_vec()
    }

    #[wasm_bindgen(js_name = meanJointErr)]
    pub fn mean_joint_err(&self) -> f64 {
        let n = self.world.plant.servos.len().max(1) as f64;
        self.world
            .plant
            .servos
            .iter()
            .map(|s| s.tracking_error_deg())
            .sum::<f64>()
            / n
    }

    #[wasm_bindgen(js_name = reflectedInertia)]
    pub fn reflected_inertia(&self) -> f64 {
        self.world.plant.servos[0].drive.reflected_inertia()
    }

    /// Gear reduction N, or `1` for hydraulic / tendon.
    pub fn ratio(&self) -> f64 {
        match &self.world.plant.servos[0].drive {
            crate::kinematics::Drive::Gear(g) => g.ratio,
            _ => 1.0,
        }
    }

    #[wasm_bindgen(js_name = driveKind)]
    pub fn drive_kind(&self) -> String {
        self.world.plant.servos[0].drive.label().to_string()
    }

    /// Working fluid / cable / grease name.
    #[wasm_bindgen(js_name = materialName)]
    pub fn material_name(&self) -> String {
        self.world.plant.servos[0].drive.material_name().to_string()
    }

    #[wasm_bindgen(js_name = tempC)]
    pub fn temp_c(&self) -> f64 {
        self.world.plant.temp_c()
    }

    /// Operating temperature in °C (oil, grease, cable).
    #[wasm_bindgen(js_name = setTemp)]
    pub fn set_temp(&mut self, temp_c: f64) {
        self.world.plant.set_temp(temp_c.clamp(-20.0, 90.0));
    }

    /// Swap hydraulic fluid: `iso32|iso46|iso68|water-glycol|silicone`.
    #[wasm_bindgen(js_name = setFluid)]
    pub fn set_fluid(&mut self, name: &str) -> Result<(), JsValue> {
        use crate::kinematics::{Drive, HydraulicFluid};
        let fluid = HydraulicFluid::from_name(name).ok_or_else(|| {
            JsValue::from_str("unknown fluid (iso32|iso46|iso68|water-glycol|silicone)")
        })?;
        let temp = self.world.plant.temp_c();
        for s in &mut self.world.plant.servos {
            if matches!(s.drive, Drive::Hydraulic(_)) {
                let mut h = crate::kinematics::HydraulicDrive::with_fluid(fluid);
                h.env.temp_c = temp;
                s.drive = Drive::Hydraulic(h);
                s.tau_max = s.drive.torque_limit();
            }
        }
        Ok(())
    }

    /// Swap tendon material: `steel|uhmwpe|nylon|aramid`.
    #[wasm_bindgen(js_name = setTendon)]
    pub fn set_tendon(&mut self, name: &str) -> Result<(), JsValue> {
        use crate::kinematics::{Drive, TendonMaterial};
        let mat = TendonMaterial::from_name(name)
            .ok_or_else(|| JsValue::from_str("unknown tendon (steel|uhmwpe|nylon|aramid)"))?;
        let temp = self.world.plant.temp_c();
        for s in &mut self.world.plant.servos {
            if matches!(s.drive, Drive::Tendon(_)) {
                let mut t = crate::kinematics::TendonDrive::with_material(mat);
                t.env.temp_c = temp;
                s.drive = Drive::Tendon(t);
                s.tau_max = s.drive.torque_limit();
            }
        }
        Ok(())
    }

    /// Live agonist/antagonist tensions for joint 0, N: `[T+, T−, pretension]`.
    #[wasm_bindgen(js_name = tensions0)]
    pub fn tensions0(&self) -> Vec<f64> {
        match &self.world.plant.servos[0].drive {
            crate::kinematics::Drive::Tendon(t) => {
                vec![t.tension_plus, t.tension_minus, t.live_pretension()]
            }
            _ => vec![],
        }
    }

    /// Fluid kinematic viscosity at current temp, cSt (hydraulic only).
    #[wasm_bindgen(js_name = fluidNuCst)]
    pub fn fluid_nu_cst(&self) -> f64 {
        match &self.world.plant.servos[0].drive {
            crate::kinematics::Drive::Hydraulic(h) => h.fluid.nu_cst(h.env.temp_c),
            _ => 0.0,
        }
    }

    /// Mechanical design label (e.g. "harmonic + planetary 288:1").
    #[wasm_bindgen(js_name = designLabel)]
    pub fn design_label(&self) -> String {
        self.world.design_label()
    }

    /// Assembled mechanism parts in world mm.
    /// Stride 16: `[joint, role, ox,oy,oz, ax,ay,az, radius, length, r,g,b, metal, rough, shape]`.
    /// `role`: motor=0 … encoder=14, housing=15.
    /// `shape`: capsule=0, segment=1, disk=2.
    #[wasm_bindgen(js_name = designPartsFlat)]
    pub fn design_parts_flat(&self) -> Vec<f64> {
        crate::kinematics::parts_flat(&self.world.design_parts())
    }

    #[wasm_bindgen(js_name = designPartCount)]
    pub fn design_part_count(&self) -> usize {
        self.world.design_parts().len()
    }

    /// Flat link solids: per body
    /// `[ox,oy,oz, dx,dy,dz, radius, mass, volume, mat_id, rgb_r,rgb_g,rgb_b, metal, rough]`.
    /// `mat_id`: 0 aluminum, 1 steel, 2 plastic, 3 rubber.
    #[wasm_bindgen(js_name = bodiesFlat)]
    pub fn bodies_flat(&self) -> Vec<f64> {
        let bodies = self.world.bodies();
        let mut out = Vec::with_capacity(bodies.len() * 15);
        for b in bodies {
            let mat_id = match b.material {
                crate::kinematics::LinkMaterial::Aluminum => 0.0,
                crate::kinematics::LinkMaterial::Steel => 1.0,
                crate::kinematics::LinkMaterial::Plastic => 2.0,
                crate::kinematics::LinkMaterial::Rubber => 3.0,
            };
            let rgb = b.material.rgb();
            out.extend_from_slice(&b.origin);
            out.extend_from_slice(&b.distal);
            out.push(b.radius);
            out.push(b.mass);
            out.push(b.volume);
            out.push(mat_id);
            out.push(rgb[0] as f64);
            out.push(rgb[1] as f64);
            out.push(rgb[2] as f64);
            out.push(b.material.metalness() as f64);
            out.push(b.material.roughness() as f64);
        }
        out
    }

    /// Body names, newline-separated.
    #[wasm_bindgen(js_name = bodyNames)]
    pub fn body_names(&self) -> String {
        self.world
            .bodies()
            .into_iter()
            .map(|b| b.name)
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Flat joints: per hinge
    /// `[ox,oy,oz, ax,ay,az, angle, cmd, omega, lo, hi, torque, engaged]`.
    #[wasm_bindgen(js_name = jointsFlat)]
    pub fn joints_flat(&self) -> Vec<f64> {
        let joints = self.world.joints();
        let mut out = Vec::with_capacity(joints.len() * 13);
        for j in joints {
            out.extend_from_slice(&j.origin);
            out.extend_from_slice(&j.axis);
            out.push(j.angle_deg);
            out.push(j.cmd_deg);
            out.push(j.omega);
            out.push(j.limits.0);
            out.push(j.limits.1);
            out.push(j.torque);
            out.push(if j.engaged { 1.0 } else { 0.0 });
        }
        out
    }

    /// Joint names, newline-separated.
    #[wasm_bindgen(js_name = jointNames)]
    pub fn joint_names(&self) -> String {
        self.world
            .joints()
            .into_iter()
            .map(|j| j.name)
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Flat contacts: `[px,py,pz, nx,ny,nz, depth, …]` plus parallel name pairs
    /// via [`Self::contact_pairs`].
    #[wasm_bindgen(js_name = contactsFlat)]
    pub fn contacts_flat(&self) -> Vec<f64> {
        let mut out = Vec::with_capacity(self.world.contacts.len() * 7);
        for c in &self.world.contacts {
            out.extend_from_slice(&c.point);
            out.extend_from_slice(&c.normal);
            out.push(c.depth);
        }
        out
    }

    /// `"a|b"` pairs, newline-separated, matching [`Self::contacts_flat`] order.
    #[wasm_bindgen(js_name = contactPairs)]
    pub fn contact_pairs(&self) -> String {
        self.world
            .contacts
            .iter()
            .map(|c| format!("{}|{}", c.a, c.b))
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Obstacle AABB `[xmin,ymin,zmin, xmax,ymax,zmax]` and floor z as 7th value.
    #[wasm_bindgen(js_name = worldBounds)]
    pub fn world_bounds(&self) -> Vec<f64> {
        let o = &self.world.obstacles;
        let (mn, mx) = match (o.box_min, o.box_max) {
            (Some(a), Some(b)) => (a, b),
            _ => ([0.0; 3], [0.0; 3]),
        };
        vec![mn[0], mn[1], mn[2], mx[0], mx[1], mx[2], o.floor_z]
    }
}

fn flat_skeleton(chain: &crate::kinematics::SerialChain, q: &[f64]) -> Vec<f64> {
    let sk = chain.skeleton(q);
    let mut out = Vec::with_capacity(sk.len() * 3);
    for p in sk {
        out.extend_from_slice(&p);
    }
    out
}

fn flat_hinges(chain: &crate::kinematics::SerialChain, q: &[f64]) -> Vec<f64> {
    let poses = chain.poses(q);
    let mut out = Vec::with_capacity(poses.len() * 6);
    for p in poses {
        out.extend_from_slice(&p.origin);
        out.extend_from_slice(&p.axis);
    }
    out
}

// ---------------------------------------------------------------------------
// QuadView — CAD-style top / front / side / perspective panes on one canvas.
// ---------------------------------------------------------------------------

fn pane_from_name(name: &str) -> Result<crate::helpers::Pane, JsValue> {
    crate::helpers::Pane::from_name(name).ok_or_else(|| {
        JsValue::from_str(&format!(
            "unknown pane '{name}' (use top|front|side|perspective)"
        ))
    })
}

/// A draw into the WebGL2 back buffer (`WebRenderer::gl_back_buffer`). With
/// MSAA on it goes through the multisampled path, as a draw to the canvas
/// would — a pane is resolved through its own pane-sized target there, so the
/// back buffer's other panes survive. `render_to` would be single-sampled.
/// Whether anything visible in `scene` blends with what is behind it: a
/// transparent material on a mesh (of any kind) or a sprite.
fn scene_blends(scene: &crate::Scene) -> bool {
    use crate::core::ObjectKind;
    let mut any = false;
    scene.arena.traverse_visible(scene.root, &mut |_, obj| {
        any = any
            || match &obj.kind {
                ObjectKind::Mesh(m) => m.draws().iter().any(|d| d.material.transparent()),
                ObjectKind::InstancedMesh(m) => m.draws().iter().any(|d| d.material.transparent()),
                ObjectKind::SkinnedMesh(m) => m.draws().iter().any(|d| d.material.transparent()),
                ObjectKind::Sprite(_) => true,
                _ => false,
            };
    });
    any
}

fn render_back(
    renderer: &mut crate::Renderer,
    scene: &mut crate::Scene,
    camera: &dyn crate::cameras::Camera,
    back: &crate::renderer::RenderTarget,
) {
    if renderer.msaa() > 1 {
        renderer.render_to_multisampled(scene, camera, back, false);
    } else {
        renderer.render_to(scene, camera, back);
    }
}

/// Where a [`WebQuadView`] draws this frame: the canvas texture, acquired
/// once for all four panes, the renderer's active render target, or the
/// WebGL2 back buffer standing in for the canvas.
enum WebPaneTarget<'a> {
    View(&'a wgpu::TextureView),
    Target(&'a crate::renderer::RenderTarget),
    Back(&'a crate::renderer::RenderTarget),
}

struct WebPaneSurface<'a> {
    renderer: &'a mut crate::Renderer,
    target: WebPaneTarget<'a>,
}

impl crate::helpers::PaneSurface for WebPaneSurface<'_> {
    fn renderer(&mut self) -> &mut dyn crate::helpers::ViewportControl {
        self.renderer
    }
    fn draw(&mut self, scene: &mut crate::Scene, camera: &dyn crate::cameras::Camera) {
        match self.target {
            WebPaneTarget::View(v) => self.renderer.render(scene, camera, v, false),
            WebPaneTarget::Target(t) => self.renderer.render_to(scene, camera, t),
            WebPaneTarget::Back(t) => render_back(self.renderer, scene, camera, t),
        }
    }
    fn clear(&mut self, color: crate::Color, alpha: f32) {
        match self.target {
            WebPaneTarget::View(v) => self.renderer.clear(v, false, color, alpha),
            WebPaneTarget::Target(t) | WebPaneTarget::Back(t) => {
                self.renderer.clear_render_target(t, color, alpha)
            }
        }
    }
}

/// [`crate::helpers::QuadView`] for the browser: three orthographic panes
/// (top, front, side — Y-up, third-angle) and the caller's perspective camera,
/// laid out on one canvas.
///
/// Rectangles are three.js's: bottom-left origin, logical (CSS) pixels — flip
/// a DOM mouse `y` (`height - y`) before `paneAt`. Pane names are
/// `"top" | "front" | "side" | "perspective"`.
#[wasm_bindgen]
pub struct WebQuadView {
    inner: crate::helpers::QuadView,
    /// Pointer handling, built from the perspective camera on first use.
    controls: Option<crate::helpers::QuadViewControls>,
}

/// The perspective camera inside a `WebCamera`, or a JS error naming `what`.
fn quad_persp<'a>(
    camera: &'a mut WebCamera,
    what: &str,
) -> Result<&'a mut crate::cameras::PerspectiveCamera, JsValue> {
    match &mut camera.inner {
        CameraInner::Perspective(c) => Ok(c),
        _ => Err(JsValue::from_str(&format!(
            "QuadView.{what}: needs the perspective camera"
        ))),
    }
}

#[wasm_bindgen]
impl WebQuadView {
    /// Third-angle layout, 2 px gap, framed on the unit cube round the origin.
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebQuadView {
        WebQuadView {
            inner: crate::helpers::QuadView::new(),
            controls: None,
        }
    }

    /// Magnification of the orthographic panes over the fitted scale (one
    /// value for all three). `frameBox`/`frameScene`/`frameAll` reset it to 1.
    #[wasm_bindgen(getter)]
    pub fn zoom(&self) -> f32 {
        self.inner.zoom
    }
    #[wasm_bindgen(setter)]
    pub fn set_zoom(&mut self, zoom: f32) {
        if zoom.is_finite() && zoom > 0.0 {
            self.inner.zoom = zoom;
        }
    }

    /// Move what the orthographic panes are centred on, world units.
    #[wasm_bindgen(js_name = panBy)]
    pub fn pan_by(&mut self, x: f32, y: f32, z: f32) {
        self.inner.pan_by(crate::Vector3::new(x, y, z));
    }

    /// Draw the shadow maps once per `render` instead of once per pane
    /// (default on; the pictures are identical).
    #[wasm_bindgen(getter, js_name = shareShadows)]
    pub fn share_shadows(&self) -> bool {
        self.inner.share_shadows
    }
    #[wasm_bindgen(setter, js_name = shareShadows)]
    pub fn set_share_shadows(&mut self, on: bool) {
        self.inner.share_shadows = on;
    }

    /// Start a pointer gesture at `(x, y)` — canvas CSS pixels, **top-left**
    /// origin (DOM `offsetX`/`offsetY`) — on a `width`×`height` canvas.
    /// `button` is DOM `PointerEvent.button`. Returns the pane, or `undefined`
    /// over a gap. Primary drag in the perspective pane orbits `camera`; any
    /// other drag pans.
    #[wasm_bindgen(js_name = pointerDown)]
    pub fn pointer_down(
        &mut self,
        camera: &mut WebCamera,
        x: f32,
        y: f32,
        button: i32,
        width: f32,
        height: f32,
    ) -> Result<Option<String>, JsValue> {
        let cam = quad_persp(camera, "pointerDown")?.clone();
        let Some(button) = crate::helpers::PointerButton::from_dom(button) else {
            return Ok(None);
        };
        let mut ctl = self.controls.take();
        let c = ctl.get_or_insert_with(|| crate::helpers::QuadViewControls::new(&cam));
        c.set_size(width, height);
        let pane = c.pointer_down(&self.inner, &cam, x, y, button);
        self.controls = ctl;
        Ok(pane.map(|p| p.name().to_string()))
    }

    /// Continue the gesture. Returns whether anything moved.
    #[wasm_bindgen(js_name = pointerMove)]
    pub fn pointer_move(
        &mut self,
        camera: &mut WebCamera,
        x: f32,
        y: f32,
    ) -> Result<bool, JsValue> {
        let cam = quad_persp(camera, "pointerMove")?;
        let Some(c) = self.controls.as_mut() else {
            return Ok(false);
        };
        Ok(c.pointer_move(&mut self.inner, cam, x, y))
    }

    #[wasm_bindgen(js_name = pointerUp)]
    pub fn pointer_up(&mut self) {
        if let Some(c) = self.controls.as_mut() {
            c.pointer_up();
        }
    }

    /// Zoom at `(x, y)` (top-left origin): `delta` is DOM `WheelEvent.deltaY`,
    /// positive zooms out. One zoom for the three orthographic panes; a dolly
    /// of `camera` in the perspective pane. Returns whether anything moved.
    pub fn wheel(
        &mut self,
        camera: &mut WebCamera,
        x: f32,
        y: f32,
        delta: f32,
        width: f32,
        height: f32,
    ) -> Result<bool, JsValue> {
        let cam = quad_persp(camera, "wheel")?;
        let snapshot = cam.clone();
        let mut ctl = self.controls.take();
        let c = ctl.get_or_insert_with(|| crate::helpers::QuadViewControls::new(&snapshot));
        c.set_size(width, height);
        let moved = c.wheel(&mut self.inner, cam, x, y, delta);
        self.controls = ctl;
        Ok(moved)
    }

    /// Maximise the pane under `(x, y)` (top-left origin), or restore the
    /// four. Returns the pane, `undefined` over a gap.
    pub fn dblclick(&mut self, x: f32, y: f32, width: f32, height: f32) -> Option<String> {
        let pane = self.inner.pane_at(x, height - y, width, height)?;
        self.inner.toggle_maximize(pane);
        if let Some(c) = self.controls.as_mut() {
            c.pointer_up();
        }
        Some(pane.name().to_string())
    }

    /// Frame every visible mesh in every pane: the orthographic panes at
    /// zoom 1, and `camera` moved along its line of sight to fit. False when
    /// there is nothing to frame.
    #[wasm_bindgen(js_name = frameAll)]
    pub fn frame_all(
        &mut self,
        scene: &mut WebScene,
        camera: &mut WebCamera,
    ) -> Result<bool, JsValue> {
        let cam = quad_persp(camera, "frameAll")?;
        let snapshot = cam.clone();
        let mut ctl = self
            .controls
            .take()
            .unwrap_or_else(|| crate::helpers::QuadViewControls::new(&snapshot));
        let framed = ctl
            .frame_all(&mut self.inner, cam, &mut scene.inner)
            .is_some();
        self.controls = Some(ctl);
        Ok(framed)
    }

    /// `frameAll` for a box: frame `bounds` in every pane.
    #[wasm_bindgen(js_name = frameBoxAll)]
    pub fn frame_box_all(
        &mut self,
        bounds: &WebBox3,
        camera: &mut WebCamera,
    ) -> Result<(), JsValue> {
        let cam = quad_persp(camera, "frameBoxAll")?;
        let snapshot = cam.clone();
        let mut ctl = self
            .controls
            .take()
            .unwrap_or_else(|| crate::helpers::QuadViewControls::new(&snapshot));
        ctl.frame_box(&mut self.inner, cam, &bounds.inner);
        self.controls = Some(ctl);
        Ok(())
    }

    /// Panes in grid order: top-left, top-right, bottom-left, bottom-right.
    pub fn layout(&self) -> Vec<String> {
        self.inner
            .layout
            .iter()
            .map(|p| p.name().to_string())
            .collect()
    }

    #[wasm_bindgen(js_name = setLayout)]
    pub fn set_layout(
        &mut self,
        top_left: &str,
        top_right: &str,
        bottom_left: &str,
        bottom_right: &str,
    ) -> Result<(), JsValue> {
        self.inner.layout = [
            pane_from_name(top_left)?,
            pane_from_name(top_right)?,
            pane_from_name(bottom_left)?,
            pane_from_name(bottom_right)?,
        ];
        Ok(())
    }

    /// Space between panes, logical pixels.
    #[wasm_bindgen(getter)]
    pub fn gap(&self) -> f32 {
        self.inner.gap
    }
    #[wasm_bindgen(setter)]
    pub fn set_gap(&mut self, gap: f32) {
        self.inner.gap = gap.max(0.0);
    }

    /// Space between the panes and the canvas edge, logical pixels.
    #[wasm_bindgen(getter)]
    pub fn border(&self) -> f32 {
        self.inner.border
    }
    #[wasm_bindgen(setter)]
    pub fn set_border(&mut self, border: f32) {
        self.inner.border = border.max(0.0);
    }

    /// Padding round the framed box in the orthographic panes, as a fraction
    /// of its extent.
    #[wasm_bindgen(getter)]
    pub fn margin(&self) -> f32 {
        self.inner.margin
    }
    #[wasm_bindgen(setter)]
    pub fn set_margin(&mut self, margin: f32) {
        self.inner.margin = margin.max(0.0);
    }

    /// What the gap and border are cleared to (linear, like every `WebColor`).
    #[wasm_bindgen(js_name = setGapColor)]
    pub fn set_gap_color(&mut self, color: &WebColor) {
        self.inner.gap_color = Some(color.inner);
    }

    /// Leave the gap and border untouched.
    #[wasm_bindgen(js_name = clearGapColor)]
    pub fn clear_gap_color(&mut self) {
        self.inner.gap_color = None;
    }

    /// Per-pane background overriding `scene.background`.
    #[wasm_bindgen(js_name = setPaneBackground)]
    pub fn set_pane_background(&mut self, pane: &str, color: &WebColor) -> Result<(), JsValue> {
        let p = pane_from_name(pane)?;
        self.inner.backgrounds[p.index()] = Some(color.inner);
        Ok(())
    }

    /// Back to the scene's background for `pane`.
    #[wasm_bindgen(js_name = clearPaneBackground)]
    pub fn clear_pane_background(&mut self, pane: &str) -> Result<(), JsValue> {
        let p = pane_from_name(pane)?;
        self.inner.backgrounds[p.index()] = None;
        Ok(())
    }

    /// The pane shown full-size, or `undefined` for all four.
    pub fn maximized(&self) -> Option<String> {
        self.inner.maximized.map(|p| p.name().to_string())
    }

    /// Show `pane` alone; `undefined`/`null` goes back to all four.
    #[wasm_bindgen(js_name = setMaximized)]
    pub fn set_maximized(&mut self, pane: Option<String>) -> Result<(), JsValue> {
        self.inner.maximized = match pane {
            Some(name) => Some(pane_from_name(&name)?),
            None => None,
        };
        Ok(())
    }

    /// Show `pane` alone, or — if it already is — go back to all four.
    #[wasm_bindgen(js_name = toggleMaximize)]
    pub fn toggle_maximize(&mut self, pane: &str) -> Result<(), JsValue> {
        self.inner.toggle_maximize(pane_from_name(pane)?);
        Ok(())
    }

    /// Aim the orthographic cameras at a box.
    #[wasm_bindgen(js_name = frameBox)]
    pub fn frame_box(&mut self, bounds: &WebBox3) {
        self.inner.frame_box(&bounds.inner);
    }

    /// Frame every visible mesh in `scene`. Returns false when there is
    /// nothing to frame (the cameras are left where they were).
    #[wasm_bindgen(js_name = frameScene)]
    pub fn frame_scene(&mut self, scene: &mut WebScene) -> bool {
        self.inner.frame_scene(&mut scene.inner).is_some()
    }

    /// The framed box's centre, `[x, y, z]` — a natural orbit target.
    pub fn target(&self) -> Vec<f32> {
        let t = self.inner.target();
        vec![t.x, t.y, t.z]
    }

    /// `[x, y, width, height]` of `pane` on a `width`×`height` canvas (logical
    /// pixels, bottom-left origin), or `undefined` when it is hidden.
    #[wasm_bindgen(js_name = paneRect)]
    pub fn pane_rect(
        &self,
        pane: &str,
        width: f32,
        height: f32,
    ) -> Result<Option<Vec<f32>>, JsValue> {
        let p = pane_from_name(pane)?;
        Ok(self
            .inner
            .pane_rect(p, width, height)
            .map(|r| vec![r.x, r.y, r.width, r.height]))
    }

    /// The pane under `(x, y)` — bottom-left origin, logical pixels — or
    /// `undefined` over a gap or border.
    #[wasm_bindgen(js_name = paneAt)]
    pub fn pane_at(&self, x: f32, y: f32, width: f32, height: f32) -> Option<String> {
        self.inner
            .pane_at(x, y, width, height)
            .map(|p| p.name().to_string())
    }

    /// Size the orthographic frusta for a `width`×`height` canvas. `render`
    /// does this itself; call it before reading the cameras out.
    pub fn fit(&mut self, width: f32, height: f32) {
        self.inner.fit(width, height);
    }

    /// A copy of the orthographic camera for `"top"`, `"front"` or `"side"`
    /// (as last fitted). Throws for `"perspective"`, which is the caller's.
    #[wasm_bindgen(js_name = orthoCamera)]
    pub fn ortho_camera(&self, pane: &str) -> Result<WebCamera, JsValue> {
        let p = pane_from_name(pane)?;
        let cam = self
            .inner
            .ortho_camera(p)
            .ok_or_else(|| JsValue::from_str("the perspective pane has no orthographic camera"))?;
        Ok(WebCamera {
            inner: CameraInner::Orthographic(cam.clone()),
        })
    }

    /// Draw every visible pane: the gap colour first, then each pane cleared
    /// to its background and drawn inside its own viewport and scissor. Goes
    /// to the canvas — acquired once for all panes, presented once — or to the
    /// renderer's active render target. `perspective` must be a perspective
    /// camera; its aspect is set per pane on a copy. The renderer's viewport,
    /// scissor and auto-clear are left as they were.
    pub fn render(
        &mut self,
        renderer: &mut WebRenderer,
        scene: &mut WebScene,
        perspective: &WebCamera,
    ) -> Result<(), JsValue> {
        let CameraInner::Perspective(persp) = &perspective.inner else {
            return Err(JsValue::from_str(
                "QuadView.render: the fourth pane needs a perspective camera",
            ));
        };
        if let Some(env_rt_id) = scene.inner.environment_cube_rt {
            if let Some(target) = ACTIVE_CUBE_TARGETS.with(|m| m.borrow().get(&env_rt_id).cloned())
            {
                renderer
                    .renderer
                    .register_cube_render_target(env_rt_id, &target);
            }
        }
        if let Some(id) = renderer.current_target_id {
            if let Some(target) = ACTIVE_TARGETS.with(|m| m.borrow().get(&id).cloned()) {
                let mut surface = WebPaneSurface {
                    renderer: &mut renderer.renderer,
                    target: WebPaneTarget::Target(&target),
                };
                self.inner.render(&mut surface, &mut scene.inner, persp);
                return Ok(());
            }
        }
        // WebGL2 page already composing by hand: keep its back buffer current.
        if let Some((id, back)) = renderer.gl_back_buffer() {
            let mut surface = WebPaneSurface {
                renderer: &mut renderer.renderer,
                target: WebPaneTarget::Back(&back),
            };
            self.inner.render(&mut surface, &mut scene.inner, persp);
            renderer.present_gl_back_buffer(id);
            return Ok(());
        }
        match renderer.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(frame)
            | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
                let view = frame
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());
                {
                    let mut surface = WebPaneSurface {
                        renderer: &mut renderer.renderer,
                        target: WebPaneTarget::View(&view),
                    };
                    self.inner.render(&mut surface, &mut scene.inner, persp);
                }
                renderer.renderer.queue_arc().present(frame);
            }
            _ => renderer
                .surface
                .configure(&renderer.device, &renderer.config),
        }
        Ok(())
    }
}

/// Shell fur's groom and look (`threers::fur::FurMaterial`), for
/// `WebScene.addFur`. Every setter returns nothing and changes this object;
/// fur already added keeps what it was built with.
#[wasm_bindgen]
pub struct WebFurMaterial {
    pub(crate) inner: crate::fur::FurMaterial,
}

#[wasm_bindgen]
impl WebFurMaterial {
    #[wasm_bindgen(constructor)]
    pub fn new() -> WebFurMaterial {
        WebFurMaterial {
            inner: crate::fur::FurMaterial::default(),
        }
    }
    /// Full strand length, world units.
    #[wasm_bindgen(js_name = setLength)]
    pub fn set_length(&mut self, v: f32) {
        self.inner.groom.length = v;
    }
    /// Strands per UV unit along each axis.
    #[wasm_bindgen(js_name = setDensity)]
    pub fn set_density(&mut self, v: f32) {
        self.inner.groom.density = v;
    }
    /// Root radius as a fraction of a strand's cell (≤ 0.5).
    #[wasm_bindgen(js_name = setThickness)]
    pub fn set_thickness(&mut self, v: f32) {
        self.inner.groom.thickness = v;
    }
    /// Tip radius as a fraction of the root's.
    #[wasm_bindgen(js_name = setTaper)]
    pub fn set_taper(&mut self, v: f32) {
        self.inner.groom.taper = v;
    }
    /// Droop at the tips, world units per unit of length.
    #[wasm_bindgen(js_name = setGravity)]
    pub fn set_gravity(&mut self, x: f32, y: f32, z: f32) {
        self.inner.groom.gravity = crate::Vector3::new(x, y, z);
    }
    /// Turns each strand makes over its length.
    #[wasm_bindgen(js_name = setCurl)]
    pub fn set_curl(&mut self, v: f32) {
        self.inner.groom.curl = v;
    }
    /// 0..1: how far tips gather into clumps; `size` in strands.
    #[wasm_bindgen(js_name = setClumping)]
    pub fn set_clumping(&mut self, amount: f32, size: f32) {
        self.inner.groom.clumping = amount;
        self.inner.groom.clump_size = size;
    }
    /// 0..1: how much shorter than the length a strand may be.
    #[wasm_bindgen(js_name = setLengthVariation)]
    pub fn set_length_variation(&mut self, v: f32) {
        self.inner.groom.length_variation = v;
    }
    #[wasm_bindgen(js_name = setSeed)]
    pub fn set_seed(&mut self, v: u32) {
        self.inner.groom.seed = v;
    }
    /// Shells above the skin (16–48 typical).
    #[wasm_bindgen(js_name = setShells)]
    pub fn set_shells(&mut self, v: u32) {
        self.inner.shells = v;
    }
    #[wasm_bindgen(js_name = setColors)]
    pub fn set_colors(&mut self, root: &WebColor, tip: &WebColor) {
        self.inner.root_color = root.inner;
        self.inner.tip_color = tip.inner;
    }
    /// 0..1: how much darker the roots are.
    #[wasm_bindgen(js_name = setOcclusion)]
    pub fn set_occlusion(&mut self, v: f32) {
        self.inner.occlusion = v;
    }
    /// The Kajiya-Kay highlight: strength, sharpness, and shift along the strand.
    #[wasm_bindgen(js_name = setSpecular)]
    pub fn set_specular(&mut self, strength: f32, exponent: f32, shift: f32) {
        self.inner.specular = strength;
        self.inner.specular_exponent = exponent;
        self.inner.specular_shift = shift;
    }
    /// The wind's velocity (m/s; it pulls by drag, as its speed squared)
    /// and gusts a second; animate with `WebScene.stepFur`.
    #[wasm_bindgen(js_name = setWind)]
    pub fn set_wind(&mut self, x: f32, y: f32, z: f32, frequency: f32) {
        self.inner.wind = crate::Vector3::new(x, y, z);
        self.inner.wind_frequency = frequency;
    }
    /// How far each strand flutters on its own, as a fraction of its cell.
    #[wasm_bindgen(js_name = setFlutter)]
    pub fn set_flutter(&mut self, v: f32) {
        self.inner.flutter = v;
    }
    /// How far up the coat shell fur's shadow reaches, as a share of its
    /// length (0.6); 0 casts none. (Hair's shadow is `shadowStrands`.)
    #[wasm_bindgen(js_name = setShadowHeight)]
    pub fn set_shadow_height(&mut self, v: f32) {
        self.inner.shadow_height = v;
    }
    /// Air drag (pull of air going by at 1 m/s; 0.15) and the gusts'
    /// strength (the turbulent share of the wind's speed; 0.35).
    #[wasm_bindgen(js_name = setAir)]
    pub fn set_air(&mut self, drag: f32, turbulence: f32) {
        self.inner.drag = drag;
        self.inner.turbulence = turbulence;
    }
    /// Draw fewer shells where the fur is small on screen (on by default).
    #[wasm_bindgen(js_name = setLod)]
    pub fn set_lod(&mut self, on: bool) {
        self.inner.lod = on;
    }
    /// Inertia: spring rate (1/s²), damping (0..1 of critical), response (1 =
    /// tips as free masses) and the largest swing (fraction of the length).
    #[wasm_bindgen(js_name = setDynamics)]
    pub fn set_dynamics(&mut self, stiffness: f32, damping: f32, response: f32, max_lag: f32) {
        self.inner.dynamics = crate::fur::FurDynamics {
            stiffness,
            damping,
            response,
            max_lag,
        };
    }
    /// Root strands over the surface in object space, one per `cell × cell`
    /// (no UVs needed); `0` puts them back on the UVs.
    #[wasm_bindgen(js_name = setSurfacePlacement)]
    pub fn set_surface_placement(&mut self, cell: f32) {
        self.inner.groom.placement = if cell > 0.0 {
            crate::fur::FurPlacement::Surface { cell }
        } else {
            crate::fur::FurPlacement::Uv
        };
    }
}

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