threers 0.1.0

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

#include <metal_stdlib>
using namespace metal;

// The functions both backends share — the tone curves and the shading
// helpers (`SHARED_FUNCTIONS` in `renderer/shader.rs`) — put in here by
// `shader_source()`.
@@SHARED_FUNCTIONS@@

// ---------------------------------------------------------------- vertex data

// 48 bytes. `packed_float3` so the layout is exactly the Rust `Vertex`.
// `alpha` is the colour attribute's fourth component (1 for a 3-component
// colour), multiplied into opacity as three.js does with `vertexAlphas`.
struct Vertex {
    packed_float3 position;
    packed_float3 normal;
    float2        uv;
    packed_float3 color;
    float         alpha;
};

/// Lines carry only what a line can use: a position and a colour, 24 bytes
/// against `Vertex`'s 48.
///
/// Lines are unlit and untextured, so the normal, the UV and the pad are dead
/// weight — and at connectome scale that is not a rounding error. A 268M-segment
/// scene stores 536M vertices, where the difference is 25.8 GB against 12.9 GB,
/// which is the difference between fitting in memory and paging.
struct LineVertex {
    packed_float3 position;
    packed_float3 color;
};

// ------------------------------------------------------------------ uniforms

struct DirLight {
    float4 direction;   // xyz = direction of travel
    float4 color;       // rgb premultiplied by intensity
};

struct PointLight {
    float4 position;
    float4 color;
    float4 params;      // x = cutoff distance (0 = none), y = decay
};

struct SpotLight {
    float4 position;
    float4 direction;
    float4 color;
    float4 params;      // x = distance, y = decay, z = cos(outer), w = cos(inner)
};

/// A `RectAreaLight`: centre, colour × intensity, half width and half
/// height as vectors (three.js's `halfWidth`, `halfHeight`).
struct RectLight {
    float4 position;
    float4 color;
    float4 right;
    float4 up;
};

/// Named as wgpu's `HemiLight`, so a translated WGSL shader reads the frame's
/// own records rather than copies.
struct HemiLight {
    float4 sky_color;
    float4 ground_color;
    float4 direction;
};

// Per-view state. One view is a plain camera; two are the eyes of a headset,
// and the vertex stage picks between them from the instance id; four are the
// panes of a quad view. Must match `MAX_VIEWS` in renderer.rs.
constant uint MAX_VIEWS = 4u;

/// A shadow-casting light's shadow — `ShadowRecord` in
/// `renderer/shader.rs`, field for field.
struct ShadowRecord {
    uint4    info;    // kind (0 directional, 1 spot, 2 point), first layer, cascades, filter
    float4   params;  // depth bias, normal bias, filter radius, one texel
    float4   extra;   // directional: cascade far edges; point: position, radius
    float4   pcss;    // search radius, spot near, spot far, penumbra scale
    float4x4 vp[4];   // world -> light clip, a cascade each
};

/// What one shadow pass draws with: its matrix, and for a point light its
/// position and radius.
struct ShadowPass {
    float4x4 shadow_vp;
    float4   point_shadow_pos;
};

struct Frame {
    float4x4   view_proj[MAX_VIEWS];
    float4x4   view[MAX_VIEWS];
    float4     camera_pos[MAX_VIEWS];
    float4     ambient;
    float4     fog_color;   // rgb, w = mode (0 off, 1 linear, 2 exp2)
    float4     fog_params;  // near, far, density
    float4     viewport;    // width, height, 1/width, 1/height
    uint4      counts;      // dir, point, spot, hemi
    uint4      view_info;   // view count; y: bit 0 the target is sRGB (encodes on write), bit 1 it stands in for a Unorm one; z, w: tone mapping
    DirLight   dir[4];
    PointLight pts[8];
    SpotLight  spots[4];
    HemiLight  hemis[2];
    uint4      rect_counts; // x: RectAreaLights; y: the transmission capture's mip count;
                            // z: 1 for reflective transparency; w: view 0's capture slice
    RectLight  rects[4];
    /// x: shadow records in use.
    uint4      shadow_info;
    /// One per shadow-casting light, which names it in its own `color.w`
    /// (record + 1).
    ShadowRecord shadows[16];
};

struct Draw {
    float4x4 model;
    float4x4 normal_mat;
    float4   base_color;   // rgb, a = opacity
    float4   emissive;     // rgb
    float4   specular;     // rgb, w = shininess
    float4   pbr;          // roughness, metalness, alpha_test, toon gradientMap bound
    float4   misc;         // wide line blends, point size, depth near, depth far
    uint4    flags;        // kind, has_map, has_vertex_color, instanced
    uint4    maps;         // emissive, normal, metallic-roughness, AO: bound?
    float4   map_params;   // normal scale, AO strength, env intensity, has env
    uint4    object;       // x: receives shadow; y: 1 for a sprite; z: 1 for ShadowMaterial; w: tone mapped
    uint4    extra;        // bound: x alpha map, y light map, z bump map, w specular map
    float4   map_scalars;  // lightMapIntensity, bumpScale, envMap bound, matcap bound
    float4   env_params;   // combine, reflectivity, refractionRatio, refraction mapping
    float4   env_dir[3];   // rows of envMapRotation · diag(flipEnvMap, 1, 1)
    // Each map's sampler, as an index into the sampler pool (`map_samps`),
    // four to a vector in `MAP_*` order — so every texture keeps its own
    // filter and wrap within Metal's sixteen sampler slots.
    uint4    map_samplers[6];
    // MeshPhysicalMaterial (zero for anything else):
    // [0] ior, specularIntensity, clearcoat, clearcoatRoughness
    // [1] specularColor, sheen
    // [2] sheenColor, sheenRoughness
    // [3] iridescence, iridescenceIOR, iridescenceThicknessRange
    // [4] anisotropy, anisotropyRotation, clearcoatNormalScale
    // [5] transmission, thickness, attenuationDistance (0 = infinite), dispersion
    // [6] attenuationColor
    float4   physical[7];
    // x: which physical maps are bound, bit `MAP_* − MAP_PHYS0`;
    // y: 1 for geometric specular antialiasing in place of three.js's
    // `geometryRoughness` (`set_specular_antialiasing`); z: what the
    // geometry's per-vertex extras (`buffer(8)`) hold — 1 uv sets, 2 tangents.
    uint4    phys_flags;
    // Each map's own uv transform, as two rows of three.js's `Texture.matrix`
    // (`setUvTransform`), in `MAP_*` order.
    float4   map_xform[44];
    // The planet terms of Standard and Physical (`DrawUniforms::planet`):
    // [0] night-side emissive, sun angular radius, twilight width, cloud
    // scatter; [1] twilight colour, scatter anisotropy; [2] cloud shell
    // height, shadow strength, longitude offset, cloud map bound; [3] the
    // eclipse occluder; [4] x: the normal map's y scale.
    float4   planet[5];
    // three.js `clippingPlanes` (one): xyz the plane's normal, w its
    // constant; what is behind it (dot(n, p) + c < 0) is cut away. A zero
    // normal: no plane.
    float4   clip;
};

/// Whether the world point `p` is cut away by the draw's clipping plane.
static inline bool clipped(constant Draw &draw, float3 p) {
    return any(draw.clip.xyz != float3(0.0)) && dot(draw.clip.xyz, p) + draw.clip.w < 0.0;
}

constant uint MAP_BASE     = 0u;
constant uint MAP_EMISSIVE = 1u;
constant uint MAP_NORMAL   = 2u;
constant uint MAP_MR       = 3u;
constant uint MAP_AO       = 4u;
constant uint MAP_ALPHA    = 5u;
constant uint MAP_LIGHT    = 6u;
constant uint MAP_BUMP     = 7u;
constant uint MAP_SPECULAR = 8u;
constant uint MAP_MATCAP   = 9u;
// MeshPhysicalMaterial's maps, at textures 16–27 in this order.
constant uint MAP_PHYS0                = 10u;
constant uint MAP_SPECULAR_INTENSITY   = 10u;
constant uint MAP_SPECULAR_COLOR       = 11u;
constant uint MAP_CLEARCOAT            = 12u;
constant uint MAP_CLEARCOAT_ROUGHNESS  = 13u;
constant uint MAP_CLEARCOAT_NORMAL     = 14u;
constant uint MAP_IRIDESCENCE          = 15u;
constant uint MAP_IRIDESCENCE_THICKNESS = 16u;
constant uint MAP_SHEEN_COLOR          = 17u;
constant uint MAP_SHEEN_ROUGHNESS      = 18u;
constant uint MAP_TRANSMISSION         = 19u;
constant uint MAP_THICKNESS            = 20u;
constant uint MAP_ANISOTROPY           = 21u;
constant uint PHYS_MAP_COUNT           = 12u;
constant uint SAMPLER_POOL             = 10u;

/// Map `i`'s sampler's place in the pool.
static inline uint map_sampler(constant Draw &draw, uint i) {
    return draw.map_samplers[i / 4u][i % 4u];
}

/// Whether physical map `i` (a `MAP_*` from `MAP_PHYS0`) is bound.
static inline bool has_phys(constant Draw &draw, uint i) {
    return (draw.phys_flags.x >> (i - MAP_PHYS0) & 1u) != 0u;
}

/// The physical maps' texels at this fragment, sampled in the entry point
/// (white where a map is absent, and a flat normal for the coat's).
struct PhysTexels {
    float4 v[12];
};

static inline float4 phys_texel(thread const PhysTexels &p, uint i) {
    return p.v[i - MAP_PHYS0];
}

/// `uv` through map `i`'s transform — three.js's `vMapUv`, `vEmissiveMapUv`
/// and the rest, one per map.
static inline float2 map_uv(constant Draw &draw, uint i, float2 uv) {
    float3 h = float3(uv, 1.0);
    return float2(dot(draw.map_xform[2u * i].xyz, h), dot(draw.map_xform[2u * i + 1u].xyz, h));
}

/// `uv` through map `i`'s transform after choosing the uv set its `channel`
/// names (row 0's w): `uv`, `uv1`, `uv2` or `uv3`.
static inline float2 map_uv_sets(constant Draw &draw, uint i, float2 uv, float4 uv12, float2 uv3) {
    float c = draw.map_xform[2u * i].w;
    float2 src = c < 0.5 ? uv : (c < 1.5 ? uv12.xy : (c < 2.5 ? uv12.zw : uv3));
    return map_uv(draw, i, src);
}

// Material kinds — `crate::materials::MaterialKind` values, not renumberable.
constant uint KIND_BASIC      = 0u;
constant uint KIND_LAMBERT    = 1u;
constant uint KIND_PHONG      = 2u;
constant uint KIND_STANDARD   = 3u;
constant uint KIND_PHYSICAL   = 4u;
constant uint KIND_NORMAL     = 5u;
constant uint KIND_DEPTH      = 6u;
constant uint KIND_TOON       = 7u;
constant uint KIND_MATCAP     = 8u;
constant uint KIND_DISTANCE   = 12u;
constant uint KIND_ATMOSPHERE = 16u;

// The interpolants, shared by the single-view and layered outputs. A macro
// because Metal has no struct inheritance and the fragment stage matches its
// inputs to the vertex outputs by declaration order — the two lists have to
// stay identical, and this is the only way to make that structural rather than
// a comment asking future edits to remember.
#define VOUT_INTERPOLANTS                                                      \
    float4 position [[position]];                                              \
    float3 world_pos;                                                          \
    float3 normal;                                                             \
    float2 uv;                                                                 \
    /* three.js `uv1` (xy) and `uv2` (zw), and `uv3`.                       */ \
    float4 uv12;                                                               \
    float2 uv3;                                                                \
    /* The `tangent` attribute in world space, w its handedness; zero when  */ \
    /* the geometry has none.                                               */ \
    float4 tangent;                                                            \
    float4 color;                                                              \
    float  view_dist;                                                          \
    /* Which eye this vertex belongs to; the fragment stage needs it for the */ \
    /* view vector. Flat because it is an index, not a quantity.             */ \
    uint   view_index [[flat]];

/// What the fragment stage receives — the interpolants and nothing else. The
/// builtins below are vertex outputs only.
struct FIn {
    VOUT_INTERPOLANTS
};

/// Per-vertex skinning influences. Joint indices arrive as floats because that
/// is how `BufferGeometry` stores them, three.js doing the same.
struct SkinVertex {
    float4 joints;
    float4 weights;
};

/// Highest bone index the skinning reads. The renderer pads the bone buffer
/// with identities to 128 matrices — the wgpu backend's fixed uniform array —
/// and joints clamp here, so both backends (and the CPU raycaster) read the
/// same matrix for every joint index.
constant uint MAX_BONE = 127u;

/// The weighted blend of a vertex's four bones: three.js's `Σ wᵢ · boneMatᵢ`.
///
/// Not renormalised: three.js normalises weights on load
/// (`normalizeSkinWeights`), not in the shader, and draws whatever an
/// un-normalised set gives. Normalising here would draw a mesh the other
/// backend, the raycaster and three.js all put somewhere else.
static inline float4x4 skin_matrix(SkinVertex sv, device const float4x4 *bones) {
    float4x4 m = float4x4(0.0);
    for (uint k = 0u; k < 4u; ++k) {
        if (sv.weights[k] != 0.0) {
            m += bones[min(uint(max(sv.joints[k], 0.0)), MAX_BONE)] * sv.weights[k];
        }
    }
    return m;
}

/// The one matrix that takes a rest position to world space the way
/// three.js's `skinning_vertex.glsl` does with an identity `bindMatrix` and
/// `bindMatrixInverse = inverse(model)` (attached bind mode):
///
///     skinned = skin * (p, 1)                  // w = the weight sum
///     world   = model * ((inverse(model) * skinned).xyz, 1)
///             = skinned.xyz + (1 - skinned.w) * translation(model)
///
/// The model cancels when the weights sum to one. Bone matrices are affine, so
/// `skinned.w` is `skin[3].w`. See `SkinnedMesh` on the Rust side.
static inline float4x4 skinned_model(float4x4 model, float4x4 skin) {
    float4x4 m = skin;
    m[3].xyz += (1.0 - skin[3].w) * model[3].xyz;
    m[0].w = 0.0;
    m[1].w = 0.0;
    m[2].w = 0.0;
    m[3].w = 1.0;
    return m;
}

/// `skinnormal_vertex.glsl` then the normal matrix: `N · inverse(model) ·
/// skin`, where `inverse(model)`'s linear part is `transpose(N)` — so for a
/// rigid model it is just the skin's linear part.
static inline float3x3 skinned_normal_basis(constant Draw &draw, float4x4 skin) {
    float3x3 n = float3x3(draw.normal_mat[0].xyz, draw.normal_mat[1].xyz, draw.normal_mat[2].xyz);
    return n * transpose(n) * float3x3(skin[0].xyz, skin[1].xyz, skin[2].xyz);
}

/// Single-view output. `point_size` is harmless for triangles here because a
/// pipeline that names no topology class may write it.
struct VOut {
    VOUT_INTERPOLANTS
    float point_size [[point_size]];
};

// Layered outputs carry the array slice to render into. They are separate
// structs for two reasons Metal enforces: a pipeline whose vertex function
// writes `render_target_array_index` must declare its topology class, and a
// pipeline that declares `triangle` must then *not* write `point_size`.
struct VOutLayered {
    VOUT_INTERPOLANTS
    uint layer [[render_target_array_index]];
};

struct VOutLayeredPoint {
    VOUT_INTERPOLANTS
    float point_size [[point_size]];
    uint  layer [[render_target_array_index]];
};

#define COPY_INTERPOLANTS(out, v)                                              \
    out.position = v.position;                                                 \
    out.world_pos = v.world_pos;                                               \
    out.normal = v.normal;                                                     \
    out.uv = v.uv;                                                             \
    out.uv12 = v.uv12;                                                         \
    out.uv3 = v.uv3;                                                           \
    out.tangent = v.tangent;                                                   \
    out.color = v.color;                                                       \
    out.view_dist = v.view_dist;                                               \
    out.view_index = v.view_index;                                             \
    out.layer = v.view_index; /* one eye per slice */

static inline VOutLayered to_layered(VOut v) {
    VOutLayered out;
    COPY_INTERPOLANTS(out, v)
    return out;
}

static inline VOutLayeredPoint to_layered_point(VOut v) {
    VOutLayeredPoint out;
    COPY_INTERPOLANTS(out, v)
    out.point_size = v.point_size;
    return out;
}

// ---------------------------------------------------------------- morph targets

/// three.js's morph-target blend (`morphtarget_vertex`, `morphnormal_vertex`,
/// `morphcolor_vertex`): `base · attribute + Σ wᵢ · targetᵢ`, where `base` is
/// 1 for relative targets and `1 − Σ influences` for absolute ones (computed
/// on the CPU, as `WebGLMorphtargets` does). The targets live in one float4
/// buffer laid out like three.js's morph texture: target `t`, vertex `v`,
/// slot `k` (0 position, 1 normal, 2 colour) at `(t · vertex_count + v) ·
/// stride + k`. `MorphInfo` twins `MorphUniforms` in renderer.rs.
struct MorphInfo {
    uint4  info;        // x: target count (0 = off), y: stride, z: flags (1 normal, 2 colour, 4 position, 8 colour alpha, 16 per instance), w: vertex count
    float4 base;        // x: morphTargetBaseInfluence
    float4 weights[16]; // 64 influences
};

/// `iid` is the instance drawn and `instances` the instance buffer: for an
/// `InstancedMesh` with a morph texture (`info.z & 16`) the per-instance rows
/// — three.js's `morphTexture`, `morphTargetBaseInfluence` then the
/// influences, `base.y` floats each — follow the matrices, `base.z` floats in.
static inline Vertex apply_morph(Vertex v,
                                 uint vid,
                                 uint iid,
                                 constant MorphInfo &m,
                                 device const float4 *data,
                                 device const float4x4 *instances) {
    uint count = m.info.x;
    if (count == 0u) {
        return v;
    }
    uint stride = m.info.y;
    uint vc = m.info.w;
    bool per_instance = (m.info.z & 16u) != 0u;
    device const float *row = (device const float *)instances
        + uint(m.base.z) + iid * uint(m.base.y);
    float b = per_instance ? row[0] : m.base.x;
    bool has_p = (m.info.z & 4u) != 0u;
    float3 p = has_p ? float3(v.position) * b : float3(v.position);
    bool has_n = (m.info.z & 1u) != 0u;
    bool has_c = (m.info.z & 2u) != 0u;
    float3 n = has_n ? float3(v.normal) * b : float3(v.normal);
    // `morphcolor_vertex.glsl`: all four channels for a 4-component colour
    // (USE_COLOR_ALPHA), rgb otherwise.
    bool has_ca = (m.info.z & 8u) != 0u;
    float4 c0 = float4(float3(v.color), v.alpha);
    float4 c = has_c ? c0 * b : c0;
    for (uint i = 0u; i < count; ++i) {
        float w = per_instance ? row[i + 1u] : m.weights[i / 4u][i % 4u];
        if (w == 0.0) {
            continue;
        }
        uint at = (i * vc + vid) * stride;
        if (has_p) {
            p += data[at].xyz * w;
        }
        if (has_n) {
            n += data[at + 1u].xyz * w;
        }
        if (has_c) {
            c += data[at + 2u] * w;
        }
    }
    v.position = packed_float3(p);
    v.normal = packed_float3(n);
    v.color = packed_float3(c.rgb);
    v.alpha = has_ca ? c.a : c0.a;
    return v;
}

// --------------------------------------------------------------------- vertex

static inline float4x4 model_matrix(constant Draw &draw,
                                    device const float4x4 *instances,
                                    uint iid) {
    // Only pay for the instance multiply when there is an instance to apply;
    // a 4x4 product per vertex is not free at scene scale.
    return (draw.flags.w & 1u) == 1u ? draw.model * instances[iid] : draw.model;
}

/// three.js `instanceColor` (`InstancedMesh.setColorAt`): `color_vertex`
/// multiplies it into `vColor`, after any colour attribute. The colours are
/// float4s in the instance buffer, after the matrices (and the morph rows),
/// starting `draw.flags.w >> 1` float4s in; 0 there means the mesh has none.
static inline float4 instance_color(constant Draw &draw,
                                    device const float4x4 *instances,
                                    uint iid) {
    uint at = draw.flags.w >> 1;
    if ((draw.flags.w & 1u) == 0u || at == 0u) {
        return float4(1.0);
    }
    return float4(((device const float4 *)instances)[at + iid].rgb, 1.0);
}

static inline VOut transform(Vertex v,
                             float4x4 model,
                             float3x3 nrm,
                             constant Frame &frame,
                             constant Draw &draw,
                             uint view_index) {
    VOut out;
    float4 world = model * float4(float3(v.position), 1.0);
    out.position = frame.view_proj[view_index] * world;
    out.world_pos = world.xyz;
    out.normal = nrm * float3(v.normal);
    out.uv = v.uv;
    out.uv12 = float4(0.0);
    out.uv3 = float2(0.0);
    out.tangent = float4(0.0);
    out.color = draw.flags.z == 1u ? float4(float3(v.color), v.alpha) : float4(1.0);
    out.view_dist = length(frame.camera_pos[view_index].xyz - world.xyz);
    out.point_size = 1.0;
    out.view_index = view_index;
    return out;
}

static inline float3x3 normal_basis(constant Draw &draw,
                                    device const float4x4 *instances,
                                    uint iid) {
    float3x3 nm = float3x3(draw.normal_mat[0].xyz,
                           draw.normal_mat[1].xyz,
                           draw.normal_mat[2].xyz);
    if ((draw.flags.w & 1u) == 1u) {
        // `defaultnormal_vertex.glsl` under USE_INSTANCING: the instance's
        // linear part with each column divided by its squared length — so an
        // axis-scaled instance keeps its normals perpendicular — then the
        // mesh's normal matrix.
        float4x4 i4 = instances[iid];
        float3x3 im = float3x3(i4[0].xyz, i4[1].xyz, i4[2].xyz);
        float3x3 inv_s = float3x3(float3(1.0 / dot(im[0], im[0]), 0.0, 0.0),
                                  float3(0.0, 1.0 / dot(im[1], im[1]), 0.0),
                                  float3(0.0, 0.0, 1.0 / dot(im[2], im[2])));
        return nm * im * inv_s;
    }
    return nm;
}

static inline VOut point_size_for(VOut out, constant Frame &frame, constant Draw &draw) {
    float size = draw.misc.y;
    if (draw.misc.z > 0.5) {
        // three.js size attenuation: gl_PointSize = size * (h/2) / -mvPosition.z
        float view_z =
            max(-(frame.view[out.view_index] * float4(out.world_pos, 1.0)).z, 1e-4);
        size *= (frame.viewport.y * 0.5) / view_z;
    }
    out.point_size = clamp(size, 1.0, 255.0);
    return out;
}

/// A `Sprite` draw (`draw.object.y == 1`): three.js's `sprite_vert`, the unit
/// quad turned to face view `view_index`. `draw.normal_mat[0]` carries
/// (centre − 0.5, rotation, scale-by-depth) — the normal matrix means nothing
/// to an unlit, camera-facing quad. The wgpu backend's `vs_sprite` and the
/// raycaster build the same quad.
static inline VOut sprite_vertex(Vertex v,
                                 constant Frame &frame,
                                 constant Draw &draw,
                                 uint view_index) {
    float4 params = draw.normal_mat[0];
    float4x4 view = frame.view[view_index];
    float4 center_view = view * float4(draw.model[3].xyz, 1.0);
    float2 scale = float2(length(draw.model[0].xyz), length(draw.model[1].xyz));
    if (params.w > 0.5) {
        scale *= -center_view.z;
    }
    float2 aligned = (float3(v.position).xy - params.xy) * scale;
    float c = cos(params.z);
    float s = sin(params.z);
    float2 rotated = float2(c * aligned.x - s * aligned.y, s * aligned.x + c * aligned.y);
    float3 view_pos = float3(center_view.xy + rotated, center_view.z);
    // Back to world space: a view matrix is rigid, so its inverse rotation is
    // the transpose.
    float3x3 r = float3x3(view[0].xyz, view[1].xyz, view[2].xyz);
    float3 world = transpose(r) * (view_pos - view[3].xyz);
    // `transform` does the rest (uv, colour, distances), handed a translation
    // that takes this vertex to its billboarded place.
    float4x4 model = float4x4(1.0);
    model[3] = float4(world - float3(v.position), 1.0);
    float3x3 facing = transpose(r);
    return transform(v, model, facing, frame, draw, view_index);
}

struct TangentPair {
    float3 t;
    float3 b;
};

/// three.js's `tbn` from the `tangent` attribute (`normal_fragment_begin`):
/// the tangent normalised, the bitangent `cross(normal, tangent) · w` — the
/// frame the anisotropy and the coat's normal map read — or `fallback`
/// (`getTangentFrame`) without one.
static inline TangentPair tbn_frame(float4 vt, float3 vertex_normal, TangentPair fallback) {
    if (dot(vt.xyz, vt.xyz) < 1e-12) {
        return fallback;
    }
    TangentPair f;
    f.t = normalize(vt.xyz);
    f.b = normalize(cross(normalize(vertex_normal), f.t) * (vt.w >= 0.0 ? 1.0 : -1.0));
    return f;
}

/// Vertex `vid`'s extra uv sets and tangent into `out` (zero without
/// them); the tangent through `model`, a direction along the surface.
static inline void read_uv_sets(thread VOut &out, uint vid, constant Draw &draw,
                                device const float4 *uv_sets, float4x4 model) {
    if ((draw.phys_flags.z & 1u) != 0u) {
        out.uv12 = uv_sets[3u * vid];
        out.uv3 = uv_sets[3u * vid + 1u].xy;
    }
    if ((draw.phys_flags.z & 2u) != 0u) {
        float4 t = uv_sets[3u * vid + 2u];
        out.tangent = float4((model * float4(t.xyz, 0.0)).xyz, t.w);
    }
}

/// The tangent frame for a normal map or anisotropy: the `tangent`
/// attribute's, orthogonalised against `n`, with the bitangent from its
/// handedness — as `surface_frame` in `renderer/shader.rs` — when the geometry
/// has one; else `fallback`, from screen-space derivatives. Flipped with a
/// back face (`face` −1), as three.js's `faceDirection` flips `tbn`.
static inline TangentPair attribute_frame(float4 vt, float3 n, TangentPair fallback) {
    float3 t = vt.xyz - n * dot(n, vt.xyz);
    if (dot(vt.xyz, vt.xyz) < 1e-12 || dot(t, t) < 1e-12) {
        return fallback;
    }
    TangentPair f;
    f.t = normalize(t);
    f.b = normalize(cross(n, f.t)) * (vt.w >= 0.0 ? 1.0 : -1.0);
    return f;
}

/// three.js `displacementMap`: the height map's red channel moves the vertex
/// along its (morphed) normal, scaled and offset — `planet[4]`: y scale, z
/// bias, w bound — as the wgpu backend's `apply_displacement`, in every pass
/// a mesh is drawn in, its shadows' included.
static inline Vertex displace(Vertex v, constant Draw &draw, texture2d<float> disp, sampler samp) {
    if (draw.planet[4].w > 0.5) {
        float h = disp.sample(samp, v.uv, level(0.0)).r;
        float3 n = float3(v.normal);
        v.position = packed_float3(float3(v.position) + normalize(n) * (h * draw.planet[4].y + draw.planet[4].z));
    }
    return v;
}

vertex VOut vs_mesh(uint vid [[vertex_id]],
                    uint iid [[instance_id]],
                    device const Vertex   *verts     [[buffer(0)]],
                    constant Frame        &frame     [[buffer(1)]],
                    constant Draw         &draw      [[buffer(2)]],
                    device const float4x4 *instances [[buffer(3)]],
                    device const float4   *morph_data [[buffer(6)]],
                    constant MorphInfo    &morph      [[buffer(7)]],
                    device const float4   *uv_sets    [[buffer(8)]],
                    texture2d<float>      disp_map   [[texture(0)]],
                    sampler               disp_samp  [[sampler(0)]]) {
    if (draw.object.y == 1u) {
        return sprite_vertex(verts[vid], frame, draw, 0u);
    }
    float4x4 model = model_matrix(draw, instances, iid);
    Vertex v = apply_morph(verts[vid], vid, iid, morph, morph_data, instances);
    v = displace(v, draw, disp_map, disp_samp);
    VOut out = transform(v, model, normal_basis(draw, instances, iid), frame, draw, 0u);
    out.color *= instance_color(draw, instances, iid);
    read_uv_sets(out, vid, draw, uv_sets, model);
    return out;
}

/// Skinned transform: three.js's skinning, see `skinned_model`.
///
/// `bones[i]` is already world × inverse-bind for bone `i` — `Skeleton::update`
/// composes that on the CPU — so the work here is the weighted sum. Four
/// influences, which is what glTF stores and what three.js reads.
///
/// The normal is transformed by the same blend rather than by its own inverse
/// transpose, as three.js's `skinnormal_vertex.glsl` does. That is exact for
/// rigid bones and wrong only under non-uniform bone scale.
vertex VOut vs_skinned(uint vid [[vertex_id]],
                       uint iid [[instance_id]],
                       device const Vertex     *verts     [[buffer(0)]],
                       constant Frame          &frame     [[buffer(1)]],
                       constant Draw           &draw      [[buffer(2)]],
                       device const float4x4   *instances [[buffer(3)]],
                       device const SkinVertex *skin      [[buffer(4)]],
                       device const float4x4   *bones     [[buffer(5)]],
                       device const float4     *morph_data [[buffer(6)]],
                       constant MorphInfo      &morph      [[buffer(7)]],
                       device const float4     *uv_sets    [[buffer(8)]],
                       texture2d<float>        disp_map    [[texture(0)]],
                       sampler                 disp_samp   [[sampler(0)]]) {
    float4x4 sk = skin_matrix(skin[vid], bones);
    float4x4 model = skinned_model(model_matrix(draw, instances, iid), sk);
    // Morph first, then skin — three.js's chunk order.
    Vertex v = displace(apply_morph(verts[vid], vid, iid, morph, morph_data, instances), draw, disp_map, disp_samp);
    VOut out = transform(v, model, skinned_normal_basis(draw, sk), frame, draw, 0u);
    read_uv_sets(out, vid, draw, uv_sets, model);
    return out;
}

/// Depth-only pass from the light's point of view.
///
/// Writes position and nothing else: the shadow map is a depth buffer, and a
/// fragment function that returns a colour nobody reads would cost a whole
/// attachment. Instancing and skinning both apply — a shadow cast by the bind
/// pose of an animated mesh is worse than no shadow, because it is wrong in a
/// way that looks deliberate.
vertex float4 vs_shadow(uint vid [[vertex_id]],
                        uint iid [[instance_id]],
                        device const Vertex     *verts     [[buffer(0)]],
                        constant ShadowPass     &frame     [[buffer(1)]],
                        constant Draw           &draw      [[buffer(2)]],
                        device const float4x4   *instances [[buffer(3)]],
                        device const SkinVertex *skin      [[buffer(4)]],
                        device const float4x4   *bones     [[buffer(5)]],
                        device const float4     *morph_data [[buffer(6)]],
                        constant MorphInfo      &morph      [[buffer(7)]],
                        texture2d<float>        disp_map    [[texture(0)]],
                        sampler                 disp_samp   [[sampler(0)]]) {
    float4x4 model = model_matrix(draw, instances, iid);
    if (draw.maps.w == 2u) {   // 2 marks a skinned draw; see `DrawUniforms`
        model = skinned_model(model, skin_matrix(skin[vid], bones));
    }
    Vertex v = displace(apply_morph(verts[vid], vid, iid, morph, morph_data, instances), draw, disp_map, disp_samp);
    return frame.shadow_vp * model * float4(float3(v.position), 1.0);
}

/// Point-light shadow pass: writes *radial* distance, not projected depth.
///
/// This is the one place a shadow pass needs a fragment stage. A cube's six
/// faces each have their own frustum, so projected depth is per-face and
/// discontinuous across the seams — but the lookup is by direction and has only
/// one number to compare, the distance from the light. Storing that directly is
/// what makes one cube serve all six directions.
///
/// Worth noting because it is a trap the wgpu path is still in: it renders its
/// cube with `fragment: None`, so the stored value is projected depth while the
/// comparison is `dist / radius`. Those are different quantities and the test
/// never passes — its point shadows silently never trigger.
struct ShadowPointOut {
    float4 position [[position]];
    float3 world;
    float2 uv;
};

/// A cut-out caster's clip position and map uv (directional and spot): three.js's
/// shadow depth material takes the caster's `map` and `alphaTest`
/// (`WebGLShadowMap.getDepthMaterial`), not its opacity.
struct ShadowCutOut {
    float4 position [[position]];
    float2 uv;
};

vertex ShadowCutOut vs_shadow_cut(uint vid [[vertex_id]],
                                  uint iid [[instance_id]],
                                  device const Vertex     *verts     [[buffer(0)]],
                                  constant ShadowPass     &frame     [[buffer(1)]],
                                  constant Draw           &draw      [[buffer(2)]],
                                  device const float4x4   *instances [[buffer(3)]],
                                  device const SkinVertex *skin      [[buffer(4)]],
                                  device const float4x4   *bones     [[buffer(5)]],
                                  device const float4     *morph_data [[buffer(6)]],
                                  constant MorphInfo      &morph      [[buffer(7)]],
                                  texture2d<float>        disp_map    [[texture(0)]],
                                  sampler                 disp_samp   [[sampler(0)]]) {
    float4x4 model = model_matrix(draw, instances, iid);
    if (draw.maps.w == 2u) {
        model = skinned_model(model, skin_matrix(skin[vid], bones));
    }
    Vertex v = displace(apply_morph(verts[vid], vid, iid, morph, morph_data, instances), draw, disp_map, disp_samp);
    ShadowCutOut o;
    o.position = frame.shadow_vp * model * float4(float3(v.position), 1.0);
    o.uv = v.uv;
    return o;
}

/// Whether a shadow caster's fragment is cut away: below `alphaTest` in its
/// map's alpha. A caster with no map, or no test, is never cut.
/// Its `alphaMap`'s green channel too, as three.js's depth material takes it.
static inline bool shadow_cut(constant Draw &draw, texture2d<float> base_map,
                              sampler samp, texture2d<float> alpha_map,
                              sampler alpha_samp, float2 uv) {
    bool has_map = draw.flags.y == 1u;
    bool has_alpha = draw.extra.x == 1u;
    if (draw.pbr.z <= 0.0 || !(has_map || has_alpha)) {
        return false;
    }
    float a = 1.0;
    if (has_map) {
        a = base_map.sample(samp, map_uv(draw, MAP_BASE, uv), level(0.0)).a;
    }
    if (has_alpha) {
        a *= alpha_map.sample(alpha_samp, map_uv(draw, MAP_ALPHA, uv), level(0.0)).g;
    }
    return a < draw.pbr.z;
}

fragment void fs_shadow_cut(ShadowCutOut in [[stage_in]],
                            constant Draw &draw [[buffer(2)]],
                            texture2d<float> base_map [[texture(0)]],
                            texture2d<float> alpha_map [[texture(1)]],
                            sampler samp [[sampler(0)]],
                            sampler alpha_samp [[sampler(1)]]) {
    if (shadow_cut(draw, base_map, samp, alpha_map, alpha_samp, in.uv)) {
        discard_fragment();
    }
}

vertex ShadowPointOut vs_shadow_point(uint vid [[vertex_id]],
                                      uint iid [[instance_id]],
                                      device const Vertex     *verts     [[buffer(0)]],
                                      constant ShadowPass     &frame     [[buffer(1)]],
                                      constant Draw           &draw      [[buffer(2)]],
                                      device const float4x4   *instances [[buffer(3)]],
                                      device const SkinVertex *skin      [[buffer(4)]],
                                      device const float4x4   *bones     [[buffer(5)]],
                                      device const float4     *morph_data [[buffer(6)]],
                                      constant MorphInfo      &morph      [[buffer(7)]],
                                      texture2d<float>        disp_map    [[texture(0)]],
                                      sampler                 disp_samp   [[sampler(0)]]) {
    float4x4 model = model_matrix(draw, instances, iid);
    if (draw.maps.w == 2u) {
        model = skinned_model(model, skin_matrix(skin[vid], bones));
    }
    Vertex v = displace(apply_morph(verts[vid], vid, iid, morph, morph_data, instances), draw, disp_map, disp_samp);
    float4 world = model * float4(float3(v.position), 1.0);
    ShadowPointOut o;
    o.position = frame.shadow_vp * world;
    o.world = world.xyz;
    o.uv = v.uv;
    return o;
}

struct ShadowDepth {
    float depth [[depth(any)]];
};

fragment ShadowDepth fs_shadow_point(ShadowPointOut in [[stage_in]],
                                     constant ShadowPass &frame [[buffer(1)]],
                                     constant Draw &draw [[buffer(2)]],
                                     texture2d<float> base_map [[texture(0)]],
                                     texture2d<float> alpha_map [[texture(1)]],
                                     sampler samp [[sampler(0)]],
                                     sampler alpha_samp [[sampler(1)]]) {
    if (shadow_cut(draw, base_map, samp, alpha_map, alpha_samp, in.uv)) {
        discard_fragment();
    }
    float radius = max(frame.point_shadow_pos.w, 1e-4);
    ShadowDepth o;
    o.depth = saturate(length(in.world - frame.point_shadow_pos.xyz) / radius);
    return o;
}

vertex VOut vs_line(uint vid [[vertex_id]],
                    uint iid [[instance_id]],
                    device const LineVertex *verts     [[buffer(0)]],
                    constant Frame          &frame     [[buffer(1)]],
                    constant Draw           &draw      [[buffer(2)]],
                    device const float4x4   *instances [[buffer(3)]]) {
    // Widened into a full Vertex and handed to the same transform, so the line
    // path cannot drift from the mesh path as that code changes.
    Vertex v;
    v.position = verts[vid].position;
    v.normal   = packed_float3(0.0, 0.0, 1.0);  // never read; unlit
    v.uv       = float2(0.0);
    v.color    = verts[vid].color;
    v.alpha    = 1.0;
    float4x4 model = model_matrix(draw, instances, iid);
    return transform(v, model, normal_basis(draw, instances, iid), frame, draw, 0u);
}

// Expand each segment into a screen-space quad, so a line thinner than a pixel
// contributes in proportion to the area it covers.
//
// Hardware lines are all-or-nothing at one pixel wide. For filaments that sit
// below a pixel — most of a connectome at any sane resolution — that means a
// neurite either lights a whole pixel or vanishes, and which one it does
// changes frame to frame as the camera turns. That is the flicker supersampling
// only partly hides, and coverage fixes at the source.
//
// Reads the same `LineVertex` buffer, six vertices per segment instead of two,
// so nothing extra is stored.
vertex VOut vs_line_quad(uint vid [[vertex_id]],
                         uint iid [[instance_id]],
                         device const LineVertex *verts     [[buffer(0)]],
                         constant Frame          &frame     [[buffer(1)]],
                         constant Draw           &draw      [[buffer(2)]],
                         device const float4x4   *instances [[buffer(3)]]) {
    const uint seg    = vid / 6u;
    const uint corner = vid % 6u;
    // Two triangles: (near,-) (far,-) (near,+) / (near,+) (far,-) (far,+)
    const uint  ends[6]  = {0u, 1u, 0u, 0u, 1u, 1u};
    const float sides[6] = {-1.0, -1.0, 1.0, 1.0, -1.0, 1.0};
    const uint  end  = ends[corner];
    const float side = sides[corner];

    const float4x4 model = model_matrix(draw, instances, iid);
    const LineVertex me = verts[seg * 2u + end];
    const LineVertex ot = verts[seg * 2u + (1u - end)];

    float4 pm = frame.view_proj[0] * (model * float4(float3(me.position), 1.0));
    float4 po = frame.view_proj[0] * (model * float4(float3(ot.position), 1.0));

    // Perpendicular in pixels, then back to clip. Guarded because a segment can
    // project to a point, and normalize(0) is a NaN that takes the quad with it.
    const float2 sm = pm.xy / max(abs(pm.w), 1e-6);
    const float2 so = po.xy / max(abs(po.w), 1e-6);
    // From the segment's start to its end whichever end this is, so both
    // ends agree on which side is +: measured from `me`, the far end's
    // normal flips and the quad twists into a bowtie.
    float2 d = (end == 0u ? so - sm : sm - so) * frame.viewport.xy;
    const float len = length(d);
    d = len > 1e-6 ? d / len : float2(1.0, 0.0);
    // NDC spans 2 across the viewport: a pixel is 2/width of it.
    const float2 nrm = float2(-d.y, d.x) * 2.0 * frame.viewport.zw;

    // draw.misc.y carries the width in pixels, shared with point size. The
    // quad reaches as far again as a pixel's footprint does — half its
    // diagonal — so the pixels a thin line only grazes get their share too.
    const float half_px = max(draw.misc.y, 0.0) * 0.5;
    const float reach = half_px + 0.75;
    pm.xy += nrm * side * reach * abs(pm.w);

    VOut out;
    out.position = pm;
    out.world_pos = (model * float4(float3(me.position), 1.0)).xyz;
    out.normal = float3(0.0, 0.0, 1.0);
    // uv.x carries the signed distance across the ribbon in pixels, uv.y the
    // half width, for the coverage.
    out.uv12 = float4(0.0);
    out.uv3 = float2(0.0);
    out.tangent = float4(0.0);
    out.uv = float2(side * reach, half_px);
    out.color = draw.flags.z == 1u ? float4(float3(me.color), 1.0) : float4(1.0);
    out.view_dist = length(frame.camera_pos[0].xyz - out.world_pos);
    out.point_size = 1.0;
    out.view_index = 0u;
    return out;
}

fragment float4 fs_line_quad(VOut in [[stage_in]],
                             constant Frame &frame [[buffer(0)]],
                             constant Draw  &draw  [[buffer(1)]]) {
    if (clipped(draw, in.world_pos)) {
        discard_fragment();
    }
    // The share of the pixel the ribbon covers, a box filter over the pixel's
    // width across it (1 square to a row or column, √2 on the diagonal; uv.x
    // is affine on screen, so its derivatives are exact). A sub-pixel
    // filament contributes its width rather than a whole pixel, and the
    // coverages across it sum to that width wherever it falls, so it keeps
    // one weight as the camera turns instead of shimmering.
    const float half_px = in.uv.y;
    const float dist = abs(in.uv.x);
    const float w = max(fwidth(in.uv.x), 1e-6);
    const float lo = max(dist - 0.5 * w, -half_px);
    const float hi = min(dist + 0.5 * w, half_px);
    // Opaque (misc.x 0), coverage would be ignored, so cut at half a width
    // and never under a pixel, as a hardware line keeps it visible.
    const float cov = draw.misc.x > 0.5 ? clamp((hi - lo) / w, 0.0, 1.0)
                                        : (dist <= max(half_px, 0.5) ? 1.0 : 0.0);
    // three.js `alphaTest` applies to the material alpha, before coverage.
    if (draw.base_color.a * in.color.a < draw.pbr.z) {
        discard_fragment();
    }
    float4 c = float4(draw.base_color.rgb * in.color.rgb, draw.base_color.a * cov);
    if (c.a <= 0.0) {
        discard_fragment();
    }
    return c;
}

vertex VOut vs_point(uint vid [[vertex_id]],
                     uint iid [[instance_id]],
                     device const Vertex   *verts     [[buffer(0)]],
                     constant Frame        &frame     [[buffer(1)]],
                     constant Draw         &draw      [[buffer(2)]],
                     device const float4x4 *instances [[buffer(3)]],
                     device const float4   *morph_data [[buffer(6)]],
                     constant MorphInfo    &morph      [[buffer(7)]],
                     texture2d<float>        disp_map    [[texture(0)]],
                     sampler                 disp_samp   [[sampler(0)]]) {
    float4x4 model = model_matrix(draw, instances, iid);
    Vertex v = displace(apply_morph(verts[vid], vid, iid, morph, morph_data, instances), draw, disp_map, disp_samp);
    VOut out = transform(v, model, normal_basis(draw, instances, iid), frame, draw, 0u);
    return point_size_for(out, frame, draw);
}

// ------------------------------------------------------------ layered stereo
//
// Both eyes in one pass, into one texture array. The draw is issued with
// `instanceCount * view_count` instances and each vertex reads its eye out of
// the instance id, writing `render_target_array_index` to pick the slice — so a
// headset frame costs one traversal of the scene, not two.

static inline uint view_of(uint iid, constant Frame &frame) {
    return frame.view_info.x > 1u ? iid % frame.view_info.x : 0u;
}

static inline uint instance_of(uint iid, constant Frame &frame) {
    return frame.view_info.x > 1u ? iid / frame.view_info.x : iid;
}

vertex VOutLayered vs_mesh_layered(uint vid [[vertex_id]],
                                   uint iid [[instance_id]],
                                   device const Vertex   *verts     [[buffer(0)]],
                                   constant Frame        &frame     [[buffer(1)]],
                                   constant Draw         &draw      [[buffer(2)]],
                                   device const float4x4 *instances [[buffer(3)]],
                                   device const float4   *morph_data [[buffer(6)]],
                                   constant MorphInfo    &morph      [[buffer(7)]],
                                   device const float4   *uv_sets    [[buffer(8)]],
                                   texture2d<float>        disp_map    [[texture(0)]],
                                   sampler                 disp_samp   [[sampler(0)]]) {
    uint view = view_of(iid, frame);
    if (draw.object.y == 1u) {
        return to_layered(sprite_vertex(verts[vid], frame, draw, view));
    }
    float4x4 model = model_matrix(draw, instances, instance_of(iid, frame));
    Vertex v = displace(apply_morph(verts[vid], vid, instance_of(iid, frame), morph, morph_data, instances), draw, disp_map, disp_samp);
    VOut out = transform(v, model, normal_basis(draw, instances, instance_of(iid, frame)), frame, draw, view);
    out.color *= instance_color(draw, instances, instance_of(iid, frame));
    read_uv_sets(out, vid, draw, uv_sets, model);
    return to_layered(out);
}

vertex VOutLayeredPoint vs_point_layered(uint vid [[vertex_id]],
                                    uint iid [[instance_id]],
                                    device const Vertex   *verts     [[buffer(0)]],
                                    constant Frame        &frame     [[buffer(1)]],
                                    constant Draw         &draw      [[buffer(2)]],
                                    device const float4x4 *instances [[buffer(3)]],
                                    device const float4   *morph_data [[buffer(6)]],
                                    constant MorphInfo    &morph      [[buffer(7)]],
                                    texture2d<float>        disp_map    [[texture(0)]],
                                    sampler                 disp_samp   [[sampler(0)]]) {
    uint view = view_of(iid, frame);
    float4x4 model = model_matrix(draw, instances, instance_of(iid, frame));
    Vertex v = displace(apply_morph(verts[vid], vid, instance_of(iid, frame), morph, morph_data, instances), draw, disp_map, disp_samp);
    VOut out = transform(v, model, normal_basis(draw, instances, instance_of(iid, frame)), frame, draw, view);
    return to_layered_point(point_size_for(out, frame, draw));
}

// ------------------------------------------------------------------- lighting


struct Surface {
    float3 n;
    float3 v;        // surface -> camera
    float3 albedo;
    float3 specular;
    float  shininess;
    float  roughness;
    float  metalness;
    uint   kind;
    float  toon_gradient; // 1 when a gradientMap is bound (in the matcap slot)
    /// Screen-space derivatives of the normal, for the toon ramp's
    /// antialiased step (three.js's `fwidth(coord)`).
    float3 dndx;
    float3 dndy;
    /// three.js `lightMap` irradiance (texel × `lightMapIntensity`), added to
    /// the indirect light (`lights_fragment_maps`).
    float3 light_map;
    /// three.js `specularStrength`: the `specularMap`'s red channel, else 1.
    float  specular_strength;
    /// Standard/Physical: the roughness the environment is read at —
    /// `max(roughness, 0.0525)` without the geometry term, as the wgpu path
    /// reads it.
    float  roughness_env;
    /// three.js r165 `PhysicalMaterial`'s specular lobe, as
    /// `lights_physical_fragment` fills it (Standard: F0 0.04, F90 1).
    float3 f0;
    float  f90;
    float  alpha;
    float  irid;
    float3 irid_fresnel;
    /// Anisotropy strength, negative for none; the tangent alpha; the
    /// anisotropy direction and its perpendicular (not unit, as three.js's
    /// `tbn` is not).
    float  aniso;
    float  alpha_t;
    float3 at;
    float3 ab;
    /// `sheenColor × sheen` (zero for none) and `sheenRoughness`.
    float3 sheen_color;
    float  sheen_roughness;
    /// `clearcoat` (zero for none), its roughness and normal.
    float  clearcoat;
    float  cc_roughness;
    float3 cc_n;
};

/// three.js `getGradientIrradiance`, as `toon_gradient` in
/// `renderer/shader.rs`: with a `gradientMap`, its rgb at `(n·l/2 + ½, 0)`,
/// through `coord`'s own derivatives; without one, 0.7 / 1.0 split at
/// `coord = 0.7`, antialiased. Not clamped to the lit side, as in three.js.
static inline float3 toon_gradient(Surface s, float3 l, texture2d<float> ramp, sampler ramp_samp) {
    float coord = dot(s.n, l) * 0.5 + 0.5;
    float dx = 0.5 * dot(s.dndx, l);
    float dy = 0.5 * dot(s.dndy, l);
    if (s.toon_gradient > 0.5) {
        return ramp.sample(ramp_samp, float2(coord, 0.0), gradient2d(float2(dx, 0.0), float2(dy, 0.0))).rgb;
    }
    float fw = 0.5 * (abs(dx) + abs(dy));
    return float3(mix(0.7, 1.0, smoothstep(0.7 - fw, 0.7 + fw, coord)));
}

// three.js `BRDF_BlinnPhong`, for KIND_PHONG: F_Schlick(specular) · ¼ ·
// (s/2 + 1)/π · (n·h)^s.
static inline float3 phong_specular(Surface s, float3 l) {
    float3 h = normalize(l + s.v);
    float ndh = saturate(dot(s.n, h));
    float vdh = saturate(dot(s.v, h));
    float d = (1.0 / M_PI_F) * (s.shininess * 0.5 + 1.0) * pow(ndh, s.shininess);
    return f_schlick(vdh, s.specular) * (0.25 * d);
}



// three.js `evalIridescence`: the reflectance of a `thickness` nm film of
// `film_ior` over a base of reflectance `base_f0`, seen at `cos1`.
static inline float3 eval_iridescence(float outside_ior, float film_ior_in, float cos1,
                                      float thickness, float3 base_f0) {
    float film_ior = mix(outside_ior, film_ior_in, smoothstep(0.0, 0.03, thickness));
    float sin2_sq = (outside_ior / film_ior) * (outside_ior / film_ior) * (1.0 - cos1 * cos1);
    float cos2_sq = 1.0 - sin2_sq;
    if (cos2_sq < 0.0) {
        return float3(1.0);
    }
    float cos2 = sqrt(cos2_sq);
    float r0 = pow((film_ior - outside_ior) / (film_ior + outside_ior), 2.0);
    float r12 = f_schlick_f90(float3(r0), float3(1.0), cos1).x;
    float t121 = 1.0 - r12;
    float phi12 = film_ior < outside_ior ? M_PI_F : 0.0;
    float phi21 = M_PI_F - phi12;
    float3 sqrt_f0 = sqrt(clamp(base_f0, 0.0, 0.9999));
    float3 base_ior = (1.0 + sqrt_f0) / (1.0 - sqrt_f0);
    float3 r1 = pow((base_ior - film_ior) / (base_ior + film_ior), 2.0);
    float3 r23 = f_schlick_f90(r1, float3(1.0), cos2);
    float3 phi23 = select(float3(0.0), float3(M_PI_F), base_ior < film_ior);
    float opd = 2.0 * film_ior * thickness * cos2;
    float3 phi = float3(phi21) + phi23;
    float3 r123 = clamp(r12 * r23, 1e-5, 0.9999);
    float3 r123_sqrt = sqrt(r123);
    float3 rs = t121 * t121 * r23 / (float3(1.0) - r123);
    float3 out = r12 + rs;
    float3 cm = rs - t121;
    for (int m = 1; m <= 2; ++m) {
        cm *= r123_sqrt;
        out += cm * 2.0 * eval_sensitivity(float(m) * opd, float(m) * phi);
    }
    return max(out, float3(0.0));
}

// three.js `getTangentFrame`: tangent and bitangent from screen-space
// derivatives of position and uv, scaled together (not each to unit length).
static inline TangentPair three_tangent_frame(float3 p, float3 n, float2 uv) {
    float3 q0 = dfdx(p);
    float3 q1 = dfdy(p);
    float2 st0 = dfdx(uv);
    float2 st1 = dfdy(uv);
    float3 q1perp = cross(q1, n);
    float3 q0perp = cross(n, q0);
    float3 t = q1perp * st0.x + q0perp * st1.x;
    float3 b = q1perp * st0.y + q0perp * st1.y;
    float det = max(dot(t, t), dot(b, b));
    float scale = det == 0.0 ? 0.0 : rsqrt(det);
    TangentPair f;
    f.t = t * scale;
    f.b = b * scale;
    return f;
}


// three.js `BRDF_GGX`: `F · V · D`, the Fresnel mixed toward the thin film's,
// with Filament's anisotropic V and D when there is anisotropy. As
// `brdf_ggx` in `renderer/shader.rs`.
static inline float3 brdf_ggx(Surface s, float3 l) {
    float3 h = normalize(l + s.v);
    float ndl = saturate(dot(s.n, l));
    float ndv = saturate(dot(s.n, s.v));
    float ndh = saturate(dot(s.n, h));
    float vdh = saturate(dot(s.v, h));
    float3 f = mix(f_schlick_f90(s.f0, float3(s.f90), vdh), s.irid_fresnel, s.irid);
    if (s.aniso >= 0.0) {
        float t_l = dot(s.at, l), t_v = dot(s.at, s.v), t_h = dot(s.at, h);
        float b_l = dot(s.ab, l), b_v = dot(s.ab, s.v), b_h = dot(s.ab, h);
        float gv = ndl * length(float3(s.alpha_t * t_v, s.alpha * b_v, ndv));
        float gl = ndv * length(float3(s.alpha_t * t_l, s.alpha * b_l, ndl));
        float vis = saturate(0.5 / (gv + gl));
        float a2 = s.alpha_t * s.alpha;
        float3 dv = float3(s.alpha * t_h, s.alpha_t * b_h, a2 * ndh);
        float w2 = a2 / dot(dv, dv);
        return f * (vis * a2 * w2 * w2 / M_PI_F);
    }
    return f * (v_ggx_smith_correlated(s.alpha, ndl, ndv) * d_ggx(ndh, s.alpha));
}

// Standard / Physical: three.js r165 `RE_Direct_Physical`, `irradiance ·
// (BRDF_GGX + BRDF_Lambert(diffuseColor))`, `diffuseColor = albedo · (1 −
// metalness)` and no (1 − F) on it.
static inline float3 pbr_direct(Surface s, float3 l, float ndl) {
    float3 diff = s.albedo * (1.0 - s.metalness) * (1.0 / M_PI_F);
    return (diff + brdf_ggx(s, l)) * ndl;
}

// three.js `BRDF_Sheen`: Charlie distribution, Neubelt visibility.
static inline float3 brdf_sheen(Surface s, float3 l) {
    float3 h = normalize(l + s.v);
    float ndl = saturate(dot(s.n, l));
    float ndv = saturate(dot(s.n, s.v));
    float ndh = saturate(dot(s.n, h));
    return s.sheen_color * (d_charlie(ndh, s.sheen_roughness * s.sheen_roughness) * v_neubelt(ndv, ndl));
}

// three.js `BRDF_GGX_Clearcoat` × the coat's n·l: F0 0.04, F90 1.
static inline float3 clearcoat_direct(Surface s, float3 l) {
    float3 h = normalize(l + s.v);
    float ndl = saturate(dot(s.cc_n, l));
    float ndv = saturate(dot(s.cc_n, s.v));
    float ndh = saturate(dot(s.cc_n, h));
    float vdh = saturate(dot(s.v, h));
    float a = max(s.cc_roughness * s.cc_roughness, 0.0016);
    return f_schlick_f90(float3(0.04), float3(1.0), vdh) * (v_ggx_smith_correlated(a, ndl, ndv) * d_ggx(ndh, a)) * ndl;
}

// Shadows, as `renderer/shader.rs` reads them: every casting light owns a
// `ShadowRecord` and names it in its own `color.w`, each kind's maps are one
// depth array, and the filters — basic, PCF, soft PCF, PCSS — and cascade
// selection are the same, line for line.

constant uint SHADOW_TAPS = 12u;




/// The three kinds' maps and their comparison sampler.
struct ShadowMaps {
    depth2d_array<float> dir;
    depth2d_array<float> spot;
    depth2d_array<float> point;
    sampler samp;
};

static inline float shadow_tap(thread const ShadowMaps &maps, uint kind, int layer, float3 centre,
                               float3 t, float3 b, float2 o, float depth) {
    if (kind == 2u) {
        float3 f = point_shadow_face(centre + t * o.x + b * o.y);
        return maps.point.sample_compare(maps.samp, f.xy, uint(layer + int(f.z)), depth);
    }
    float2 uv = centre.xy + o;
    return kind == 0u ? maps.dir.sample_compare(maps.samp, uv, uint(layer), depth)
                      : maps.spot.sample_compare(maps.samp, uv, uint(layer), depth);
}

static inline float shadow_pcf(thread const ShadowMaps &maps, uint kind, int layer, float3 centre,
                               float3 t, float3 b, float depth, float r, uint taps, float3 world_pos) {
    if (r <= 0.0 || taps <= 1u) {
        return shadow_tap(maps, kind, layer, centre, t, b, float2(0.0), depth);
    }
    float phi = shadow_disc_rotation(world_pos);
    float sum = 0.0;
    for (uint k = 0u; k < taps; ++k) {
        float2 o = shadow_disc_tap(k, taps, phi) * r * 1.5;
        sum += shadow_tap(maps, kind, layer, centre, t, b, o, depth);
    }
    return sum / float(taps);
}

/// Percentage-closer soft shadows with a comparison-only blocker search —
/// see `shadow_pcss` in `renderer/shader.rs`.
static inline float shadow_pcss(thread const ShadowMaps &maps, constant ShadowRecord &rec, int layer, float3 centre,
                                float3 t, float3 b, float depth, float3 world_pos) {
    uint kind = rec.info.x;
    float texel = rec.params.w;
    float search = max(rec.pcss.x, 2.0 * texel);
    float phi = shadow_disc_rotation(world_pos);
    float4 blocked = float4(0.0);
    for (uint k = 0u; k < 12u; ++k) {
        float2 o = shadow_disc_tap(k, 12u, phi) * search;
        for (uint l = 0u; l < 4u; ++l) {
            float z = depth * float(l + 1u) * 0.25;
            blocked[l] += 1.0 - shadow_tap(maps, kind, layer, centre, t, b, o, z);
        }
    }
    blocked /= 12.0;
    if (blocked.w <= 0.0) {
        return 1.0;
    }
    float integral = depth * 0.25 * (blocked.x + blocked.y + blocked.z + 0.5 * blocked.w) / blocked.w;
    float blocker = max(depth - integral, 1e-4);
    float gap;
    if (kind == 0u) {
        gap = (depth - blocker) * rec.pcss.w;
    } else if (kind == 1u) {
        float n = rec.pcss.y, f = rec.pcss.z;
        float dr = n * f / max(f - depth * (f - n), 1e-6);
        float db = n * f / max(f - blocker * (f - n), 1e-6);
        gap = (dr - db) / max(db * dr, 1e-6) * rec.pcss.w;
    } else {
        float radius = rec.extra.w;
        float dr = depth * radius, db = blocker * radius;
        gap = (dr - db) / max(db * dr, 1e-6) * rec.pcss.w;
    }
    float r = clamp(gap, texel, 64.0 * texel);
    return shadow_pcf(maps, kind, layer, centre, t, b, depth, r, 16u, world_pos);
}

static inline float shadow_filter(thread const ShadowMaps &maps, constant ShadowRecord &rec, int layer, float3 centre,
                                  float3 t, float3 b, float depth, float3 world_pos) {
    uint kind = rec.info.x;
    float r = rec.params.z;
    switch (rec.info.w) {
        case 0u: return shadow_tap(maps, kind, layer, centre, t, b, float2(0.0), depth);
        case 2u: return shadow_pcf(maps, kind, layer, centre, t, b, depth, max(r * 2.0, 2.0 * rec.params.w), 24u, world_pos);
        case 3u: return shadow_pcss(maps, rec, layer, centre, t, b, depth, world_pos);
        default: return shadow_pcf(maps, kind, layer, centre, t, b, depth, r, SHADOW_TAPS, world_pos);
    }
}

/// Record `r`'s shadow at a point: 1 lit, 0 shadowed, 1 for no record. The
/// lookup steps off the surface along the normal first (normal bias).
static inline float shadow_at(constant Frame &frame, int r, thread const ShadowMaps &maps,
                              float3 world_pos, float3 n) {
    if (r < 0 || uint(r) >= frame.shadow_info.x) {
        return 1.0;
    }
    constant ShadowRecord &rec = frame.shadows[r];
    uint kind = rec.info.x;
    float3 biased = world_pos + n * rec.params.y;
    int layer = int(rec.info.y);
    if (kind == 2u) {
        float radius = rec.extra.w;
        float3 to_frag = biased - rec.extra.xyz;
        float dist = length(to_frag);
        if (dist > radius) {
            return 1.0;
        }
        // Half a percent of the radius, at most a quarter of a unit.
        float depth = dist / radius - min(0.005, 0.25 / radius) - rec.params.x;
        float3 dir = to_frag / max(dist, 1e-6);
        float3 helper = abs(dir.y) > 0.9 ? float3(1.0, 0.0, 0.0) : float3(0.0, 1.0, 0.0);
        float3 t = normalize(cross(dir, helper));
        return shadow_filter(maps, rec, layer, dir, t, cross(dir, t), depth, world_pos);
    }
    uint cascade = 0u;
    if (kind == 0u && rec.info.z > 1u) {
        float view_depth = -(frame.view[0] * float4(world_pos, 1.0)).z;
        cascade = rec.info.z;
        for (uint c = 0u; c < rec.info.z; ++c) {
            if (view_depth <= rec.extra[c]) {
                cascade = c;
                break;
            }
        }
        if (cascade >= rec.info.z) {
            return 1.0;
        }
    }
    float4 p = rec.vp[cascade] * float4(biased, 1.0);
    float3 ndc = p.xyz / max(p.w, 1e-4);
    float2 uv = float2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
    if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) {
        return 1.0;
    }
    return shadow_filter(maps, rec, layer + int(cascade), float3(uv, 0.0), float3(0.0), float3(0.0),
                         ndc.z - rec.params.x, world_pos);
}

/// The shadow of the light whose `color.w` is `color_w`, from a fragment's
/// cache of every record's.
static inline float cached_shadow(thread const float *cache, float color_w) {
    int r = int(color_w + 0.5) - 1;
    return (r < 0 || r >= 16) ? 1.0 : cache[r];
}

/// One direct light (three.js's `RE_Direct_*`). Lambert, Phong and Toon take
/// the irradiance through `BRDF_Lambert` (÷π) — three.js r155+'s physically
/// correct light units, the same as the physical model.
static inline float3 shade_one(Surface s, float3 l, float3 light_color, float attenuation,
                               texture2d<float> ramp, sampler ramp_samp) {
    float ndl = max(dot(s.n, l), 0.0);
    if (attenuation <= 0.0) {
        return float3(0.0);
    }
    float3 c = light_color * attenuation;
    // Standard / Physical: the diffuse half here, the specular in
    // `pbr_specular_one` — three.js keeps `directDiffuse` and `directSpecular`
    // apart, and transmission replaces the diffuse alone.
    if (s.kind == KIND_STANDARD || s.kind == KIND_PHYSICAL) {
        return s.albedo * (1.0 - s.metalness) * (1.0 / M_PI_F) * ndl * c;
    }
    if (s.kind == KIND_TOON) {
        return s.albedo * (1.0 / M_PI_F) * toon_gradient(s, l, ramp, ramp_samp) * c;
    }
    float3 e = c * ndl;
    float3 out = e * s.albedo * (1.0 / M_PI_F);
    if (s.kind == KIND_PHONG) {
        out += e * phong_specular(s, l) * s.specular_strength;
    }
    return out;
}

/// One light's `BRDF_GGX` term for Standard and Physical.
static inline float3 pbr_specular_one(Surface s, float3 l, float3 light_color, float attenuation) {
    if (attenuation <= 0.0) {
        return float3(0.0);
    }
    return brdf_ggx(s, l) * max(dot(s.n, l), 0.0) * light_color * attenuation;
}





/// `[diffuse, specular]`.
static inline float2x3 rect_area_light(RectLight rl, float3 p, Surface s,
                                       texture2d_array<float> ltc, sampler ltc_samp) {
    float3 c = rl.position.xyz;
    float3 hw = rl.right.xyz;
    float3 hh = rl.up.xyz;
    float3 r0 = c + hw - hh;
    float3 r1 = c - hw - hh;
    float3 r2 = c - hw + hh;
    float3 r3 = c + hw + hh;
    float2 uv = ltc_uv(s.n, s.v, s.roughness);
    float4 t1 = ltc.sample(ltc_samp, uv, 0u, level(0.0));
    float4 t2 = ltc.sample(ltc_samp, uv, 1u, level(0.0));
    float3x3 m_inv = float3x3(float3(t1.x, 0.0, t1.y), float3(0.0, 1.0, 0.0), float3(t1.z, 0.0, t1.w));
    float3 fresnel = s.f0 * t2.x + (1.0 - s.f0) * t2.y;
    float3 diffuse = s.albedo * (1.0 - s.metalness);
    return float2x3(rl.color.rgb * diffuse * ltc_evaluate(s.n, s.v, p, float3x3(1.0), r0, r1, r2, r3),
                    rl.color.rgb * fresnel * ltc_evaluate(s.n, s.v, p, m_inv, r0, r1, r2, r3));
}

/// What `shade` gathers from the direct lights: the shaded colour, and for
/// Physical its sheen and clearcoat lobes, which three.js composes over the
/// rest afterwards (`sheenSpecularDirect`, `clearcoatSpecularDirect`).
struct Shaded {
    /// The diffuse light (all of it, for models that do not split), and for
    /// Standard and Physical the specular apart.
    float3 lit;
    float3 spec;
    float3 sheen;
    float3 cc;
};

/// One light's sheen and clearcoat (`RE_Direct_Physical`); `c` is its colour
/// times attenuation.
static inline void physical_direct(Surface s, float3 l, float3 c, thread Shaded &o) {
    if (any(s.sheen_color > 0.0)) {
        o.sheen += c * saturate(dot(s.n, l)) * brdf_sheen(s, l);
    }
    if (s.clearcoat > 0.0) {
        o.cc += c * clearcoat_direct(s, l);
    }
}

// ---- Planets: what the wgpu backend's lit path does for a body lit by a sun.



/// How much of the sun the occluder (`planet[3]`: centre, radius) leaves
/// showing from `p`: the overlap of two discs.
static inline float eclipse_factor(float3 p, float3 to_sun, constant Draw &draw) {
    float radius = draw.planet[3].w;
    float a = draw.planet[0].y;
    if (radius <= 0.0 || a <= 0.0) { return 1.0; }
    float3 v = draw.planet[3].xyz - p;
    float dist = length(v);
    if (dist < 1e-5) { return 1.0; }
    float cos_sep = dot(v / dist, to_sun);
    if (cos_sep <= 0.0) { return 1.0; }
    float b = asin(clamp(radius / max(dist, radius), 0.0, 1.0));
    float d = acos(clamp(cos_sep, -1.0, 1.0));
    if (d >= a + b) { return 1.0; }
    if (d <= b - a) { return 0.0; }
    if (d <= a - b) { return 1.0 - (b * b) / (a * a); }
    float a2 = a * a, b2 = b * b, d2 = d * d;
    float x = (d2 + a2 - b2) / (2.0 * d);
    float y = (d2 + b2 - a2) / (2.0 * d);
    float lens = a2 * acos(clamp(x / a, -1.0, 1.0)) - x * sqrt(max(a2 - x * x, 0.0))
               + b2 * acos(clamp(y / b, -1.0, 1.0)) - y * sqrt(max(b2 - y * y, 0.0));
    return clamp(1.0 - lens / (M_PI_F * a2), 0.0, 1.0);
}

/// The shadow of a cloud shell `planet[2].x` above the body, from its cloud
/// map's alpha where the ray to the sun leaves it (`cloud_shadow` in the
/// wgpu shader). The map is bound in the matcap slot.
static inline float cloud_shadow(float3 world_pos, float3 sun_world, constant Draw &draw,
                                 texture2d<float> clouds, sampler clouds_samp) {
    if (draw.planet[2].w < 0.5) { return 1.0; }
    float3x3 inv = transpose(float3x3(draw.normal_mat[0].xyz, draw.normal_mat[1].xyz,
                                      draw.normal_mat[2].xyz));
    float3 sv = normalize(inv * sun_world);
    // The object-space point: the model's linear part undone.
    float3x3 lin = float3x3(draw.model[0].xyz, draw.model[1].xyz, draw.model[2].xyz);
    float3 r0 = cross(lin[1], lin[2]), r1 = cross(lin[2], lin[0]), r2 = cross(lin[0], lin[1]);
    float3x3 lin_inv = transpose(float3x3(r0, r1, r2)) * (1.0 / dot(lin[0], r0));
    float3 n = normalize(lin_inv * (world_pos - draw.model[3].xyz));
    float rc = 1.0 + max(draw.planet[2].x, 1e-4);
    float b = dot(n, sv);
    float t = -b + sqrt(max(b * b + rc * rc - 1.0, 0.0));
    float3 q = normalize(n + sv * t);
    float u = atan2(q.z, -q.x) / (2.0 * M_PI_F) + draw.planet[2].z;
    float v = 1.0 - acos(clamp(q.y, -1.0, 1.0)) / M_PI_F;
    float cover = clouds.sample(clouds_samp, float2(u, v)).a;
    return 1.0 - clamp(cover, 0.0, 1.0) * clamp(draw.planet[2].y, 0.0, 1.0);
}

static inline Shaded shade(Surface s,
                           float3 world_pos,
                           constant Frame &frame,
                           float ao,
                           depth2d_array<float> shadow_map,
                           depth2d_array<float> spot_map,
                           depth2d_array<float> point_map,
                           sampler shadow_samp,
                           bool receives_shadow,
                           texture2d_array<float> ltc,
                           sampler ltc_samp,
                           texture2d<float> ramp,
                           sampler ramp_samp,
                           constant Draw &draw) {
    // Ambient and hemisphere light are irradiance, through `BRDF_Lambert` like
    // the direct lights (`RE_IndirectDiffuse_*`): ÷π, and the physical model's
    // diffuse colour is the albedo less the metal.
    bool pbr = s.kind == KIND_STANDARD || s.kind == KIND_PHYSICAL;
    float3 diffuse_color = pbr ? s.albedo * (1.0 - s.metalness) : s.albedo;
    float3 irr = frame.ambient.rgb + s.light_map;
    for (uint i = 0u; i < frame.counts.w && i < 2u; ++i) {
        constant HemiLight &h = frame.hemis[i];
        float t = dot(s.n, normalize(h.direction.xyz)) * 0.5 + 0.5;
        irr += mix(h.ground_color.rgb, h.sky_color.rgb, t);
    }
    // Every record's shadow once (`compute_shadows` in `renderer/shader.rs`:
    // one inlined copy of the filters rather than one per light loop).
    ShadowMaps maps = { shadow_map, spot_map, point_map, shadow_samp };
    float shadow_cache[16];
    for (uint r = 0u; r < 16u; ++r) {
        shadow_cache[r] = 1.0;
    }
    if (receives_shadow) {
        uint count = min(frame.shadow_info.x, 16u);
        for (uint r = 0u; r < count; ++r) {
            shadow_cache[r] = shadow_at(frame, int(r), maps, world_pos, s.n);
        }
    }
    Shaded o;
    o.lit = diffuse_color * irr * (1.0 / M_PI_F) * ao;
    o.spec = float3(0.0);
    o.sheen = float3(0.0);
    o.cc = float3(0.0);
    // The first directional light is the sun a planet's terms are for: its
    // cloud shadow and eclipse (`planet`, zero for everything else).
    float sun_att = 1.0;
    if (pbr && frame.counts.x > 0u) {
        float3 to_sun = normalize(-frame.dir[0].direction.xyz);
        sun_att = cloud_shadow(world_pos, to_sun, draw, ramp, ramp_samp)
                * eclipse_factor(world_pos, to_sun, draw);
    }
    float sun_radius = pbr ? draw.planet[0].y : 0.0;
    // Every casting light its own shadow (a layer of its kind's map array).
    for (uint i = 0u; i < frame.counts.x && i < 4u; ++i) {
        DirLight d = frame.dir[i];
        float att = receives_shadow
            ? cached_shadow(shadow_cache, d.color.w)
            : 1.0;
        if (i == 0u) { att *= sun_att; }
        float3 l = normalize(-d.direction.xyz);
        if (sun_radius > 0.0) {
            // A sun of finite size: its light wraps past the terminator, for
            // the diffuse and specular lobes alike.
            float soft = soft_lambert(dot(s.n, l), sun_radius);
            float3 c = d.color.rgb * att;
            if (att > 0.0) {
                o.lit += s.albedo * (1.0 - s.metalness) * (1.0 / M_PI_F) * soft * c;
                o.spec += brdf_ggx(s, l) * soft * c;
            }
        } else {
            o.lit += shade_one(s, l, d.color.rgb, att, ramp, ramp_samp);
            if (pbr) { o.spec += pbr_specular_one(s, l, d.color.rgb, att); }
        }
        physical_direct(s, l, d.color.rgb * att, o);
        if (pbr && i == 0u) {
            // Twilight: a warm band along the terminator.
            float width = draw.planet[0].z;
            if (width > 0.0) {
                float x = dot(s.n, l) / width;
                float band = exp(-x * x * 3.0) * (1.0 - smoothstep(0.0, 1.0, max(x, 0.0)));
                o.lit += d.color.rgb * draw.planet[1].rgb * s.albedo * band * 0.15 * att / M_PI_F;
            }
            // Clouds lit from behind: forward scattering toward the eye.
            float scatter = draw.planet[0].w;
            if (scatter > 0.0) {
                float phase = henyey_greenstein(dot(-l, s.v), clamp(draw.planet[1].w, -0.95, 0.95));
                float slant = min(1.0 / max(abs(dot(s.n, s.v)), 0.08), 8.0);
                float reach = clamp(dot(s.n, l) * 2.0 + 0.55, 0.0, 1.0);
                o.lit += d.color.rgb * s.albedo * scatter * phase * slant * reach * att;
            }
        }
    }
    for (uint i = 0u; i < frame.counts.y && i < 8u; ++i) {
        PointLight p = frame.pts[i];
        float3 to_light = p.position.xyz - world_pos;
        float dist = length(to_light);
        float att = punctual_attenuation(dist, p.params.x, p.params.y);
        att *= cached_shadow(shadow_cache, p.color.w);
        float3 l = to_light / max(dist, 1e-4);
        o.lit += shade_one(s, l, p.color.rgb, att, ramp, ramp_samp);
        if (pbr) { o.spec += pbr_specular_one(s, l, p.color.rgb, att); }
        physical_direct(s, l, p.color.rgb * att, o);
    }
    for (uint i = 0u; i < frame.counts.z && i < 4u; ++i) {
        SpotLight sp = frame.spots[i];
        float3 to_light_vec = sp.position.xyz - world_pos;
        float dist = length(to_light_vec);
        float3 to_light = to_light_vec / max(dist, 1e-4);
        float cos_angle = dot(-to_light, normalize(sp.direction.xyz));
        float cone = cos_angle > sp.params.z
                   ? smoothstep(sp.params.z, sp.params.w, cos_angle)
                   : 0.0;
        float att = punctual_attenuation(dist, sp.params.x, sp.params.y) * cone;
        att *= cached_shadow(shadow_cache, sp.color.w);
        o.lit += shade_one(s, to_light, sp.color.rgb, att, ramp, ramp_samp);
        if (pbr) { o.spec += pbr_specular_one(s, to_light, sp.color.rgb, att); }
        physical_direct(s, to_light, sp.color.rgb * att, o);
    }
    // `RE_Direct_RectArea_Physical`: Standard and Physical only, and no
    // sheen or clearcoat, as in three.js.
    if (pbr) {
        for (uint i = 0u; i < frame.rect_counts.x && i < 4u; ++i) {
            float2x3 rt = rect_area_light(frame.rects[i], world_pos, s, ltc, ltc_samp);
            o.lit += rt[0];
            o.spec += rt[1];
        }
    }
    return o;
}

/// How much of a fragment `view_dist` away the fog replaces, 0 to 1.
static inline float fog_amount(float view_dist, constant Frame &frame) {
    uint mode = uint(frame.fog_color.w + 0.5);
    if (mode == 0u) {
        return 0.0;
    }
    float f;
    if (mode == 2u) {
        float d = frame.fog_params.z * view_dist;
        f = 1.0 - exp(-d * d);
    } else {
        f = (view_dist - frame.fog_params.x) /
            max(frame.fog_params.y - frame.fog_params.x, 1e-4);
    }
    return clamp(f, 0.0, 1.0);
}

static inline float3 apply_fog(float3 color, float view_dist, constant Frame &frame) {
    return mix(color, frame.fog_color.rgb, fog_amount(view_dist, frame));
}

/// What fog is measured along: the fragment's depth in view space, three.js's
/// `fogDepth` (`-mvPosition.z`) and the wgpu backend's `view_z`. Worked out
/// per fragment from the interpolated world position, which is exact: a
/// distance interpolated between vertices is not, and across a large
/// triangle — a ground plane is two — it is the corners' distance everywhere,
/// fogging what is under the camera as if it were at the horizon.
static inline float fog_depth(float3 world_pos, uint view_index, constant Frame &frame) {
    return max(-(frame.view[view_index] * float4(world_pos, 1.0)).z, 0.0);
}

// -------------------------------------------------------------- tone mapping

// three.js r165 `tonemapping_pars_fragment`, as the wgpu backend's
// `apply_tone_mapping`: `frame.view_info.z` is the mode (0 none, 1 linear,
// 2 ACES filmic, 3 neutral, 4 AgX) and `.w` the exposure's bits. A material
// with `toneMapped: false` (`draw.object.w == 0`) is left alone, as three.js
// compiles it without TONE_MAPPING.
static inline float3 tone_map(float3 c, constant Frame &frame, constant Draw &draw) {
    uint mode = frame.view_info.z;
    if (mode == 0u || draw.object.w == 0u) {
        return c;
    }
    const float3 e = c * as_type<float>(frame.view_info.w);
    if (mode == 1u) { return linear_tonemap(e); }
    if (mode == 2u) { return aces_tonemap(e); }
    if (mode == 3u) { return neutral_tonemap(e); }
    return agx_tonemap(e);
}

// ----------------------------------------------------------------------- IBL

// Image-based lighting, mirroring `sample_env_cube` / `dfg_approx` in
// `renderer/shader.rs` so the two renderers agree about what a room looks like
// reflected in a phone.
//
// The environment arrives as a plain cube with its own mip chain rather than
// the PMREM atlas the wgpu path prefers, so roughness picks a level directly.
// `roughness²` is the mapping: roughness is authored perceptually and the
// filter width goes as alpha, and the wgpu side learned the same thing the hard
// way — it used to map the whole of 0..1 onto seven tenths of one level, so a
// mirror and a rough metal came back identically blurred.
static inline float3 sample_env(texturecube<float> env,
                                sampler samp,
                                float3 dir,
                                float roughness) {
    float levels = float(env.get_num_mip_levels()) - 1.0;
    float mip = clamp(roughness * roughness * levels, 0.0, levels);
    float lo = floor(mip);
    float f = mip - lo;
    float3 c0 = env.sample(samp, dir, level(lo)).rgb;
    if (f <= 0.0) {
        return c0;
    }
    return mix(c0, env.sample(samp, dir, level(lo + 1.0)).rgb, f);
}

// three.js `cube_uv_reflection_fragment`: a PMREM's CubeUV atlas, read by
// direction and roughness — the same lookup as the wgpu path's
// `texture_cube_uv`. `params`: texel width and height, the top mip.
constant float CUBEUV_MIN_MIP_LEVEL = 4.0;
constant float CUBEUV_MIN_TILE_SIZE = 16.0;



static inline float3 bilinear_cube_uv(texture2d<float> atlas, sampler samp, float3 d,
                                      float mip_int, float4 params) {
    float face = cube_uv_get_face(d);
    float filter_int = max(CUBEUV_MIN_MIP_LEVEL - mip_int, 0.0);
    float mip_i = max(mip_int, CUBEUV_MIN_MIP_LEVEL);
    float face_size = exp2(mip_i);
    float2 uv = cube_uv_get_uv(d, face) * (face_size - 2.0) + 1.0;
    if (face > 2.0) {
        uv.y += face_size;
        face -= 3.0;
    }
    uv.x += face * face_size;
    uv.x += filter_int * 3.0 * CUBEUV_MIN_TILE_SIZE;
    uv.y += 4.0 * (exp2(params.z) - face_size);
    uv *= params.xy;
    // three.js's uv math is bottom-left; the atlas's rows are top first.
    uv.y = 1.0 - uv.y;
    return atlas.sample(samp, uv, level(0.0)).rgb;
}


static inline float3 texture_cube_uv(texture2d<float> atlas, sampler samp, float3 d,
                                     float roughness, float4 params) {
    float mip = clamp(roughness_to_mip(roughness), -2.0, params.z);
    float f = fract(mip);
    float i = floor(mip);
    float3 c0 = bilinear_cube_uv(atlas, samp, d, i, params);
    if (f <= 0.0) {
        return c0;
    }
    return mix(c0, bilinear_cube_uv(atlas, samp, d, i + 1.0, params), f);
}




static inline float4 transmission_bicubic(texture2d_array<float> tex, sampler smp, float2 uv_in, uint slice, float4 texel, float lod) {
    float2 uv = uv_in * texel.zw + 0.5;
    float2 iuv = floor(uv);
    float2 fuv = fract(uv);
    float g0x = bicubic_g0(fuv.x), g1x = bicubic_g1(fuv.x);
    float h0x = bicubic_h0(fuv.x), h1x = bicubic_h1(fuv.x);
    float h0y = bicubic_h0(fuv.y), h1y = bicubic_h1(fuv.y);
    float2 p0 = (float2(iuv.x + h0x, iuv.y + h0y) - 0.5) * texel.xy;
    float2 p1 = (float2(iuv.x + h1x, iuv.y + h0y) - 0.5) * texel.xy;
    float2 p2 = (float2(iuv.x + h0x, iuv.y + h1y) - 0.5) * texel.xy;
    float2 p3 = (float2(iuv.x + h1x, iuv.y + h1y) - 0.5) * texel.xy;
    return bicubic_g0(fuv.y) * (g0x * tex.sample(smp, p0, slice, level(lod)) + g1x * tex.sample(smp, p1, slice, level(lod)))
         + bicubic_g1(fuv.y) * (g0x * tex.sample(smp, p2, slice, level(lod)) + g1x * tex.sample(smp, p3, slice, level(lod)));
}

// The capture holds a slice per view, each the scene from that view: a layered
// pass reads slice `view_index`; a per-view pass, whose view sits in slot 0,
// the slice `rect_counts.w` names.
static inline float4 transmission_sample(float3 p, float roughness, float ior, constant Frame &frame, uint view_index,
                                         texture2d_array<float> tex, sampler smp) {
    uint slice = min(view_index + frame.rect_counts.w, tex.get_array_size() - 1u);
    float4 ndc = frame.view_proj[view_index] * float4(p, 1.0);
    float2 xy = ndc.xy / ndc.w;
    float2 uv = float2(xy.x * 0.5 + 0.5, 0.5 - xy.y * 0.5);
    float lod = log2(float(tex.get_width(0))) * roughness * clamp(ior * 2.0 - 2.0, 0.0, 1.0);
    int last = max(int(frame.rect_counts.y) - 1, 0);
    int fl = min(int(floor(lod)), last);
    int cl = min(int(ceil(lod)), last);
    float2 fs = float2(tex.get_width(fl), tex.get_height(fl));
    float2 cs = float2(tex.get_width(cl), tex.get_height(cl));
    float4 f = transmission_bicubic(tex, smp, uv, slice, float4(1.0 / fs, fs), float(fl));
    float4 c = transmission_bicubic(tex, smp, uv, slice, float4(1.0 / cs, cs), float(cl));
    return mix(f, c, fract(lod));
}

static inline float3 volume_transmission_ray(float3 n, float3 v, float thickness, float ior, constant Draw &draw) {
    float3 r = refract(-v, normalize(n), 1.0 / ior);
    float3 scale = float3(length(draw.model[0].xyz), length(draw.model[1].xyz), length(draw.model[2].xyz));
    return normalize(r) * thickness * scale;
}


/// three.js `getIBLVolumeRefraction`.
static inline float4 ibl_volume_refraction(Surface s, float3 position, float roughness, float ior,
                                           float thickness, float dispersion, float3 attenuation_color,
                                           float attenuation_distance, constant Frame &frame,
                                           constant Draw &draw, uint view_index,
                                           texture2d_array<float> tex, sampler smp) {
    float3 diffuse_color = s.albedo * (1.0 - s.metalness);
    float4 transmitted = float4(0.0);
    float3 transmittance = float3(0.0);
    if (dispersion > 0.0) {
        float half_spread = (ior - 1.0) * 0.025 * dispersion;
        float3 iors = float3(ior - half_spread, ior, ior + half_spread);
        for (uint i = 0u; i < 3u; ++i) {
            float3 ray = volume_transmission_ray(s.n, s.v, thickness, iors[i], draw);
            float4 t = transmission_sample(position + ray, roughness, iors[i], frame, view_index, tex, smp);
            transmitted[i] = t[i];
            transmitted.a += t.a;
            transmittance[i] = diffuse_color[i] * volume_attenuation(length(ray), attenuation_color, attenuation_distance)[i];
        }
        transmitted.a /= 3.0;
    } else {
        float3 ray = volume_transmission_ray(s.n, s.v, thickness, ior, draw);
        transmitted = transmission_sample(position + ray, roughness, ior, frame, view_index, tex, smp);
        transmittance = diffuse_color * volume_attenuation(length(ray), attenuation_color, attenuation_distance);
    }
    float3 attenuated = transmittance * transmitted.rgb;
    float2 fab = dfg_approx(s.n, s.v, roughness);
    float3 f = s.f0 * fab.x + s.f90 * fab.y;
    float factor = (transmittance.r + transmittance.g + transmittance.b) / 3.0;
    return float4((1.0 - f) * attenuated, 1.0 - (1.0 - transmitted.a) * factor);
}

/// The environment's radiance along `dir` at `roughness`, rotated and scaled
/// as `ibl` reads it — three.js's `getIBLRadiance` lookup.
static inline float3 env_radiance(float3 dir,
                                  float roughness,
                                  texturecube<float> env,
                                  sampler samp,
                                  constant Draw &draw,
                                  texture2d<float> atlas,
                                  sampler atlas_samp) {
    float3 d = float3(dot(draw.env_dir[0].xyz, dir), dot(draw.env_dir[1].xyz, dir),
                      dot(draw.env_dir[2].xyz, dir));
    bool cube_uv = draw.env_params.w > 0.5;
    return (cube_uv ? texture_cube_uv(atlas, atlas_samp, d, roughness, draw.env_params)
                    : sample_env(env, samp, d, roughness)) * draw.map_params.z;
}

/// The environment's contribution, diffuse and specular, occluded — three.js
/// r165 `RE_IndirectSpecular_Physical` with `computeMultiscattering`
/// (`…Iridescence`): the reflectance is the lobe's F0 mixed toward the thin
/// film's Fresnel, at its F90, and anisotropy bends the normal the
/// environment is reflected about (`getIBLAnisotropyRadiance`).
/// `[diffuse, specular]`.
static inline float2x3 ibl(Surface s,
                         texturecube<float> env,
                         sampler samp,
                         float ao,
                         constant Draw &draw,
                         texture2d<float> atlas,
                         sampler atlas_samp) {
    float roughness = s.roughness_env;
    float3 specular_color = mix(s.f0, s.irid_fresnel, s.irid);
    float3 diffuse_color = s.albedo * (1.0 - s.metalness);

    float3 refl_n = s.n;
    if (s.aniso >= 0.0) {
        float3 bent = normalize(cross(cross(s.ab, s.v), s.ab));
        float bend = 1.0 - s.aniso * (1.0 - roughness);
        bend *= bend;
        refl_n = normalize(mix(bent, s.n, bend * bend));
    }
    // `getIBLRadiance`: pulled toward that normal as roughness rises, which is
    // what keeps a rough surface from mirroring a sharp edge of the room.
    float3 refl = reflect(-s.v, refl_n);
    refl = normalize(mix(refl, refl_n, roughness * roughness));
    float3 radiance = env_radiance(refl, roughness, env, samp, draw, atlas, atlas_samp);
    float3 irradiance = env_radiance(s.n, 1.0, env, samp, draw, atlas, atlas_samp) * M_PI_F;

    float2 fab = dfg_approx(s.n, s.v, roughness);
    float3 fss_ess = specular_color * fab.x + float3(s.f90 * fab.y);
    float ess = fab.x + fab.y;
    float ems = 1.0 - ess;
    float3 favg = specular_color + (float3(1.0) - specular_color) * 0.047619;
    float3 fms = fss_ess * favg / (float3(1.0) - ems * favg);
    float3 multi_scatter = fms * ems;
    float3 total = fss_ess + multi_scatter;
    float scatter_max = max(max(total.r, total.g), total.b);
    float3 cosine_weighted = irradiance * (1.0 / M_PI_F);

    float spec_occ = specular_occlusion(saturate(dot(s.n, s.v)), ao, roughness);
    float3 spec = (radiance * fss_ess + multi_scatter * cosine_weighted) * spec_occ;
    // The environment's diffuse term, added exactly once — the ambient lights
    // are accounted for separately in `shade`, and adding this there as well is
    // how a white surface ends up reflecting more light than reaches it.
    float3 diffuse = diffuse_color * (1.0 - scatter_max) * cosine_weighted * ao;
    return float2x3(diffuse, spec);
}


// ------------------------------------------------------------------- fragment

static inline float4 sample_base(constant Draw &draw,
                                 texture2d<float> base_map,
                                 sampler samp,
                                 float2 uv, float4 uv12, float2 uv3) {
    float4 base = draw.base_color;
    if (draw.flags.y == 1u) {
        base *= base_map.sample(samp, map_uv_sets(draw, MAP_BASE, uv, uv12, uv3));
    }
    return base;
}

// Tangent frame from screen-space derivatives, so a normal map works without
// tangent attributes.
//
// The vertex stage here carries position, normal, uv and colour and no tangent,
// and adding one would mean touching every geometry path for a slot most of
// them never fill. This is the standard alternative (Mikkelsen 2010): the
// derivatives of position and uv across the quad give the same basis the
// tangent would have, evaluated per pixel. It costs four derivatives and agrees
// with a supplied tangent wherever the UVs are not degenerate.
// three.js `envmap_fragment` (Basic, Lambert, Phong): the reflected — or, for a
// refraction-mapped cube, refracted — view ray looks the `envMap` up, and the
// result meets `outgoing` per `combine`, weighted by `specularStrength ×
// reflectivity`. The ray is the camera's forward axis for an orthographic view
// (whose view-projection has a constant w row), as three.js's `isOrthographic`.
static inline float3 apply_env_map(float3 outgoing, float3 n, float3 world_pos,
                                   float specular_strength, constant Frame &frame,
                                   constant Draw &draw, uint view_index,
                                   texturecube<float> env, sampler samp) {
    if (draw.map_scalars.z < 0.5) {
        return outgoing;
    }
    float4x4 vp = frame.view_proj[view_index];
    float4x4 v = frame.view[view_index];
    bool ortho = abs(vp[0][3]) + abs(vp[1][3]) + abs(vp[2][3]) < 1e-6;
    float3 to_frag = ortho ? normalize(-float3(v[0][2], v[1][2], v[2][2]))
                           : normalize(world_pos - frame.camera_pos[view_index].xyz);
    float3 r = draw.env_params.w > 0.5 ? refract(to_frag, n, draw.env_params.z)
                                       : reflect(to_frag, n);
    float3 dir = float3(dot(draw.env_dir[0].xyz, r), dot(draw.env_dir[1].xyz, r),
                        dot(draw.env_dir[2].xyz, r));
    float3 e = env.sample(samp, dir).rgb;
    float k = specular_strength * draw.env_params.y;
    uint combine = uint(draw.env_params.x + 0.5);
    if (combine == 1u) { return mix(outgoing, e, k); }
    if (combine == 2u) { return outgoing + e * k; }
    return mix(outgoing, outgoing * e, k);
}

// three.js `bumpmap_pars_fragment`: `dHdxy_fwd` and `perturbNormalArb`
// (Mikkelsen), in world space — the construction is crosses and dots, so the
// view rotation changes nothing, and nor does the framebuffer's y direction.
static inline float3 bump_normal(float3 n, float3 pos, float2 uv, float4 uv12, float2 uv3,
                                 float face, constant Draw &draw, texture2d<float> bump_map,
                                 sampler samp) {
    float scale = draw.map_scalars.y;
    float2 st = map_uv_sets(draw, MAP_BUMP, uv, uv12, uv3);
    float2 dstdx = dfdx(st);
    float2 dstdy = dfdy(st);
    float hll = scale * bump_map.sample(samp, st).x;
    float dbx = scale * bump_map.sample(samp, st + dstdx).x - hll;
    float dby = scale * bump_map.sample(samp, st + dstdy).x - hll;
    float3 sigma_x = normalize(dfdx(pos));
    float3 sigma_y = normalize(dfdy(pos));
    float3 r1 = cross(sigma_y, n);
    float3 r2 = cross(n, sigma_x);
    float det = dot(sigma_x, r1) * face;
    float3 grad = sign(det) * (dbx * r1 + dby * r2);
    return normalize(abs(det) * n - grad);
}

static inline float3 perturb_normal(float3 n,
                                    float3 world_pos,
                                    float2 uv,
                                    float3 map_sample,
                                    float2 scale,
                                    float4 tangent) {
    // The `tangent` attribute's frame when the geometry has one, as the wgpu
    // backend's `surface_frame`; screen-space derivatives otherwise.
    if (dot(tangent.xyz, tangent.xyz) > 1e-12) {
        TangentPair none;
        none.t = float3(0.0);
        none.b = float3(0.0);
        TangentPair f = attribute_frame(tangent, n, none);
        if (dot(f.t, f.t) > 0.0) {
            float3 m = map_sample * 2.0 - 1.0;
            m.xy *= scale;
            float3 p = f.t * m.x + f.b * m.y + n * m.z;
            return dot(p, p) > 1e-12 ? normalize(p) : n;
        }
    }
    // The wgpu backend's `cotangent_frame`: the tangent from the position and
    // uv derivatives, made unit length, and the bitangent at right angles to
    // it. three.js's `perturbNormal2Arb` keeps the two derivatives' lengths
    // instead, and where a UV sphere pinches to its poles one of them is far
    // shorter than the other — the relief along it fades to nothing, which
    // `examples/pole_probe` shows. A unit frame keeps it at full strength.
    float3 dpx = dfdx(world_pos);
    float3 dpy = dfdy(world_pos);
    float2 duvx = dfdx(uv);
    float2 duvy = dfdy(uv);
    float det = duvx.x * duvy.y - duvy.x * duvx.y;
    float3 t = float3(0.0);
    if (abs(det) > 1e-12) {
        t = (dpx * duvy.y - dpy * duvx.y) / det;
        t = t - n * dot(n, t);
    }
    if (dot(t, t) < 1e-12) {
        t = dpx - n * dot(n, dpx);
        if (dot(t, t) < 1e-12) { t = dpy - n * dot(n, dpy); }
    }
    if (dot(t, t) < 1e-12) {
        t = abs(n.x) > 0.9 ? float3(0.0, 1.0, 0.0) : float3(1.0, 0.0, 0.0);
        t = t - n * dot(n, t);
    }
    t = normalize(t);
    float3 b = normalize(cross(n, t));
    float3 m = map_sample * 2.0 - 1.0;
    m.xy *= scale;
    float3 p = t * m.x + b * m.y + n * m.z;
    return dot(p, p) > 1e-12 ? normalize(p) : n;
}

static inline float4 mesh_fragment(FIn in,
                                   bool front_facing,
                                   constant Frame   &frame,
                                   constant Draw    &draw,
                                   texture2d<float>  base_map,
                                   texture2d<float>  emissive_map,
                                   texture2d<float>  normal_map,
                                   texture2d<float>  mr_map,
                                   texture2d<float>  ao_map,
                                   texturecube<float> env_map,
                                   depth2d_array<float> shadow_map,
                                   depth2d_array<float> spot_map,
                                   depth2d_array<float> point_map,
                                   sampler           samp,
                                   sampler           env_samp,
                                   sampler           shadow_samp,
                                   sampler           emissive_samp,
                                   sampler           normal_samp,
                                   sampler           mr_samp,
                                   sampler           ao_samp,
                                   texture2d<float>  alpha_map,
                                   sampler           alpha_samp,
                                   texture2d<float>  light_map,
                                   sampler           light_samp,
                                   texture2d<float>  bump_map,
                                   sampler           bump_samp,
                                   texture2d<float>  specular_map,
                                   sampler           specular_samp,
                                   texturecube<float> mat_env,
                                   sampler           mat_env_samp,
                                   texture2d<float>  matcap_tex,
                                   sampler           matcap_samp,
                                   texture2d<float>  env_atlas,
                                   sampler           env_atlas_samp,
                                   texture2d_array<float> ltc,
                                   texture2d_array<float> transmission_tex,
                                   sampler           transmission_samp,
                                   thread const PhysTexels &phys,
                                   thread float3 &glass_t) {
    if (clipped(draw, in.world_pos)) {
        discard_fragment();
    }
    // Blended glass (`TransparencyMode::Glass`, `Oit`): what passes of the
    // background, per channel, for the caller's blend. Negative otherwise.
    glass_t = float3(-1.0);
    uint kind = draw.flags.x;
    float3 n = normalize(in.normal);
    if (!front_facing) {
        n = -n;   // double-sided lighting, as three.js does for BackSide/DoubleSide
    }

    if (kind == KIND_NORMAL) {
        // three.js MeshNormalMaterial: the *view-space* normal packed to rgb
        // and written as data, with no transfer curve — so on a target that
        // sRGB-encodes on write, decode first and the stored byte is the value.
        float3 view_n = normalize((frame.view[in.view_index] * float4(n, 0.0)).xyz);
        float3 packed = saturate(view_n * 0.5 + 0.5);
        if ((frame.view_info.y & 1u) != 0u) {
            packed = select(pow((packed + 0.055) / 1.055, float3(2.4)), packed / 12.92,
                            packed <= float3(0.04045));
        }
        return float4(packed, draw.base_color.a);
    }
    if (kind == KIND_DEPTH || kind == KIND_DISTANCE) {
        float near = draw.misc.z;
        float far = max(draw.misc.w, near + 1e-4);
        float d = clamp((in.view_dist - near) / (far - near), 0.0, 1.0);
        return float4(float3(1.0 - d), draw.base_color.a);
    }

    if (kind == KIND_ATMOSPHERE) {
        // Planetary atmosphere, as the wgpu shader's `MAT_ATMOSPHERE`: march
        // the view ray through the shell between the planet and the top of
        // the air, and shade from how much air it crosses and how much of
        // that is in sunlight. `physical[0..3]` carry the material
        // (`MetalRenderer`'s `atmosphere_uniforms`).
        float3 centre = (draw.model * float4(0.0, 0.0, 0.0, 1.0)).xyz;
        float r_planet = draw.physical[0].x;
        float r_air = max(draw.physical[0].y, r_planet + 1e-5);
        float strength = draw.physical[0].z;
        float falloff = max(draw.physical[0].w, 0.1);

        float3 eye = frame.camera_pos[in.view_index].xyz;
        float3 dir = normalize(in.world_pos - eye);
        float3 oc = eye - centre;
        float b = dot(oc, dir);
        float disc_air = b * b - (dot(oc, oc) - r_air * r_air);
        if (disc_air <= 0.0) { discard_fragment(); }
        float root = sqrt(disc_air);
        float t_enter = max(-b - root, 0.0);
        float t_exit = -b + root;
        if (t_exit <= t_enter) { discard_fragment(); }
        float disc_planet = b * b - (dot(oc, oc) - r_planet * r_planet);
        if (disc_planet > 0.0) {
            float t_hit = -b - sqrt(disc_planet);
            if (t_hit > 0.0) { t_exit = min(t_exit, t_hit); }
        }
        if (t_exit <= t_enter) { discard_fragment(); }

        const int steps = 8;
        float dt = (t_exit - t_enter) / float(steps);
        float depth_scale = max(r_air - r_planet, 1e-5);
        float density = 0.0, lit = 0.0, sun_path = 0.0, glow_g = 0.0, glow_r = 0.0;
        float aurora = draw.physical[2].w;
        float ring = max(draw.physical[3].w, 1.0) * (M_PI_F / 180.0);
        float mag_tilt = 0.19;
        float3 mag_axis = normalize(float3(sin(mag_tilt) * 0.9, 1.0, sin(mag_tilt) * 0.4));
        float3 to_sun = frame.counts.x > 0u ? normalize(-frame.dir[0].direction.xyz) : float3(0.0, 1.0, 0.0);
        for (int i = 0; i < steps; i++) {
            float3 p = eye + dir * (t_enter + dt * (float(i) + 0.5));
            float3 up = p - centre;
            float altitude = (length(up) - r_planet) / depth_scale;
            float d = exp(-max(altitude, 0.0) * falloff) * dt;
            density += d;
            float sun_dot = dot(normalize(up), to_sun);
            lit += d * smoothstep(-0.25, 0.35, sun_dot);
            float low = exp(-max(altitude, 0.0) * falloff * 2.0);
            sun_path += d * low * (1.0 - smoothstep(0.0, 0.55, abs(sun_dot)));
            if (aurora > 0.0) {
                float3 un = normalize(up);
                float colat = acos(clamp(abs(dot(un, mag_axis)), -1.0, 1.0));
                float x = (colat - ring) / (ring * 0.34);
                float band = exp(-(x * x));
                float ph = atan2(dot(un, float3(0.0, 0.0, 1.0)), dot(un, float3(1.0, 0.0, 0.0)));
                float curtain = 0.55 + 0.45 * sin(ph * 9.0) * sin(ph * 23.0 + 1.7);
                float wgt = band * curtain * dt;
                glow_g += wgt * smoothstep(0.04, 0.16, altitude) * (1.0 - smoothstep(0.22, 0.5, altitude));
                glow_r += wgt * smoothstep(0.3, 0.55, altitude) * (1.0 - smoothstep(0.75, 1.0, altitude)) * 0.35;
            }
        }
        if (density <= 1e-6) { discard_fragment(); }
        float day = lit / density;
        float grazing = sun_path / density;
        float mu = dot(dir, to_sun);
        float phase = 0.75 * (1.0 + mu * mu);
        float max_chord = 2.0 * sqrt(max(r_air * r_air - r_planet * r_planet, 1e-6));
        float tau = density / max_chord * strength;
        float alpha = (1.0 - exp(-tau)) * day * draw.base_color.a;
        if (alpha <= 0.002) { discard_fragment(); }

        float3 tint = mix(draw.base_color.rgb, draw.physical[1].rgb, clamp(grazing * 1.15, 0.0, 1.0));
        float3 col = tint * phase * (0.35 + 0.65 * day);
        float out_a = alpha;
        float ozone = draw.physical[2].z;
        if (ozone > 0.0) {
            col *= exp(-float3(3.1, 2.0, 0.35) * ozone * grazing);
        }
        if (aurora > 0.0) {
            float night = 1.0 - day;
            float gg = glow_g / max_chord * aurora;
            float gr = glow_r / max_chord * aurora;
            if (gg + gr > 0.0) {
                col += (draw.physical[3].rgb * gg + float3(1.0, 0.22, 0.30) * gr) * night * 6.0;
                out_a = max(out_a, clamp((gg + gr) * night * 8.0, 0.0, 1.0));
            }
        }
        return float4(apply_fog(col, fog_depth(in.world_pos, in.view_index, frame), frame), clamp(out_a, 0.0, 1.0));
    }

    float4 base = sample_base(draw, base_map, samp, in.uv, in.uv12, in.uv3);
    base *= in.color;
    // three.js `alphamap_fragment`: the green channel scales the alpha.
    if (draw.extra.x == 1u) {
        base.a *= alpha_map.sample(alpha_samp, map_uv_sets(draw, MAP_ALPHA, in.uv, in.uv12, in.uv3)).g;
    }
    if (base.a < draw.pbr.z) {
        discard_fragment();
    }

    if (kind == KIND_MATCAP) {
        // three.js `meshmatcap.glsl`: the view-space normal in a frame built
        // around the view direction, × 0.495; no matcap: mix(0.2, 0.8, uv.y).
        float3 view_n = normalize((frame.view[in.view_index] * float4(n, 0.0)).xyz);
        float3 view_dir = normalize(-(frame.view[in.view_index] * float4(in.world_pos, 1.0)).xyz);
        float3 mx = normalize(float3(view_dir.z, 0.0, -view_dir.x));
        float3 my = cross(view_dir, mx);
        float2 muv = float2(dot(mx, view_n), dot(my, view_n)) * 0.495 + 0.5;
        float3 matcap = draw.map_scalars.w > 0.5 ? matcap_tex.sample(matcap_samp, muv).rgb
                                                 : float3(mix(0.2, 0.8, muv.y));
        // `base` is the colour, its `map` and the vertex colour, as three.js's
        // `diffuseColor` is by now.
        return float4(apply_fog(tone_map(base.rgb * matcap, frame, draw), fog_depth(in.world_pos, in.view_index, frame), frame),
                      base.a);
    }

    if (draw.object.z == 1u) {
        // three.js ShadowMaterial: `vec4(color, opacity · (1 − getShadowMask()))`,
        // the product of every casting light's shadow on a receiving mesh.
        float mask = 1.0;
        if (draw.object.x == 1u) {
            ShadowMaps maps = { shadow_map, spot_map, point_map, shadow_samp };
            for (uint r = 0u; r < frame.shadow_info.x; ++r) {
                mask *= shadow_at(frame, int(r), maps, in.world_pos, n);
            }
        }
        return float4(apply_fog(tone_map(draw.base_color.rgb, frame, draw), fog_depth(in.world_pos, in.view_index, frame), frame),
                      draw.base_color.a * (1.0 - mask));
    }

    // Emissive is its own channel and applies to lit and unlit alike: a phone
    // screen emits its picture rather than reflecting it, and that is the case
    // this slot exists for.
    float3 emissive = draw.emissive.rgb;
    if (draw.maps.x == 1u) {
        emissive *= emissive_map.sample(emissive_samp, map_uv_sets(draw, MAP_EMISSIVE, in.uv, in.uv12, in.uv3)).rgb;
    }

    bool lit_kind = kind == KIND_LAMBERT || kind == KIND_PHONG || kind == KIND_STANDARD
                 || kind == KIND_PHYSICAL || kind == KIND_TOON;
    float3 color;
    if (lit_kind) {
        // three.js `nonPerturbedNormal`: the clearcoat's normal and the one the
        // anisotropy frame is built about.
        const float3 n_flat = n;
        if (draw.maps.y == 1u) {
            float2 nuv = map_uv_sets(draw, MAP_NORMAL, in.uv, in.uv12, in.uv3);
            n = perturb_normal(n, in.world_pos, nuv,
                               normal_map.sample(normal_samp, nuv).rgb,
                               float2(draw.map_params.x, draw.planet[4].x), in.tangent);
        } else if (draw.extra.z == 1u) {
            n = bump_normal(n, in.world_pos, in.uv, in.uv12, in.uv3, front_facing ? 1.0 : -1.0,
                            draw, bump_map, bump_samp);
        }
        float roughness = draw.pbr.x;
        float metalness = draw.pbr.y;
        if (draw.maps.z == 1u) {
            // glTF packing: roughness in green, metalness in blue, both as
            // multipliers on the material's scalars.
            float3 mr = mr_map.sample(mr_samp, map_uv_sets(draw, MAP_MR, in.uv, in.uv12, in.uv3)).rgb;
            roughness *= mr.g;
            metalness *= mr.b;
        }
        float ao = 1.0;
        if (draw.maps.w == 1u) {
            ao = mix(1.0, ao_map.sample(ao_samp, map_uv_sets(draw, MAP_AO, in.uv, in.uv12, in.uv3)).r, draw.map_params.y);
        }
        bool pbr = kind == KIND_STANDARD || kind == KIND_PHYSICAL;
        bool physical = kind == KIND_PHYSICAL;

        Surface s;
        s.n = n;
        s.v = normalize(frame.camera_pos[in.view_index].xyz - in.world_pos);
        s.albedo = base.rgb;
        s.specular = draw.specular.rgb;
        s.shininess = draw.specular.w;
        s.metalness = metalness;
        s.kind = kind;
        s.toon_gradient = draw.pbr.w;
        s.dndx = dfdx(n);
        s.dndy = dfdy(n);
        s.light_map = draw.extra.y == 1u
            ? light_map.sample(light_samp, map_uv_sets(draw, MAP_LIGHT, in.uv, in.uv12, in.uv3)).rgb * draw.map_scalars.x
            : float3(0.0);
        s.specular_strength = draw.extra.w == 1u
            ? specular_map.sample(specular_samp, map_uv_sets(draw, MAP_SPECULAR, in.uv, in.uv12, in.uv3)).r
            : 1.0;

        // three.js `lights_physical_fragment`: `max(roughness, 0.0525)` plus
        // `geometryRoughness`, the largest screen-space change of any
        // component of the view-space unperturbed normal; or, with specular
        // antialiasing on, the shading normal's variance folded into alpha.
        float3 n_view_flat = (frame.view[in.view_index] * float4(n_flat, 0.0)).xyz;
        float3 n_dxy = max(abs(dfdx(n_view_flat)), abs(dfdy(n_view_flat)));
        float geometry_roughness = max(max(n_dxy.x, n_dxy.y), n_dxy.z);
        bool specular_aa = draw.phys_flags.y == 1u;
        s.roughness_env = max(roughness, 0.0525);
        s.roughness = specular_aa ? specular_aa_roughness(n, s.roughness_env)
                                  : min(s.roughness_env + geometry_roughness, 1.0);
        s.alpha = max(s.roughness * s.roughness, 0.0016);

        // The specular lobe: Standard's F0 0.04 and F90 1; Physical's from
        // `ior`, `specularIntensity` and `specularColor` and their maps.
        s.f0 = mix(float3(0.04), base.rgb, metalness);
        s.f90 = 1.0;
        s.irid = 0.0;
        s.irid_fresnel = float3(0.0);
        s.aniso = -1.0;
        s.alpha_t = s.alpha;
        s.at = float3(0.0);
        s.ab = float3(0.0);
        s.sheen_color = float3(0.0);
        s.sheen_roughness = 1.0;
        s.clearcoat = 0.0;
        s.cc_roughness = 0.0;
        s.cc_n = n_flat;
        if (physical) {
            float spec_intensity = draw.physical[0].y * phys_texel(phys, MAP_SPECULAR_INTENSITY).a;
            float3 spec_tint = draw.physical[1].rgb * phys_texel(phys, MAP_SPECULAR_COLOR).rgb;
            float ior = draw.physical[0].x;
            float r0 = (ior - 1.0) / (ior + 1.0);
            s.f0 = mix(min(float3(r0 * r0) * spec_tint, float3(1.0)) * spec_intensity, base.rgb, metalness);
            s.f90 = mix(spec_intensity, 1.0, metalness);

            // Iridescence: the thin film's Fresnel at the view angle over the
            // base's reflectance; a film of 0 nm is none.
            float4 irid_p = draw.physical[3];
            if (irid_p.x > 0.0) {
                float irid = irid_p.x * phys_texel(phys, MAP_IRIDESCENCE).r;
                float film = has_phys(draw, MAP_IRIDESCENCE_THICKNESS)
                    ? (irid_p.w - irid_p.z) * phys_texel(phys, MAP_IRIDESCENCE_THICKNESS).g + irid_p.z
                    : irid_p.w;
                irid = film == 0.0 ? 0.0 : saturate(irid);
                if (irid > 0.0) {
                    s.irid = irid;
                    s.irid_fresnel = eval_iridescence(1.0, irid_p.y, saturate(dot(n, s.v)), film, s.f0);
                }
            }

            // Anisotropy: `anisotropy · (cos, sin)(anisotropyRotation)`, turned
            // by the map's direction and scaled by its strength, in
            // `getTangentFrame`'s frame, flipped with a back face.
            float4 an_p = draw.physical[4];
            if (an_p.x > 0.0) {
                TangentPair f = tbn_frame(in.tangent, in.normal, three_tangent_frame(in.world_pos, n_flat, in.uv));
                float3 t = front_facing ? f.t : -f.t;
                float3 b = front_facing ? f.b : -f.b;
                float2 av = an_p.x * float2(cos(an_p.y), sin(an_p.y));
                if (has_phys(draw, MAP_ANISOTROPY)) {
                    float3 polar = phys_texel(phys, MAP_ANISOTROPY).rgb;
                    av = float2x2(float2(av.x, av.y), float2(-av.y, av.x))
                       * normalize(2.0 * polar.rg - 1.0) * polar.b;
                }
                float a = length(av);
                if (a == 0.0) {
                    av = float2(1.0, 0.0);
                } else {
                    av /= a;
                    a = saturate(a);
                }
                s.aniso = a;
                s.alpha_t = mix(s.alpha, 1.0, a * a);
                s.at = t * av.x + b * av.y;
                s.ab = b * av.x - t * av.y;
            }

            // Sheen: `sheenColor × sheen` and its map; `sheenRoughness`
            // clamped to [0.07, 1] before its map scales it.
            float4 sheen_p = draw.physical[2];
            if (draw.physical[1].w > 0.0) {
                s.sheen_color = sheen_p.rgb * draw.physical[1].w * phys_texel(phys, MAP_SHEEN_COLOR).rgb;
                s.sheen_roughness = clamp(sheen_p.w, 0.07, 1.0) * phys_texel(phys, MAP_SHEEN_ROUGHNESS).a;
            }

            // Clearcoat: its maps, the unperturbed normal or its own normal map
            // (scaled by `clearcoatNormalScale`), and the base's roughness rule.
            if (draw.physical[0].z > 0.0) {
                s.clearcoat = saturate(draw.physical[0].z * phys_texel(phys, MAP_CLEARCOAT).x);
                float ccr = draw.physical[0].w * phys_texel(phys, MAP_CLEARCOAT_ROUGHNESS).y;
                if (has_phys(draw, MAP_CLEARCOAT_NORMAL)) {
                    TangentPair f = tbn_frame(in.tangent, in.normal, three_tangent_frame(in.world_pos, n_flat, in.uv));
                    float3 t = front_facing ? f.t : -f.t;
                    float3 b = front_facing ? f.b : -f.b;
                    float3 m = phys_texel(phys, MAP_CLEARCOAT_NORMAL).xyz * 2.0 - 1.0;
                    m.xy *= draw.physical[4].zw;
                    s.cc_n = normalize(t * m.x + b * m.y + n_flat * m.z);
                }
                s.cc_roughness = specular_aa ? specular_aa_roughness(s.cc_n, max(ccr, 0.0525))
                                             : min(max(ccr, 0.0525) + geometry_roughness, 1.0);
            }
        }

        Shaded shaded = shade(s, in.world_pos, frame, ao, shadow_map, spot_map, point_map,
                              shadow_samp, draw.object.x == 1u, ltc, env_atlas_samp, matcap_tex, matcap_samp,
                              draw);
        color = shaded.lit;
        float3 specular = shaded.spec;
        bool has_env = draw.map_params.w > 0.5 && pbr;
        // threers's reflective transparency (`set_reflective_transparency`, off
        // by default): a transparent surface's alpha raised by its specular
        // reflectance — `opacity + (1 − opacity) · reflectance` — so the
        // reflection, which is in front of the surface, does not fade with the
        // alpha that lets the background through. The reflectance is the
        // split-sum total `ibl` uses with an environment, its Fresnel alone
        // without one.
        if (frame.rect_counts.z == 1u && pbr && base.a < 1.0) {
            float2 fab = dfg_approx(s.n, s.v, s.roughness_env);
            float3 refl;
            if (has_env) {
                float3 sc = mix(s.f0, s.irid_fresnel, s.irid);
                float3 fss_ess = sc * fab.x + float3(s.f90 * fab.y);
                float ems = 1.0 - (fab.x + fab.y);
                float3 favg = sc + (float3(1.0) - sc) * 0.047619;
                refl = fss_ess + fss_ess * favg / (float3(1.0) - ems * favg) * ems;
            } else {
                refl = s.f0 * fab.x + float3(s.f90 * fab.y);
            }
            float coverage = saturate(max(max(refl.r, refl.g), refl.b));
            base.a = saturate(base.a + (1.0 - base.a) * coverage);
        }
        if (has_env) {
            float2x3 indirect = ibl(s, env_map, env_samp, ao, draw, env_atlas, env_atlas_samp);
            color += indirect[0];
            specular += indirect[1];
        }
        // three.js `transmission_fragment`: the scene behind, from the
        // transmission capture along the refracted ray, replaces the diffuse
        // light by `transmission`; `transmissionAlpha` scales the alpha.
        float4 trans_p = draw.physical[5];
        if (physical && trans_p.x > 0.0 && draw.phys_flags.w == 1u) {
            // The blended glass modes: the background comes through the
            // blend, so transmission is a share of it — what Fresnel does not
            // reflect, absorbed over `thickness` — per channel, as
            // `shade_main` in `renderer/shader.rs` passes it.
            float t = trans_p.x * phys_texel(phys, MAP_TRANSMISSION).r;
            float thickness = trans_p.y * phys_texel(phys, MAP_THICKNESS).g;
            float2 fab = dfg_approx(s.n, s.v, s.roughness);
            float3 f = s.f0 * fab.x + s.f90 * fab.y;
            float3 through = (float3(1.0) - f) * s.albedo * (1.0 - s.metalness)
                           * volume_attenuation(thickness, draw.physical[6].rgb, trans_p.z);
            glass_t = float3(1.0) - base.a * (float3(1.0) - t * through);
            base.a *= 1.0 - t * (through.r + through.g + through.b) / 3.0;
            color *= 1.0 - t;
        } else if (physical && trans_p.x > 0.0) {
            float t = trans_p.x * phys_texel(phys, MAP_TRANSMISSION).r;
            float thickness = trans_p.y * phys_texel(phys, MAP_THICKNESS).g;
            float4 transmitted = ibl_volume_refraction(s, in.world_pos, s.roughness, draw.physical[0].x,
                                                       thickness, trans_p.w, draw.physical[6].rgb, trans_p.z,
                                                       frame, draw, in.view_index, transmission_tex,
                                                       transmission_samp);
            base.a *= mix(1.0, transmitted.a, t);
            color = mix(color, transmitted.rgb, t);
        }
        color += specular;
        // A planet's night lights: the emissive faded out on the side its
        // brightest directional light reaches (`emissive_night_side`).
        if (draw.planet[0].x > 0.0 && frame.counts.x > 0u) {
            float3 sun_dir = float3(0.0);
            float best = -1.0;
            for (uint i = 0u; i < frame.counts.x && i < 4u; ++i) {
                float p = dot(frame.dir[i].color.rgb, float3(0.2126, 0.7152, 0.0722));
                if (p > best) { best = p; sun_dir = -normalize(frame.dir[i].direction.xyz); }
            }
            if (best > 0.0) {
                float night = 1.0 - smoothstep(-0.10, 0.18, dot(normalize(s.n), sun_dir));
                emissive *= mix(1.0, night, clamp(draw.planet[0].x, 0.0, 1.0));
            }
        }
        // three.js `meshphysical` composes `diffuse + specular + emissive`,
        // then the sheen and then the clearcoat over all of it.
        color += emissive;
        if (any(s.sheen_color > 0.0)) {
            float3 sheen = shaded.sheen;
            if (has_env) {
                float3 ibl_irr = env_radiance(s.n, 1.0, env_map, env_samp, draw, env_atlas, env_atlas_samp) * M_PI_F;
                sheen += ibl_irr * s.sheen_color * ibl_sheen_brdf(s.n, s.v, s.sheen_roughness);
            }
            float sheen_max = max(max(s.sheen_color.r, s.sheen_color.g), s.sheen_color.b);
            color = color * (1.0 - 0.157 * sheen_max) + sheen;
        }
        if (s.clearcoat > 0.0) {
            float3 cc = shaded.cc;
            if (has_env) {
                float3 refl = reflect(-s.v, s.cc_n);
                refl = normalize(mix(refl, s.cc_n, s.cc_roughness * s.cc_roughness));
                float2 fab = dfg_approx(s.cc_n, s.v, s.cc_roughness);
                cc += env_radiance(refl, s.cc_roughness, env_map, env_samp, draw, env_atlas, env_atlas_samp)
                    * (float3(0.04) * fab.x + fab.y);
            }
            float3 fcc = f_schlick_f90(float3(0.04), float3(1.0), saturate(dot(s.cc_n, s.v)));
            color = color * (1.0 - s.clearcoat * fcc) + cc * s.clearcoat;
        }
        if (kind == KIND_LAMBERT || kind == KIND_PHONG) {
            color = apply_env_map(color, n, in.world_pos, s.specular_strength, frame, draw,
                                  in.view_index, mat_env, mat_env_samp);
        }
    } else {
        // Unlit: Basic, Line, Points, Sprite, Sky, Mirror, Shader, Atmosphere.
        // three.js `meshbasic_frag`: with a light map the indirect diffuse is
        // its texel × `lightMapIntensity` ÷ π instead of 1.
        float3 indirect = draw.extra.y == 1u
            ? light_map.sample(light_samp, map_uv_sets(draw, MAP_LIGHT, in.uv, in.uv12, in.uv3)).rgb
                  * draw.map_scalars.x * (1.0 / M_PI_F)
            : float3(1.0);
        color = base.rgb * indirect + emissive;
        // three.js Basic reflects per vertex (`vReflect`); here per fragment
        // from the interpolated normal, the same on any flat face.
        if (kind == KIND_BASIC) {
            float spec = draw.extra.w == 1u
                ? specular_map.sample(specular_samp, map_uv_sets(draw, MAP_SPECULAR, in.uv, in.uv12, in.uv3)).r
                : 1.0;
            color = apply_env_map(color, n, in.world_pos, spec, frame, draw, in.view_index,
                                  mat_env, mat_env_samp);
        }
    }

    if (glass_t.x >= 0.0) {
        // Fog in front of the glass veils what it lets through too.
        glass_t *= 1.0 - fog_amount(fog_depth(in.world_pos, in.view_index, frame), frame);
    }
    return float4(apply_fog(tone_map(color, frame, draw), fog_depth(in.world_pos, in.view_index, frame), frame), base.a);
}

// Material-map samplers are a pool (`map_samps`, slots 0–9) that each map
// indexes (`Draw::map_samplers`), the base map's always at 0: one slot per
// distinct filter-and-wrap, where one per map would pass Metal's sixteen.
#define MESH_FRAGMENT_ARGS                                                     \
    FIn in [[stage_in]],                                                       \
    bool front_facing [[front_facing]],                                        \
    constant Frame   &frame        [[buffer(0)]],                              \
    constant Draw    &draw         [[buffer(1)]],                              \
    texture2d<float>  base_map     [[texture(0)]],                             \
    texture2d<float>  emissive_map [[texture(1)]],                             \
    texture2d<float>  normal_map   [[texture(2)]],                             \
    texture2d<float>  mr_map       [[texture(3)]],                             \
    texture2d<float>  ao_map       [[texture(4)]],                             \
    texturecube<float> env_map     [[texture(5)]],                             \
    depth2d_array<float> shadow_map [[texture(6)]],                            \
    depth2d_array<float> spot_map  [[texture(7)]],                             \
    depth2d_array<float> point_map [[texture(8)]],                             \
    texture2d<float>  alpha_map    [[texture(9)]],                             \
    texture2d<float>  light_map    [[texture(10)]],                            \
    texture2d<float>  bump_map     [[texture(11)]],                            \
    texture2d<float>  specular_map [[texture(12)]],                            \
    texturecube<float> mat_env     [[texture(13)]],                            \
    texture2d<float>  matcap_tex   [[texture(14)]],                            \
    texture2d<float>  env_atlas    [[texture(15)]],                            \
    array<texture2d<float>, 12> phys_maps [[texture(16)]],                     \
    texture2d_array<float> ltc     [[texture(28)]],                            \
    texture2d_array<float> transmission_tex [[texture(29)]],                        \
    sampler           transmission_samp [[sampler(14)]],                       \
    array<sampler, 10> map_samps   [[sampler(0)]],                             \
    sampler           env_samp     [[sampler(10)]],                            \
    sampler           shadow_samp  [[sampler(11)]],                            \
    sampler           mat_env_samp [[sampler(12)]],                            \
    sampler           env_atlas_samp [[sampler(13)]]

// The physical maps' texels: white where absent (a flat normal for the
// coat's), each through its own sampler and transform. Sampled here, where
// the textures are an indexable array, in draw-uniform control flow.
#define SAMPLE_PHYSICAL                                                        \
    PhysTexels phys;                                                           \
    for (uint i = 0u; i < PHYS_MAP_COUNT; ++i) {                               \
        uint m = MAP_PHYS0 + i;                                                \
        phys.v[i] = has_phys(draw, m)                                          \
            ? phys_maps[i].sample(map_samps[map_sampler(draw, m)], map_uv_sets(draw, m, in.uv, in.uv12, in.uv3)) \
            : (m == MAP_CLEARCOAT_NORMAL ? float4(0.5, 0.5, 1.0, 1.0) : float4(1.0)); \
    }

#define MS(i) map_samps[map_sampler(draw, i)]

#define MESH_FRAGMENT_CALL                                                     \
    mesh_fragment(in, front_facing, frame, draw, base_map, emissive_map,       \
                  normal_map, mr_map, ao_map, env_map, shadow_map, spot_map,   \
                  point_map, MS(MAP_BASE), env_samp, shadow_samp,              \
                  MS(MAP_EMISSIVE), MS(MAP_NORMAL), MS(MAP_MR), MS(MAP_AO),    \
                  alpha_map, MS(MAP_ALPHA), light_map, MS(MAP_LIGHT),          \
                  bump_map, MS(MAP_BUMP), specular_map, MS(MAP_SPECULAR),      \
                  mat_env, mat_env_samp, matcap_tex, MS(MAP_MATCAP),           \
                  env_atlas, env_atlas_samp, ltc, transmission_tex,      \
                  transmission_samp, phys, glass_t)

fragment float4 fs_mesh(MESH_FRAGMENT_ARGS) {
    SAMPLE_PHYSICAL
    float3 glass_t;
    float4 src = MESH_FRAGMENT_CALL;
    if (glass_t.x >= 0.0) {
        // Blended glass through the hardware's one alpha (a float target):
        // it passes the mean of the tint, and the light divided by alpha
        // comes back at full strength after the blend.
        float a = max(src.a, 1e-3);
        return float4(src.rgb / a, src.a);
    }
    return src;
}

static inline float3 srgb_encode(float3 c) {
    c = saturate(c);
    return select(1.055 * pow(c, float3(1.0 / 2.4)) - 0.055, c * 12.92, c <= float3(0.0031308));
}

static inline float3 srgb_decode(float3 c) {
    c = saturate(c);
    return select(pow((c + 0.055) / 1.055, float3(2.4)), c / 12.92, c <= float3(0.04045));
}

/// Alpha blending as three.js's default `WebGLRenderer` does it: into the
/// canvas's 8-bit framebuffer, which holds sRGB-*encoded* bytes, so
/// `NormalBlending` (`SRC_ALPHA, ONE_MINUS_SRC_ALPHA`; alpha `ONE,
/// ONE_MINUS_SRC_ALPHA`) mixes encoded values, not light. An sRGB attachment
/// would blend in linear light instead, so the pipelines for blended draws
/// into one read the destination (programmable blending — it arrives
/// decoded), blend the encodings here, and write the result back with
/// fixed-function blending off. Per sample under MSAA, which is what the
/// framebuffer read makes the stage. Float targets blend in linear in
/// three.js too (a render target's output is linear) and keep the hardware
/// blend.
fragment float4 fs_mesh_encoded_blend(MESH_FRAGMENT_ARGS, float4 dst [[color(0)]]) {
    SAMPLE_PHYSICAL
    float3 glass_t;
    float4 src = MESH_FRAGMENT_CALL;
    if (glass_t.x >= 0.0) {
        // Blended glass: what is behind times its transmittance, per
        // channel, then its light — `behind · T + L` on the encoded values,
        // where `T`'s factor is its encoding (a power law to within sRGB's
        // toe). The `Glass` mode's two draws on the wgpu path, in one here.
        float m = (glass_t.r + glass_t.g + glass_t.b) / 3.0;
        float3 e = srgb_encode(src.rgb) + srgb_encode(dst.rgb) * srgb_encode(glass_t);
        return float4(srgb_decode(e), saturate(1.0 - m + dst.a * m));
    }
    float a = saturate(src.a);
    float3 e = srgb_encode(src.rgb) * a + srgb_encode(dst.rgb) * (1.0 - a);
    return float4(srgb_decode(e), a + dst.a * (1.0 - a));
}

// three.js `points_frag`: the map and alpha map at the point's
// `(gl_PointCoord.x, 1 − gl_PointCoord.y)` through each map's transform, the
// vertex colour, `alphaTest`, tone mapping and fog.
static inline float4 point_fragment(FIn in, float2 point_coord, constant Frame &frame,
                                    constant Draw &draw, texture2d<float> base_map,
                                    sampler samp, texture2d<float> alpha_map,
                                    sampler alpha_samp) {
    if (clipped(draw, in.world_pos)) {
        discard_fragment();
    }
    float2 pc = float2(point_coord.x, 1.0 - point_coord.y);
    float4 base = draw.base_color;
    if (draw.flags.y == 1u) {
        base *= base_map.sample(samp, map_uv(draw, MAP_BASE, pc));
    }
    if (draw.extra.x == 1u) {
        base.a *= alpha_map.sample(alpha_samp, map_uv(draw, MAP_ALPHA, pc)).g;
    }
    base *= in.color;
    if (base.a < draw.pbr.z) {
        discard_fragment();
    }
    return float4(apply_fog(tone_map(base.rgb, frame, draw), fog_depth(in.world_pos, in.view_index, frame), frame), base.a);
}

#define POINT_FRAGMENT_ARGS                                                    \
    FIn in [[stage_in]],                                                       \
    float2 point_coord [[point_coord]],                                        \
    constant Frame   &frame     [[buffer(0)]],                                 \
    constant Draw    &draw      [[buffer(1)]],                                 \
    texture2d<float>  base_map  [[texture(0)]],                                \
    texture2d<float>  alpha_map [[texture(9)]],                                \
    array<sampler, 10> map_samps [[sampler(0)]]

fragment float4 fs_point(POINT_FRAGMENT_ARGS) {
    return point_fragment(in, point_coord, frame, draw, base_map, MS(MAP_BASE), alpha_map, MS(MAP_ALPHA));
}

/// `fs_mesh_encoded_blend` for points: blended in the encoded values.
fragment float4 fs_point_encoded_blend(POINT_FRAGMENT_ARGS, float4 dst [[color(0)]]) {
    float4 src = point_fragment(in, point_coord, frame, draw, base_map, MS(MAP_BASE), alpha_map, MS(MAP_ALPHA));
    float a = saturate(src.a);
    float3 e = srgb_encode(src.rgb) * a + srgb_encode(dst.rgb) * (1.0 - a);
    return float4(srgb_decode(e), a + dst.a * (1.0 - a));
}

/// `AdditiveBlending` (`SrcAlpha, One`) on the encoded values, as wgpu
/// blends an 8-bit sRGB target: the light adds up in what is stored, and
/// saturates where it would on the canvas.
fragment float4 fs_point_encoded_add(POINT_FRAGMENT_ARGS, float4 dst [[color(0)]]) {
    float4 src = point_fragment(in, point_coord, frame, draw, base_map, MS(MAP_BASE), alpha_map, MS(MAP_ALPHA));
    float a = saturate(src.a);
    float3 e = srgb_encode(dst.rgb) + srgb_encode(src.rgb) * a;
    return float4(srgb_decode(e), saturate(dst.a + a));
}

fragment float4 fs_mesh_encoded_add(MESH_FRAGMENT_ARGS, float4 dst [[color(0)]]) {
    SAMPLE_PHYSICAL
    float3 glass_t;
    float4 src = MESH_FRAGMENT_CALL;
    float a = saturate(src.a);
    float3 e = srgb_encode(dst.rgb) + srgb_encode(src.rgb) * a;
    return float4(srgb_decode(e), saturate(dst.a + a));
}

// ------------------------------------------------ order-independent glass

// Weighted-blended order-independent transparency (McGuire and Bavoil, with
// McGuire and Mara's coloured transmission), as `fs_oit` in
// `renderer/shader.rs`: shaded as `fs_mesh` shades, the light added up
// weighted by depth and coverage, the transmittance multiplied down.
struct OitOut {
    float4 accum  [[color(0)]];
    float4 reveal [[color(1)]];
};

fragment OitOut fs_oit_accum(MESH_FRAGMENT_ARGS) {
    SAMPLE_PHYSICAL
    float3 glass_t;
    float4 src = MESH_FRAGMENT_CALL;
    float alpha = saturate(src.a);
    float3 light = src.rgb;
    float3 through = glass_t;
    if (through.x < 0.0) {
        // Not glass: straight colour and alpha.
        light = src.rgb * alpha;
        through = float3(1.0 - alpha);
    }
    // Nearer fragments weigh more; floored above zero so clear glass, which
    // blocks almost nothing, still carries its highlight.
    float a = max(alpha, 1e-3);
    float z = max(in.view_dist, 1e-3);
    float w = a * clamp(10.0 / (1e-5 + pow(z / 60.0, 3.0) + pow(z / 300.0, 6.0)), 1e-2, 3e3);
    OitOut o;
    o.accum = float4(light * w, a * w);
    o.reveal = float4(float3(1.0) - through, alpha);
    return o;
}

vertex float4 vs_oit_fullscreen(uint vid [[vertex_id]]) {
    float2 p = float2(vid == 1u ? 3.0 : -1.0, vid == 2u ? 3.0 : -1.0);
    return float4(p, 0.0, 1.0);
}

// The composite's first half: what is behind times the layers' product of
// transmittance, per channel.
fragment float4 fs_oit_tint(float4 pos [[position]],
                            texture2d<float> accum [[texture(0)]],
                            texture2d<float> reveal [[texture(1)]]) {
    uint2 p = uint2(pos.xy);
    if (accum.read(p).a <= 0.0) {
        discard_fragment();
    }
    return float4(reveal.read(p).rgb, 1.0);
}

// Its second half: the layers' weighted mean light, scaled by how much of the
// pixel they cover.
fragment float4 fs_oit_light(float4 pos [[position]],
                             texture2d<float> accum [[texture(0)]],
                             texture2d<float> reveal [[texture(1)]]) {
    uint2 p = uint2(pos.xy);
    float4 a = accum.read(p);
    if (a.a <= 0.0) {
        discard_fragment();
    }
    float cover = 1.0 - reveal.read(p).a;
    return float4(a.rgb / max(a.a, 1e-5) * cover, cover);
}

// ------------------------------------------------------------------- fur

// Shell fur (`crate::fur`): the WGSL shader's port, reading the same
// sixteen float4 slots (`FurMaterial::data`). Instance `iid` is shell
// `iid / shells` of the fur's length; see `src/fur/mod.rs` for the slots.
struct FurData {
    float4 d[16];
};

static inline float3 fur_air_hash3(int3 p) {
    uint3 v = as_type<uint3>(p) * 1664525u + 1013904223u;
    v.x += v.y * v.z;
    v.y += v.z * v.x;
    v.z += v.x * v.y;
    v = v ^ (v >> 16u);
    v.x += v.y * v.z;
    v.y += v.z * v.x;
    v.z += v.x * v.y;
    return float3(v >> 8u) * (1.0 / 16777216.0);
}

// The air, as `crate::fur`'s WGSL has it (`fur_noise3`, `fur_mean_pull`,
// `fur_turbulence`, `fur_flutter_noise`): pulls per unit of strand length.
static inline float3 fur_noise3(float3 p) {
    float3 i = floor(p);
    float3 f = p - i;
    float3 u = f * f * (3.0 - 2.0 * f);
    int3 b = int3(i);
    float3 x00 = mix(fur_air_hash3(b), fur_air_hash3(b + int3(1, 0, 0)), u.x);
    float3 x10 = mix(fur_air_hash3(b + int3(0, 1, 0)), fur_air_hash3(b + int3(1, 1, 0)), u.x);
    float3 x01 = mix(fur_air_hash3(b + int3(0, 0, 1)), fur_air_hash3(b + int3(1, 0, 1)), u.x);
    float3 x11 = mix(fur_air_hash3(b + int3(0, 1, 1)), fur_air_hash3(b + int3(1, 1, 1)), u.x);
    float3 v = mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
    return v * 2.0 - 1.0;
}

static inline float3 fur_mean_pull(constant FurData &fur) {
    if (fur.d[9].w > 0.5) {
        return fur.d[9].xyz;
    }
    float3 w = fur.d[6].xyz;
    return fur.d[1].xyz + w * (fur.d[12].x * length(w));
}

static inline float3 fur_turbulence(constant FurData &fur, float3 p) {
    float3 w = fur.d[6].xyz;
    float wl = length(w);
    if (wl <= 0.0 || fur.d[12].y <= 0.0) {
        return float3(0.0);
    }
    float eddy = max(wl / max(fur.d[6].w, 1e-3), 0.05);
    float3 n = fur_noise3((p - w * fur.d[5].z) / eddy);
    return n * (2.0 * fur.d[12].x * fur.d[12].y * wl * wl);
}

static inline float3 fur_brush(constant FurData &fur, float3 p) {
    float4 b = fur.d[13];
    if (b.w <= 0.0) {
        return float3(0.0);
    }
    float3 off = p - b.xyz;
    float d = length(off);
    if (d >= b.w) {
        return float3(0.0);
    }
    float f = 1.0 - d / b.w;
    float w = f * f * (3.0 - 2.0 * f);
    return (fur.d[14].xyz + off / max(d, 1e-4) * fur.d[14].w) * w;
}

static inline float3 fur_flutter_noise(constant FurData &fur, float r) {
    float wl = length(fur.d[6].xyz);
    float amp = fur.d[8].z * min(wl, 1.0);
    if (amp <= 0.0) {
        return float3(0.0);
    }
    float rate = 2.0 + 4.0 * wl;
    return fur_noise3(float3(r * 97.0, fur.d[5].z * rate, r * 31.0)) * amp;
}

/// Strand hair (`crate::fur::strands`, placement 2): the ribbon vertex stage,
/// `HAIR_VERTEX_WGSL`'s port. `uv` is (side, height), the normal the grown
/// direction, the colour's alpha the strand's own random, and the tangent
/// (`uv_sets` slot 2) the root's normal and the strand's length.
static VOut hair_vertex(VOut out, Vertex v, float4x4 model, float4 root, float3 lag,
                        constant Frame &frame, constant FurData &fur) {
    float s = v.uv.y;
    float side = v.uv.x * 2.0 - 1.0;
    float3 rn4 = (model * float4(root.xyz, 0.0)).xyz;
    float scale = max(length(rn4), 1e-6);
    float3 root_n = rn4 / scale;
    float len = root.w * scale;
    float r = v.alpha;
    float3 across0 = abs(root_n.y) > 0.9 ? normalize(cross(root_n, float3(1.0, 0.0, 0.0)))
                                         : normalize(cross(root_n, float3(0.0, 1.0, 0.0)));
    float3 base = out.world_pos - root_n * (len * s);
    float3 pull = fur_mean_pull(fur) + fur_turbulence(fur, base) + fur_flutter_noise(fur, r) * 0.3
        + fur_brush(fur, out.world_pos) + (model * float4(lag, 0.0)).xyz;
    float3 walk = float3(0.0);
    for (int k = 0; k < 6; ++k) {
        float3 d = root_n + pull * (2.0 * s * (float(k) + 0.5) / 6.0);
        walk += d / max(length(d), 1e-6);
    }
    float3 p = out.world_pos - root_n * (len * s) + walk * (len * s / 6.0);
    float3 b = root_n + pull * (2.0 * s);
    float3 bent = length(b) > 1e-4 ? b / length(b) : normalize(pull + root_n * 1e-3);
    float3 tt_dir = normalize(out.normal) - root_n + bent;
    float3 t_dir = length(tt_dir) > 1e-4 ? tt_dir / length(tt_dir) : bent;
    float3 to_eye = normalize(frame.camera_pos[0].xyz - p);
    float3 across = cross(t_dir, to_eye);
    if (length(across) < 1e-5) {
        across = across0;
    }
    across = normalize(across);
    // At least 1.5 pixels wide, as the WGSL draws it; the share its true
    // width fills goes to the fragment in `color.a`, the place across it in
    // `uv12.w`.
    float width = fur.d[0].w * mix(1.0, fur.d[1].w, s);
    float4x4 vm = frame.view[0];
    float3 up = float3(vm[0][1], vm[1][1], vm[2][1]);
    float4 ca = frame.view_proj[0] * float4(p, 1.0);
    float4 ce = frame.view_proj[0] * float4(p + up, 1.0);
    float px_per_unit = (ca.w > 1e-4 && ce.w > 1e-4)
        ? abs(ce.y / ce.w - ca.y / ca.w) * frame.viewport.y * 0.5 : 1e6;
    float width_px = width * px_per_unit;
    float drawn = max(width_px, 1.5) / max(px_per_unit, 1e-6);
    out.world_pos = p + across * (side * drawn * 0.5);
    out.normal = root_n;
    out.position = frame.view_proj[0] * float4(out.world_pos, 1.0);
    out.view_dist = length(frame.camera_pos[0].xyz - out.world_pos);
    out.tangent = float4(t_dir, 1.0);
    out.uv3 = float2(s, 1.0);
    out.color = float4(out.color.rgb, clamp(width_px / max(width_px, 1.5), 0.0, 1.0));
    out.uv12 = float4(float3(v.position), side);
    return out;
}

// `fur_lod_shells` in `crate::fur`'s WGSL: two shells per pixel of the fur's
// length on screen, at the near side of its bounding sphere (`d[11]`; a
// negative radius for none), at least four.
static float fur_lod_shells(constant FurData &fur, constant Frame &frame, constant Draw &draw,
                            float shells) {
    float4 b = fur.d[11];
    if (b.w < 0.0) {
        return shells;
    }
    float4x4 m = draw.model;
    float scale = max(length(m[0].xyz), max(length(m[1].xyz), length(m[2].xyz)));
    float3 c = (m * float4(b.xyz, 1.0)).xyz;
    float3 to_cam = frame.camera_pos[0].xyz - c;
    float d = length(to_cam);
    float3 near = c + to_cam / max(d, 1e-6) * min(b.w * scale, d * 0.9);
    float4x4 v = frame.view[0];
    float3 up = float3(v[0][1], v[1][1], v[2][1]);
    float4 a = frame.view_proj[0] * float4(near, 1.0);
    float4 e = frame.view_proj[0] * float4(near + up, 1.0);
    if (a.w <= 1e-4 || e.w <= 1e-4) {
        return shells;
    }
    float px_per_unit = abs(e.y / e.w - a.y / a.w) * frame.viewport.y * 0.5;
    return clamp(ceil(2.0 * fur.d[0].y * px_per_unit), min(4.0, shells), shells);
}

vertex VOut vs_fur(uint vid [[vertex_id]],
                   uint iid [[instance_id]],
                   device const Vertex   *verts      [[buffer(0)]],
                   constant Frame        &frame      [[buffer(1)]],
                   constant Draw         &draw       [[buffer(2)]],
                   device const float4x4 *instances  [[buffer(3)]],
                   device const float4   *morph_data [[buffer(6)]],
                   constant MorphInfo    &morph      [[buffer(7)]],
                   device const float4   *uv_sets    [[buffer(8)]],
                   constant FurData      &fur        [[buffer(9)]]) {
    float4x4 model = model_matrix(draw, instances, iid);
    Vertex v = apply_morph(verts[vid], vid, iid, morph, morph_data, instances);
    VOut out = transform(v, model, normal_basis(draw, instances, iid), frame, draw, 0u);
    if (fur.d[8].x > 1.5) {
        float4 root = (draw.phys_flags.z & 2u) != 0u ? uv_sets[3u * vid + 2u] : float4(0.0, 1.0, 0.0, 0.0);
        // On a skinned mesh, each strand's own inertia, from uv1 and uv2.
        float3 lag = fur.d[8].w > 0.5 && (draw.phys_flags.z & 1u) != 0u ? uv_sets[3u * vid].xyz : float3(0.0);
        return hair_vertex(out, v, model, root, lag, frame, fur);
    }
    float shells = fur_lod_shells(fur, frame, draw, max(fur.d[0].x, 1.0));
    // A shell beyond what the fur's size on screen needs: nothing to draw.
    if (float(iid) > shells) {
        out.position = float4(0.0, 0.0, 2.0, 1.0);
        return out;
    }
    float h = float(iid) / shells;
    float len = fur.d[0].y * out.color.a;
    float3 n = normalize(out.normal);
    float3 pull = fur_mean_pull(fur) + fur_turbulence(fur, out.world_pos) + fur_brush(fur, out.world_pos);
    if (fur.d[8].w > 0.5 && (draw.phys_flags.z & 2u) != 0u) {
        pull += (model * float4(uv_sets[3u * vid + 2u].xyz, 0.0)).xyz;
    }
    float3 walk = float3(0.0);
    for (int k = 0; k < 6; ++k) {
        float3 d = n + pull * (2.0 * h * (float(k) + 0.5) / 6.0);
        walk += d / max(length(d), 1e-6);
    }
    out.world_pos += walk * (len * h / 6.0);
    out.position = frame.view_proj[0] * float4(out.world_pos, 1.0);
    out.view_dist = length(frame.camera_pos[0].xyz - out.world_pos);
    float3 along = n + pull * (2.0 * h);
    out.tangent = float4(length(along) > 1e-6 ? normalize(along) : n, 1.0);
    out.uv3 = float2(h, out.color.a);
    // The skin point in object space, for surface placement.
    // The skin point in object space, and one shell's slab of height.
    out.uv12 = float4(float3(v.position), 1.0 / shells);
    return out;
}

static inline float2 fur_hash2(int2 p) {
    uint2 v = as_type<uint2>(p) * 1664525u + 1013904223u;
    v.x += v.y * 1664525u;
    v.y += v.x * 1664525u;
    v = v ^ (v >> 16u);
    v.x += v.y * 1664525u;
    v.y += v.x * 1664525u;
    v = v ^ (v >> 16u);
    return float2(v >> 8u) * (1.0 / 16777216.0);
}

static inline float3 fur_hash3(int3 p) {
    uint3 v = as_type<uint3>(p) * 1664525u + 1013904223u;
    v.x += v.y * v.z;
    v.y += v.z * v.x;
    v.z += v.x * v.y;
    v = v ^ (v >> 16u);
    v.x += v.y * v.z;
    v.y += v.z * v.x;
    v.z += v.x * v.y;
    return float3(v >> 8u) * (1.0 / 16777216.0);
}

// Wrapped in floats, as the WGSL does: exact for whole-number cells, and no
// integer division.
static inline int2 fur_cell_key(float2 cell, float2 n, int salt, int seed) {
    float2 w = cell - n * floor(cell / n);
    return int2(w) + int2(seed * 7919 + salt, seed * 104729 - salt);
}

static inline float2 fur_flutter(constant FurData &fur, float r, float h) {
    return fur_flutter_noise(fur, r).xy * (h * h);
}

// `fur_capsule`, `fur_slab_world`, `fur_world_to` in the WGSL: each strand
// swept across its shell's slab as the line of sight crosses it.
static inline float fur_capsule(float2 o, float2 d) {
    float dd = dot(d, d);
    float t = dd > 1e-12 ? clamp(-dot(o, d) / dd, -0.5, 0.5) : 0.0;
    return length(o + d * t);
}

static inline float2 fur_world_to(float3 step, float3 wx, float3 wy) {
    float a = dot(wx, wx);
    float b = dot(wx, wy);
    float c = dot(wy, wy);
    float det = a * c - b * b;
    if (abs(det) < 1e-20) {
        return float2(0.0);
    }
    float rx = dot(wx, step);
    float ry = dot(wy, step);
    return float2(c * rx - b * ry, a * ry - b * rx) / det;
}

// `fur_reach` and `fur_hit_uv` in `crate::fur`'s WGSL: a strand's furthest
// stray from its root, and the search — own cell first, first hit wins,
// out-of-reach roots and short strands passed over before their clump.
static inline float fur_reach(constant FurData &fur, float h) {
    float curl = 0.3 * h * min(abs(fur.d[4].x), 1.0);
    float flutter = fur.d[8].z * h * h * 1.4143;
    float pull = min(0.95, fur.d[4].y * h * (2.25 * fur.d[5].w + 2.0));
    return curl + flutter + pull + fur.d[0].w + 0.0001;
}

// The samples of this pixel, as offsets from its centre in pixels: the
// pipeline's own pattern (its centre alone when it has one sample).
static inline float2 fur_sample_offset(uint i) {
    return get_num_samples() > 1 ? get_sample_position(i) - 0.5 : float2(0.0);
}

// `fur_mask_uv` in the WGSL: which of the pixel's samples the strands about
// `uv` cover — `jx`, `jy` its steps in cells.
static inline uint fur_mask_uv(constant FurData &fur, float2 uv, float2 jx, float2 jy, float h,
                               float2 slab) {
    int seed = int(fur.d[4].w);
    float2 cells = fur.d[7].xy;
    float2 clumps = fur.d[7].zw;
    float2 q = uv * cells;
    float2 base = floor(q);
    uint n = get_num_samples();
    uint full = (1u << n) - 1u;
    float spread = n > 1 ? 0.4 * (length(jx) + length(jy)) : 0.0;
    float reach = fur_reach(fur, h) + spread + 0.5 * length(slab);
    uint mask = 0u;
    for (int k = 0; k < 9; ++k) {
        float2 cell = base + float2(float((k + 4) % 3 - 1), float((k + 4) / 3 % 3 - 1));
        float2 r = fur_hash2(fur_cell_key(cell, cells, 0, seed));
        float2 root = cell + 0.15 + 0.7 * r;
        if (length(q - root) > reach) {
            continue;
        }
        float2 r2 = fur_hash2(fur_cell_key(cell, cells, 31337, seed));
        float own_len = 1.0 - fur.d[4].z * r2.x;
        if (h > own_len) {
            continue;
        }
        float2 c = root;
        float angle = (fur.d[4].x * h + r2.y) * 6.2831853;
        c += float2(cos(angle), sin(angle)) * (0.3 * h * min(abs(fur.d[4].x), 1.0));
        c += fur_flutter(fur, r.x, h);
        float2 rc = root / cells * clumps;
        float2 cb = floor(rc - 0.5);
        float2 best = float2(0.0);
        float best_d = 1e9;
        for (int j = 0; j <= 1; ++j) {
            for (int i = 0; i <= 1; ++i) {
                float2 kk = cb + float2(float(i), float(j));
                float2 point = kk + fur_hash2(fur_cell_key(kk, clumps, 7, seed));
                float d = dot(point - rc, point - rc);
                if (d < best_d) {
                    best_d = d;
                    best = point;
                }
            }
        }
        float2 pull = (best / clumps * cells - c) * (fur.d[4].y * h);
        float pl = length(pull);
        if (pl > 0.95) {
            pull *= 0.95 / pl;
        }
        c += pull;
        float radius = fur.d[0].w * mix(1.0, fur.d[1].w, h / max(own_len, 1e-3));
        float d = fur_capsule(q - c, slab);
        if (d + spread < radius) {
            mask = full;
        } else if (d - spread < radius) {
            for (uint i = 0; i < n; ++i) {
                float2 o = fur_sample_offset(i);
                if (fur_capsule(q + jx * o.x + jy * o.y - c, slab) < radius) {
                    mask |= 1u << i;
                }
            }
        }
        if (mask == full) {
            return mask;
        }
    }
    return mask;
}

static inline uint fur_mask_surface(constant FurData &fur, float3 p, float3 n, float h,
                                    float3 jx, float3 jy, float3 slab3) {
    int seed = int(fur.d[4].w);
    float3 q = p / fur.d[8].y;
    uint samples = get_num_samples();
    uint full = (1u << samples) - 1u;
    uint mask = 0u;
    float3 base = floor(q);
    float3 helper = abs(n.x) > 0.8 ? float3(0.0, 1.0, 0.0) : float3(1.0, 0.0, 0.0);
    float3 t1 = normalize(cross(n, helper));
    float3 t2 = cross(n, t1);
    float csize = fur.d[5].w;
    float curl_r = 0.3 * h * min(abs(fur.d[4].x), 1.0);
    float pull_r = min(0.95, fur.d[4].y * h * (1.3 * csize + 0.01));
    float reach = curl_r + fur.d[8].z * h * h * 1.4143 + pull_r + fur.d[0].w + 0.0001
        + (samples > 1 ? 0.4 * (length(jx) + length(jy)) / fur.d[8].y : 0.0);
    float2 slab = float2(dot(slab3, t1), dot(slab3, t2));
    reach += 0.5 * length(slab);
    for (int z = -1; z <= 1; ++z) {
        for (int y = -1; y <= 1; ++y) {
            for (int x = -1; x <= 1; ++x) {
                float3 cell = base + float3(float(x), float(y), float(z));
                int3 key = int3(cell) + int3(seed * 7919, seed * 104729, 31);
                float3 r = fur_hash3(key);
                float3 root = cell + r;
                float3 off = root - q;
                float dn = dot(off, n);
                if (abs(dn) > 0.5) {
                    continue;
                }
                float3 r2 = fur_hash3(key + int3(977, 31337, 4099));
                float own_len = 1.0 - fur.d[4].z * r2.x;
                if (h > own_len) {
                    continue;
                }
                if (length(off - n * dn) > reach) {
                    continue;
                }
                // Where the strand is carried from its root at this height.
                float3 s = float3(0.0);
                float angle = (fur.d[4].x * h + r2.y) * 6.2831853;
                s += (t1 * cos(angle) + t2 * sin(angle)) * (0.3 * h * min(abs(fur.d[4].x), 1.0));
                float2 fl = fur_flutter(fur, r2.z, h);
                s += t1 * fl.x + t2 * fl.y;
                float3 cp = (floor(root / csize) + 0.25 + 0.5 * fur_hash3(int3(floor(root / csize)) + 17)) * csize;
                float3 pull = cp - root;
                pull = (pull - n * dot(pull, n)) * (fur.d[4].y * h);
                float pl = length(pull);
                if (pl > 0.95) {
                    pull *= 0.95 / pl;
                }
                s += pull;
                float radius = fur.d[0].w * mix(1.0, fur.d[1].w, h / max(own_len, 1e-3));
                for (uint i = 0; i < samples; ++i) {
                    float2 o = fur_sample_offset(i);
                    float3 at = off - (jx * o.x + jy * o.y) / fur.d[8].y;
                    float3 o2 = at - n * dot(at, n) + s;
                    if (fur_capsule(float2(dot(o2, t1), dot(o2, t2)), slab) < radius) {
                        mask |= 1u << i;
                    }
                }
                if (mask == full) {
                    return mask;
                }
            }
        }
    }
    return mask;
}

static inline float3 fur_kajiya(constant FurData &fur, float3 t, float3 n, float3 v, float3 l,
                                float3 albedo, float h, float spec_exp) {
    float ndl = dot(n, l);
    if (h <= 0.0) {
        return albedo * max(ndl, 0.0);
    }
    float tl = dot(t, l);
    float diffuse = sqrt(max(1.0 - tl * tl, 0.0)) * clamp(ndl * 0.75 + 0.25, 0.0, 1.0);
    float3 ts = normalize(t + n * fur.d[5].y);
    float th = dot(ts, normalize(l + v));
    float spec = pow(sqrt(max(1.0 - th * th, 0.0)), spec_exp) * fur.d[3].w
        * clamp(ndl * 0.5 + 0.5, 0.0, 1.0) * h;
    return albedo * diffuse + float3(spec);
}

// The fur's colour, and the samples of the pixel it covers.
struct FurOut {
    float4 color [[color(0)]];
    uint mask [[sample_mask]];
};

fragment FurOut fs_fur(FIn in [[stage_in]],
                       constant Frame &frame [[buffer(0)]],
                       constant Draw &draw [[buffer(1)]],
                       constant FurData &fur [[buffer(2)]],
                       depth2d_array<float> shadow_map [[texture(6)]],
                       depth2d_array<float> spot_map [[texture(7)]],
                       depth2d_array<float> point_map [[texture(8)]],
                       sampler shadow_samp [[sampler(11)]]) {
    float h = in.uv3.x;
    // As `fs_main` in the WGSL: derivatives first, then which samples the
    // strands (or the hair's true width, `color.a` of its ribbon, across it
    // at `uv12.w`) cover.
    float3 px = dfdx(in.uv12.xyz);
    float3 py = dfdy(in.uv12.xyz);
    float3 fn_raw = cross(px, py);
    float2 jx = dfdx(in.uv * fur.d[7].xy);
    float2 jy = dfdy(in.uv * fur.d[7].xy);
    float3 wx = dfdx(in.world_pos);
    float3 wy = dfdy(in.world_pos);
    // One shell's slab, swept as the line of sight crosses it relative to
    // the leaning strand (`fur_slab_world`).
    float3 slab_w = float3(0.0);
    {
        float3 nn = normalize(in.normal);
        float3 vv = normalize(frame.camera_pos[0].xyz - in.world_pos);
        float3 st = normalize(in.tangent.xyz);
        float vn = dot(vv, nn);
        float sn = max(dot(st, nn), 0.2);
        float3 ray = (vv - nn * vn) / ((vn < 0.0 ? -1.0 : (vn > 0.0 ? 1.0 : 0.0)) * max(abs(vn), 0.2));
        float3 strand = (st - nn * dot(st, nn)) / sn;
        slab_w = (ray - strand) * (fur.d[0].y * in.uv3.y * in.uv12.w);
    }
    float2 slab_m = fur_world_to(slab_w, wx, wy);
    float sx = dfdx(in.uv12.w);
    float sy = dfdy(in.uv12.w);
    float3 dt = fwidth(in.tangent.xyz);
    float spec_exp = fur.d[5].x / (1.0 + fur.d[5].x * dot(dt, dt) * 0.25);
    uint samples = get_num_samples();
    uint mask = (1u << samples) - 1u;
    if (fur.d[8].x > 1.5) {
        mask = 0u;
        for (uint i = 0; i < samples; ++i) {
            float2 o = fur_sample_offset(i);
            if (abs(in.uv12.w + sx * o.x + sy * o.y) < in.color.a) {
                mask |= 1u << i;
            }
        }
    } else if (h > 0.0) {
        if (in.uv3.y <= 0.001) {
            discard_fragment();
        }
        if (fur.d[8].x > 0.5) {
            float fl = length(fn_raw);
            float3 sl = px * slab_m.x + py * slab_m.y;
            float sll = length(sl) / fur.d[8].y;
            sl = sll > 3.0 ? sl * (3.0 / sll) : sl;
            mask = fl > 0.0 ? fur_mask_surface(fur, in.uv12.xyz, fn_raw / fl, h, px, py, sl / fur.d[8].y) : 0u;
        } else {
            float2 sc = jx * slab_m.x + jy * slab_m.y;
            float scl = length(sc);
            sc = scl > 3.0 ? sc * (3.0 / scl) : sc;
            mask = fur_mask_uv(fur, in.uv, jx, jy, h, sc);
        }
    }
    if (mask == 0u) {
        discard_fragment();
    }
    float3 n = normalize(in.normal);
    float3 t = normalize(in.tangent.xyz);
    float3 v = normalize(frame.camera_pos[0].xyz - in.world_pos);
    ShadowMaps maps = { shadow_map, spot_map, point_map, shadow_samp };
    float shadow_cache[16];
    for (uint r = 0u; r < 16u; ++r) {
        shadow_cache[r] = 1.0;
    }
    if (draw.object.x != 0u) {
        uint count = min(frame.shadow_info.x, 16u);
        for (uint r = 0u; r < count; ++r) {
            shadow_cache[r] = shadow_at(frame, int(r), maps, in.world_pos, n);
        }
    }
    float3 tint = mix(fur.d[2].rgb, fur.d[3].rgb, h) * in.color.rgb;
    float ao = mix(1.0 - fur.d[2].w, 1.0, h);
    float3 albedo = tint * ao;
    float3 irr = frame.ambient.rgb;
    for (uint i = 0u; i < frame.counts.w && i < 2u; ++i) {
        constant HemiLight &hl = frame.hemis[i];
        float k = dot(n, normalize(hl.direction.xyz)) * 0.5 + 0.5;
        irr += mix(hl.ground_color.rgb, hl.sky_color.rgb, k);
    }
    float3 col = albedo * irr * (1.0 / M_PI_F);
    for (uint i = 0u; i < frame.counts.x && i < 4u; ++i) {
        DirLight d = frame.dir[i];
        float3 l = -normalize(d.direction.xyz);
        col += d.color.rgb * cached_shadow(shadow_cache, d.color.w) * fur_kajiya(fur, t, n, v, l, albedo, h, spec_exp);
    }
    for (uint i = 0u; i < frame.counts.y && i < 8u; ++i) {
        PointLight p = frame.pts[i];
        float3 to_light = p.position.xyz - in.world_pos;
        float dist = length(to_light);
        float att = punctual_attenuation(dist, p.params.x, p.params.y) * cached_shadow(shadow_cache, p.color.w);
        col += p.color.rgb * att * fur_kajiya(fur, t, n, v, to_light / max(dist, 1e-4), albedo, h, spec_exp);
    }
    for (uint i = 0u; i < frame.counts.z && i < 4u; ++i) {
        SpotLight sp = frame.spots[i];
        float3 to_light = sp.position.xyz - in.world_pos;
        float dist = length(to_light);
        float3 l = to_light / max(dist, 1e-4);
        float cos_angle = dot(-l, normalize(sp.direction.xyz));
        float cone = cos_angle > sp.params.z ? smoothstep(sp.params.z, sp.params.w, cos_angle) : 0.0;
        float att = punctual_attenuation(dist, sp.params.x, sp.params.y) * cone
            * cached_shadow(shadow_cache, sp.color.w);
        col += sp.color.rgb * att * fur_kajiya(fur, t, n, v, l, albedo, h, spec_exp);
    }
    return {float4(apply_fog(tone_map(col, frame, draw), fog_depth(in.world_pos, in.view_index, frame), frame), 1.0), mask};
}