1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
//! wgpu scene renderer: pipelines, resource caches, shadows, and post-processing.
//!
//! Walks a [`Scene`](crate::Scene), batches draw calls by material and topology,
//! and writes to a swapchain view or [`super::RenderTarget`]. Post-fx passes
//! share WGSL in [`super::shader`] (`POSTFX_SHADER`, effect kinds 0–30).
use bytemuck::{Pod, Zeroable};
use std::collections::HashMap;
use std::sync::Arc;
use super::gpu_mesh::{geom_cache_key, GpuMesh};
use super::gpu_texture::{
cube_cache_key, tex_cache_key, GpuCubeTexture, GpuTexture, MipGenerator, TexCacheKey,
};
use super::shader::{
MAX_DIR_LIGHTS, MAX_HEMI_LIGHTS, MAX_POINT_LIGHTS, MAX_RECT_LIGHTS, MAX_SPOT_LIGHTS,
SHADER_SOURCE,
};
use crate::cameras::Camera;
use crate::core::{BufferGeometry, ObjectKind};
use crate::lights::Light;
use crate::materials::{Material, MaterialKind, MaterialTextureSlots};
use crate::math::{Matrix3, Matrix4, Vector3};
use crate::scene::Scene;
use crate::textures::{CubeTexture, Texture, TextureFormat};
fn rt_sample_format(format: wgpu::TextureFormat) -> wgpu::TextureFormat {
if format == wgpu::TextureFormat::Rgba16Float {
format
} else {
format.add_srgb_suffix()
}
}
// ---------- GPU layout types ----------
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct DirLightGpu {
direction: [f32; 4],
color: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct PointLightGpu {
position: [f32; 4],
color: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct SpotLightGpu {
position: [f32; 4],
direction: [f32; 4],
color: [f32; 4],
params: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct HemiLightGpu {
sky_color: [f32; 4],
ground_color: [f32; 4],
direction: [f32; 4],
}
/// A rectangular area light. `right`/`up` are **half-extent** vectors in world
/// space, so the four corners are `position ± right ± up` and the emitting face
/// normal is `normalize(cross(right, up))`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct RectLightGpu {
position: [f32; 4],
color: [f32; 4],
right: [f32; 4],
up: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct FrameUniforms {
view: [f32; 16],
projection: [f32; 16],
view_proj: [f32; 16],
shadow_vp: [f32; 16],
spot_shadow_vp: [f32; 16],
cube_face_vp: [f32; 16],
camera_position: [f32; 4],
ambient: [f32; 4],
light_counts: [u32; 4],
/// x: dir shadow on, y: dir bias, z: spot shadow on, w: spot bias
shadow_params: [f32; 4],
/// xyz: point shadow caster world position, w: radius (0 = disabled)
point_shadow_pos: [f32; 4],
/// x: tone-mapping mode (0 none, 1 linear, 2 ACES), y: exposure, z: IBL on,
/// w: linear framebuffer (1 = HalfFloat RT, skip sRGB encode on write)
tone_mapping_exposure: [f32; 4],
/// Fog color rgb + a (a unused). Multiplied with the mix factor in shader.
fog_color: [f32; 4],
/// x: near (linear), y: far (linear), z: density (exp2), w: mode (0/1/2)
fog_params: [f32; 4],
/// x: viewport width (pixels), y: viewport height (pixels), zw: reserved.
viewport_size: [f32; 4],
/// CubeUV PMREM: x/y texel size, z max mip, w = 1 when CubeUV active.
env_map_params: [f32; 4],
dir_lights: [DirLightGpu; MAX_DIR_LIGHTS],
point_lights: [PointLightGpu; MAX_POINT_LIGHTS],
spot_lights: [SpotLightGpu; MAX_SPOT_LIGHTS],
hemi_lights: [HemiLightGpu; MAX_HEMI_LIGHTS],
rect_lights: [RectLightGpu; MAX_RECT_LIGHTS],
/// x: rect-area light count. yzw reserved. `light_counts` was already full.
light_counts2: [u32; 4],
/// One texel of each shadow map, as a fraction of the map: x directional,
/// y spot. The PCF kernels size themselves from this rather than from a
/// constant compiled into the shader — the map is allocated on the Rust
/// side and can change, and a WGSL constant cannot be told.
shadow_texel: [f32; 4],
}
impl Default for FrameUniforms {
fn default() -> Self {
Self {
view: [0.0; 16],
projection: [0.0; 16],
view_proj: [0.0; 16],
shadow_vp: [0.0; 16],
spot_shadow_vp: [0.0; 16],
cube_face_vp: [0.0; 16],
camera_position: [0.0; 4],
ambient: [0.0; 4],
light_counts: [0; 4],
shadow_params: [0.0; 4],
point_shadow_pos: [0.0; 4],
// Default: NoToneMapping, exposure 1.0 — matches three.js default.
tone_mapping_exposure: [0.0, 1.0, 0.0, 0.0],
fog_color: [1.0, 1.0, 1.0, 1.0],
fog_params: [1.0, 1000.0, 0.0, 0.0],
viewport_size: [1.0, 1.0, 0.0, 0.0],
env_map_params: [0.0; 4],
dir_lights: [DirLightGpu::default(); MAX_DIR_LIGHTS],
point_lights: [PointLightGpu::default(); MAX_POINT_LIGHTS],
spot_lights: [SpotLightGpu::default(); MAX_SPOT_LIGHTS],
hemi_lights: [HemiLightGpu::default(); MAX_HEMI_LIGHTS],
rect_lights: [RectLightGpu::default(); MAX_RECT_LIGHTS],
light_counts2: [0; 4],
shadow_texel: [0.0; 4],
}
}
}
/// Build the environment `@group(3)` bind group. The layout (13 bindings: env
/// cube + samplers, three shadow maps + comparison samplers, the CubeUV atlas,
/// and the screen-space glass color/depth/back-depth) is fixed here in one place,
/// so the four construction sites (default, shadow-dummies, per-frame, glass)
/// just pass the 13 views/samplers in binding order and a new binding is added
/// once. Texture vs. sampler wrapping is encoded by the arg position.
macro_rules! env_bind_group {
($device:expr, $bgl:expr, $label:expr,
$t0:expr, $s1:expr, $t2:expr, $s3:expr, $t4:expr, $s5:expr,
$t6:expr, $s7:expr, $t8:expr, $t9:expr, $s10:expr, $t11:expr, $t12:expr $(,)?) => {
$device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some($label),
layout: $bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView($t0),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler($s1),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView($t2),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler($s3),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView($t4),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::Sampler($s5),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView($t6),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler($s7),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView($t8),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::TextureView($t9),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::Sampler($s10),
},
wgpu::BindGroupEntry {
binding: 11,
resource: wgpu::BindingResource::TextureView($t11),
},
wgpu::BindGroupEntry {
binding: 12,
resource: wgpu::BindingResource::TextureView($t12),
},
],
})
};
}
/// Uniform for the TAA resolve pass — see `TAA_SHADER`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct TaaUniforms {
inv_view_proj: [f32; 16],
prev_view_proj: [f32; 16],
/// x: width, y: height, z: history weight, w: first-frame flag.
params: [f32; 4],
/// xyz: how far the camera moved since the previous frame. w: the distance
/// past which a pixel is treated as sky and reprojected by rotation alone.
cam_delta: [f32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable, Default)]
struct MeshUniforms {
model: [f32; 16],
normal_matrix: [f32; 16],
color: [f32; 4],
emissive: [f32; 4],
specular: [f32; 4],
/// x: shininess/depth_near, y: opacity/depth_far, z: roughness, w: metalness
params: [f32; 4],
/// x: ao_intensity, y/z: normal_scale, w: toon_steps (bitcast u32 in WGSL)
params2: [f32; 4],
/// Physical layers: x: clearcoat, y: clearcoat_roughness, z: ior, w: transmission
params3: [f32; 4],
/// Physical volume: x: thickness (glass refraction/march depth),
/// y: dispersion, z: vertex_emissive, w: anisotropy_rotation (radians).
params4: [f32; 4],
/// Physical layers 2: x: iridescence, y: iridescence_ior,
/// z: iridescence_thickness (nm), w: sheen strength.
params5: [f32; 4],
/// x/y/z: sheen_color, w: sheen_roughness.
params6: [f32; 4],
/// x/y/z: attenuation_color, w: attenuation_distance (0 = disabled, which
/// keeps the legacy "tint transmission by base color" behaviour).
params7: [f32; 4],
/// x: displacement_scale, y: displacement_bias, z: emissive_night_side
/// (w reserved).
params8: [f32; 4],
/// UV transform from the primary map: xy offset, zw repeat.
params9: [f32; 4],
/// x: cloud shell height, y: cloud shadow strength, z: cloud longitude
/// offset (turns), w: twilight wrap width.
params10: [f32; 4],
/// xyz: twilight colour, w: the sun's angular radius in radians.
params11: [f32; 4],
/// Eclipse occluder: world-space xyz centre, w radius (0 = none).
params12: [f32; 4],
/// x: cloud forward-scatter strength, y: scattering anisotropy g,
/// z: ozone absorption strength, w: aurora strength.
params13: [f32; 4],
/// xyz: aurora colour, w: geomagnetic colatitude of the auroral oval, in
/// degrees from the pole.
params14: [f32; 4],
/// x: material kind, y: texture flags
flags: [u32; 4],
}
// Texture-flag bits — keep in sync with shader.rs FLAG_*.
const FLAG_MAP: u32 = 1;
const FLAG_NORMAL_MAP: u32 = 2;
const FLAG_ROUGHNESS_MAP: u32 = 4;
const FLAG_METALNESS_MAP: u32 = 8;
const FLAG_AO_MAP: u32 = 16;
const FLAG_EMISSIVE_MAP: u32 = 32;
const FLAG_MATCAP_MAP: u32 = 64;
const FLAG_DASHED: u32 = 128;
const FLAG_SHADOW_MAT: u32 = 256;
const FLAG_RECEIVE_SHADOW: u32 = 512;
const FLAG_IRIDESCENCE_MAP: u32 = 1024;
const FLAG_DISPLACEMENT_MAP: u32 = 2048;
const FLAG_CLOUD_SHADOW: u32 = 4096;
struct CachedGpuMesh {
version: u32,
mesh: GpuMesh,
}
/// Camera parameters forwarded into SSAO / SSR post-fx uniforms.
#[derive(Clone)]
pub struct PostFxCamera {
pub near: f32,
pub far: f32,
pub kernel_radius: f32,
pub kernel_size: u32,
pub proj: [f32; 16],
pub inv_proj: [f32; 16],
}
impl Default for PostFxCamera {
fn default() -> Self {
let mut id = [0f32; 16];
id[0] = 1.0;
id[5] = 1.0;
id[10] = 1.0;
id[15] = 1.0;
Self {
near: 0.1,
far: 100.0,
kernel_radius: 8.0,
kernel_size: 32,
proj: id,
inv_proj: id,
}
}
}
/// How the renderer compresses linear HDR radiance into displayable range.
///
/// Defaults to [`ToneMapping::None`], which matches the renderer's historical
/// behaviour — values above 1.0 hard-clip. That is fine for LDR content but
/// destroys hue in highlights: a clipped gold specular goes white, not gold.
/// Any scene using an HDR environment wants [`ToneMapping::AcesFilmic`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ToneMapping {
/// No curve; linear values are clamped to [0, 1] at output.
#[default]
None,
/// Plain exposure scale, then clamp.
Linear,
/// ACES filmic approximation — rolls highlights off smoothly and keeps
/// their hue, which is what makes bright metal read as metal.
AcesFilmic,
}
impl ToneMapping {
/// The mode index the WGSL side switches on.
fn shader_mode(self) -> f32 {
match self {
ToneMapping::None => 0.0,
ToneMapping::Linear => 1.0,
ToneMapping::AcesFilmic => 2.0,
}
}
}
/// GPU renderer: scene draws, shadow maps, environment sampling, post-fx.
pub struct Renderer {
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
pipeline_tri: wgpu::RenderPipeline,
pipeline_tri_alpha: wgpu::RenderPipeline,
// Single-layer glass (depth prepass + LessEqual color pass), sRGB + f16.
pipeline_glass_depth: wgpu::RenderPipeline,
pipeline_glass_color: wgpu::RenderPipeline,
pipeline_glass_depth_f16: wgpu::RenderPipeline,
pipeline_glass_color_f16: wgpu::RenderPipeline,
// Weighted-blended OIT: accumulation pipeline (MRT) + resolve (sRGB + f16).
pipeline_oit: wgpu::RenderPipeline,
pipeline_oit_resolve: wgpu::RenderPipeline,
pipeline_oit_resolve_f16: wgpu::RenderPipeline,
oit_resolve_bgl: wgpu::BindGroupLayout,
// accum(Rgba16F) + revealage(R16F) targets + the resolve bind group, keyed by size.
oit_targets: Option<(
u32,
u32,
wgpu::Texture,
wgpu::TextureView,
wgpu::Texture,
wgpu::TextureView,
wgpu::BindGroup,
)>,
/// No-cull triangle pipeline, used for `side: BackSide` / `side: DoubleSide`
/// materials. Without this, three.js apps using BackSide for skybox-style
/// "inside of a box" rendering silently get culled-to-nothing.
pipeline_tri_nocull: wgpu::RenderPipeline,
/// Sky dome: no cull, no depth write, LessEqual (matches three.js Sky depthWrite:false).
pipeline_tri_sky: wgpu::RenderPipeline,
pipeline_tri_wire: wgpu::RenderPipeline,
pipeline_line: wgpu::RenderPipeline,
pipeline_point: wgpu::RenderPipeline,
pipeline_sprite: wgpu::RenderPipeline,
// Hardware-MSAA variants of the opaque forward pipelines (surface path).
pipeline_tri_msaa: wgpu::RenderPipeline,
pipeline_tri_alpha_msaa: wgpu::RenderPipeline,
pipeline_tri_nocull_msaa: wgpu::RenderPipeline,
pipeline_tri_sky_msaa: wgpu::RenderPipeline,
pipeline_tri_wire_msaa: wgpu::RenderPipeline,
pipeline_line_msaa: wgpu::RenderPipeline,
pipeline_point_msaa: wgpu::RenderPipeline,
/// MSAA sample count for the surface pass: 1 = off, else `MSAA_SAMPLES`.
msaa: u32,
tone_mapping: ToneMapping,
exposure: f32,
/// Lazily-created multisampled color + depth targets, keyed by size.
msaa_targets: Option<(u32, u32, wgpu::TextureView, wgpu::TextureView)>,
/// Half-float color-target variants for EffectComposer / postfx RTs.
pipeline_tri_f16: wgpu::RenderPipeline,
pipeline_tri_alpha_f16: wgpu::RenderPipeline,
pipeline_tri_nocull_f16: wgpu::RenderPipeline,
pipeline_tri_sky_f16: wgpu::RenderPipeline,
pipeline_tri_wire_f16: wgpu::RenderPipeline,
pipeline_line_f16: wgpu::RenderPipeline,
pipeline_point_f16: wgpu::RenderPipeline,
pipeline_sprite_f16: wgpu::RenderPipeline,
pipeline_instanced_f16: wgpu::RenderPipeline,
pipeline_skinned_f16: wgpu::RenderPipeline,
pipeline_shadow: wgpu::RenderPipeline,
pipeline_shadow_spot: wgpu::RenderPipeline,
pipeline_shadow_point: wgpu::RenderPipeline,
pipeline_instanced: wgpu::RenderPipeline,
pipeline_skinned: wgpu::RenderPipeline,
/// Post-fx fullscreen-quad pipeline. Reads one input texture, writes to
/// one output attachment, applies the effect selected by the postfx
/// uniform's effect-kind field.
pipeline_postfx: wgpu::RenderPipeline,
/// Additive-blend variant of the postfx pipeline. Used for bloom composite
/// where the bloom contribution adds to the existing framebuffer content.
pipeline_postfx_add: wgpu::RenderPipeline,
/// Outline overlay: SrcAlpha + One (three.js AdditiveBlending).
pipeline_postfx_outline_add: wgpu::RenderPipeline,
/// Multiply-blend variant (DstColor * SrcColor). Used for SSAO composite.
pipeline_postfx_multiply: wgpu::RenderPipeline,
/// Half-float postfx variants for outline intermediates (Rgba16Float RTs).
pipeline_postfx_f16: wgpu::RenderPipeline,
pipeline_postfx_add_f16: wgpu::RenderPipeline,
postfx_bgl: wgpu::BindGroupLayout,
postfx_sampler: wgpu::Sampler,
postfx_nearest_sampler: wgpu::Sampler,
/// Repeat + nearest sampler for SSAO noise (matches three.js RepeatWrapping).
postfx_noise_sampler: wgpu::Sampler,
/// Uploaded by SSAOPass — 32 hemisphere samples (vec4 stride).
ssao_kernel_buffer: wgpu::Buffer,
ssao_noise_tex: wgpu::Texture,
ssao_noise_view: wgpu::TextureView,
/// 64×64 R8 displacement map for GlitchPass (DigitalGlitch tDisp).
glitch_disp_tex: wgpu::Texture,
glitch_disp_view: wgpu::TextureView,
/// Full-screen R8 snow map for GlitchPass (precomputed in JS for GLSL parity).
glitch_snow_tex: wgpu::Texture,
glitch_snow_view: wgpu::TextureView,
/// CPU-uploaded RGBA8 for WebGL postfx fallback blit to canvas/RT.
rgba_upload_tex: wgpu::Texture,
rgba_upload_view: wgpu::TextureView,
/// Alpha-blended 2D overlay pass, built on the first caption draw so
/// projects that never draw one allocate nothing.
caption_pass: Option<super::caption_pass::CaptionPass>,
mesh_skinned_bgl: wgpu::BindGroupLayout,
sprite_quad: GpuMesh,
frame_bgl: wgpu::BindGroupLayout,
mesh_bgl: wgpu::BindGroupLayout,
tex_bgl: wgpu::BindGroupLayout,
env_bgl: wgpu::BindGroupLayout,
/// Bind group layout for custom-shader draws: mesh uniform (binding 0) plus
/// `ShaderMaterial` user data (binding 1 uniform + bindings 2-4 storage), all
/// in @group(1) to stay within WebGPU's 4-bind-group limit.
custom_mesh_bgl: wgpu::BindGroupLayout,
/// Pipeline layout for custom-shader materials ([frame, custom_mesh, tex, env]).
custom_pipeline_layout: wgpu::PipelineLayout,
/// Lazily-compiled custom-shader pipelines, keyed by (fragment-source hash,
/// is-half-float-target, is-transparent).
custom_pipelines: HashMap<(u64, bool, bool, bool, u32), wgpu::RenderPipeline>,
depth_view: wgpu::TextureView,
/// The renderer's own depth texture (COPY_SRC) for the direct-`render` path.
depth_texture: wgpu::Texture,
/// 1×1 placeholder depth texture for postfx binding 6 when hw depth is unused.
hw_depth_tex: wgpu::Texture,
depth_size: (u32, u32),
geom_cache: HashMap<*const BufferGeometry, CachedGpuMesh>,
skin_attr_cache: HashMap<*const BufferGeometry, wgpu::Buffer>,
/// Uploaded textures, by [`Texture::id`].
tex_cache: HashMap<TexCacheKey, GpuTexture>,
/// Builds mip chains with the GPU rather than the CPU. See [`MipGenerator`].
mipgen: Option<MipGenerator>,
/// Lookup table for render-target-backed textures, keyed by RT id.
rt_view_cache: HashMap<u32, wgpu::TextureView>,
/// Linear (non-sRGB-decode) sample views for AO/depth/normal postfx buffers.
rt_linear_view_cache: HashMap<u32, wgpu::TextureView>,
/// Render targets keyed by id (for creating per-pass sample views).
rt_registry: HashMap<u32, Arc<super::RenderTarget>>,
/// GPU depth-buffer views for SSAO (Depth32Float, depth-only aspect).
rt_depth_view_cache: HashMap<u32, wgpu::TextureView>,
/// Lookup table for cube render targets' cube views, keyed by RT id.
cube_rt_view_cache: HashMap<u32, wgpu::TextureView>,
cube_cache: HashMap<*const CubeTexture, GpuCubeTexture>,
env_bind_group: wgpu::BindGroup,
shadow_env_bind_group: wgpu::BindGroup,
env_sampler: wgpu::Sampler,
default_env_cube: GpuCubeTexture,
default_cube_uv_view: wgpu::TextureView,
cube_face_buffers: [wgpu::Buffer; 6],
cube_face_bind_groups: [wgpu::BindGroup; 6],
env_cached_key: Option<*const CubeTexture>,
/// Rebuild the environment bind group on the next frame regardless of the
/// cache keys.
///
/// Needed because "invalidate" cannot be expressed by clearing those keys: a
/// scene with no environment map already has `None` for both, so `None !=
/// None` detects nothing and the group survives a shadow-texture
/// reallocation still pointing at the old view.
env_dirty: bool,
/// When the env source is a CubeRenderTarget, this is its id. Used to
/// invalidate the env bind group when the RT changes.
env_cached_rt_id: Option<u32>,
shadow_view: wgpu::TextureView,
/// Side of the directional shadow map currently allocated.
shadow_size: u32,
/// True while rendering one face of an environment cube. Screen-space
/// passes that assume the frame's dimensions are skipped.
cube_pass: bool,
shadow_sampler: wgpu::Sampler,
spot_shadow_view: wgpu::TextureView,
spot_shadow_sampler: wgpu::Sampler,
#[allow(dead_code)]
point_shadow_cube_view: wgpu::TextureView,
point_shadow_face_views: [wgpu::TextureView; 6],
#[allow(dead_code)]
point_shadow_sampler: wgpu::Sampler,
frame_buffer: wgpu::Buffer,
frame_bind_group: wgpu::BindGroup,
per_mesh: Vec<(wgpu::Buffer, wgpu::BindGroup, wgpu::BindGroup)>, // uniform, mesh bg, tex bg
sampler_linear: wgpu::Sampler,
sampler_nearest_clamp: wgpu::Sampler,
sampler_linear_repeat: wgpu::Sampler,
sampler_nearest_repeat: wgpu::Sampler,
// Default fallbacks (1x1 textures used when a material slot is empty).
default_white_srgb: GpuTexture,
default_white_linear: GpuTexture,
default_normal: GpuTexture, // (0.5, 0.5, 1.0, 1.0) — straight up tangent normal
/// Also the empty displacement slot: sampling black moves nothing, so the
/// vertex stage needs no branch.
default_black: GpuTexture,
/// The empty cloud-shadow slot. `default_black` is opaque, and a cover map
/// is read from *alpha* — so an unset slot there would read as total
/// overcast and black out the planet.
default_transparent: GpuTexture,
// --- Screen-space refraction glass (TransparencyMode::Refract) ---
/// Mipmapped capture of the opaque scene, sampled by the glass shader for
/// screen-space refraction/reflection. `(w, h, texture, all-mips view,
/// per-mip render views, mip count, format)`.
ss_color: Option<SsColor>,
/// Filtering sampler (trilinear) for `ss_color` — roughness selects the LOD.
ss_glass_sampler: wgpu::Sampler,
/// Sampleable copy of the opaque depth (COPY_DST | TEXTURE_BINDING), marched
/// by the glass shader. `(w, h, texture, view)`.
ss_depth: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
/// Nearest glass **back-face** depth (RENDER_ATTACHMENT | TEXTURE_BINDING),
/// used to derive the per-pixel glass thickness for two-surface refraction.
ss_back_depth: Option<(u32, u32, wgpu::Texture, wgpu::TextureView)>,
/// Depth-only pipeline rendering glass back faces (cull front) into ss_back_depth.
pipeline_ss_back_depth: wgpu::RenderPipeline,
/// 1×1 placeholder depth bound at env-group binding 11/12 when no glass draws.
ss_depth_placeholder_view: wgpu::TextureView,
/// Fullscreen "sample one texture → write" pipeline (mip downsample + blit),
/// one per framebuffer format.
pipeline_ss_blit: wgpu::RenderPipeline,
pipeline_ss_blit_f16: wgpu::RenderPipeline,
/// Glass surface pipelines (screen-space refraction/reflection).
pipeline_ss_glass: wgpu::RenderPipeline,
pipeline_ss_glass_f16: wgpu::RenderPipeline,
/// BGL for the blit/downsample pipeline (texture + sampler).
ss_blit_bgl: wgpu::BindGroupLayout,
// --- Temporal anti-aliasing (opt-in via `set_taa`) ---
taa_enabled: bool,
taa_frame: u32,
taa_prev_view_proj: [f32; 16],
/// Camera matrices tracked EVERY frame, not just when TAA is on, so a pass
/// running after the render can reproject: `mb_inv_vp` inverts the frame
/// just drawn and `mb_prev_vp` is the one before it. Motion blur needs both
/// and must not depend on whether temporal AA happens to be enabled.
mb_inv_vp: [f32; 16],
mb_prev_vp: [f32; 16],
mb_last_vp: [f32; 16],
/// Camera position at the previous TAA frame, for the sky reprojection.
taa_prev_cam: [f32; 3],
/// Ping-pong history: `(w, h, texA, viewA, texB, viewB)`; frame parity picks
/// read vs. write.
taa_history: Option<(
u32,
u32,
wgpu::Texture,
wgpu::TextureView,
wgpu::Texture,
wgpu::TextureView,
)>,
taa_uniform: wgpu::Buffer,
taa_bgl: wgpu::BindGroupLayout,
taa_sampler: wgpu::Sampler,
pipeline_taa: wgpu::RenderPipeline,
pipeline_taa_f16: wgpu::RenderPipeline,
color_format: wgpu::TextureFormat,
}
/// Mipmapped opaque-scene capture used by the screen-space glass pass.
struct SsColor {
width: u32,
height: u32,
#[allow(dead_code)]
texture: wgpu::Texture,
/// View over all mips — bound to the glass shader for LOD sampling.
all_mips_view: wgpu::TextureView,
/// One single-mip view per level — render targets for the downsample chain.
mip_render_views: Vec<wgpu::TextureView>,
/// One single-mip sample view per level — sources for the downsample chain.
mip_sample_views: Vec<wgpu::TextureView>,
mips: u32,
format: wgpu::TextureFormat,
}
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
/// Hardware MSAA sample count used when antialiasing is enabled for the
/// direct-to-surface opaque forward pass. 4× is universally supported.
const MSAA_SAMPLES: u32 = 4;
// ---- ShaderMaterial (custom-shader) support ----------------------------------
/// Cache key for a custom shader = a hash of its fragment source.
fn custom_shader_hash(src: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
src.hash(&mut h);
h.finish()
}
/// Assemble a full WGSL module for a custom shader: the built-in preamble
/// (everything before the built-in `fs_main` — structs, `vs_main`, bindings for
/// groups 0-3, and all helper functions), then the `@group(4)` user bindings,
/// then the user's fragment.
fn custom_shader_module_source(fragment: &str) -> String {
let preamble = SHADER_SOURCE
.split("@fragment")
.next()
.unwrap_or(SHADER_SOURCE);
// User data lives in @group(1) alongside the mesh uniform (binding 0), to
// stay within WebGPU's 4-bind-group limit.
let user_bindings = "\n\
struct ThreersUserData { data: array<vec4<f32>, 16>, };\n\
@group(1) @binding(1) var<uniform> u_data: ThreersUserData;\n\
@group(1) @binding(2) var<storage, read> u_s0: array<f32>;\n\
@group(1) @binding(3) var<storage, read> u_s1: array<f32>;\n\
@group(1) @binding(4) var<storage, read> u_s2: array<f32>;\n\
@group(1) @binding(5) var u_tex0: texture_2d<f32>;\n\
@group(1) @binding(6) var u_tex1: texture_2d<f32>;\n\
@group(1) @binding(7) var u_tex2: texture_2d<f32>;\n\
@group(1) @binding(8) var u_tex3: texture_2d<f32>;\n\
@group(1) @binding(9) var u_samp: sampler;\n";
format!("{preamble}{user_bindings}\n{fragment}\n")
}
/// Compile a custom-shader pipeline (alpha-blended, no depth write — treated as
/// transparent for correct compositing).
fn build_custom_pipeline(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
fragment: &str,
format: wgpu::TextureFormat,
transparent: bool,
screen_space: bool,
side: u32,
) -> wgpu::RenderPipeline {
let source = custom_shader_module_source(fragment);
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers custom shader"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let vertex_buffers = [wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
}];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers = vertex_buffers.map(Some);
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers custom pipeline"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format,
// Transparent: alpha-blend, no depth write (sorted back-to-front).
// Opaque: replace + depth write, so the surface self-occludes.
// Screen-space surfaces composite over the already-blitted opaque
// scene, so they blend — but they still write depth, so anything
// drawn later sorts against the surface rather than through it.
blend: Some(if transparent || screen_space {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
// three.js `side`: 0 FrontSide, 1 BackSide, 2 DoubleSide. Previously
// hardcoded to front, which silently culls anything meant to be seen from
// the inside — a sky dome, or a water surface viewed from below it.
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
match side {
1 => Some(wgpu::Face::Front),
2 => None,
_ => Some(wgpu::Face::Back),
},
),
depth_stencil: Some(depth_stencil(
screen_space || !transparent,
wgpu::CompareFunction::Less,
)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
}
/// Build the custom @group(1) bind group: the mesh uniform (binding 0, shared
/// with the standard path) plus the `ShaderMaterial` user uniform (binding 1)
/// and three storage arrays (bindings 2-4). Returns the bind group plus the new
/// buffers it owns (kept alive by the caller until the render pass is submitted).
#[allow(clippy::too_many_arguments)]
fn build_user_bind_group(
device: &wgpu::Device,
bgl: &wgpu::BindGroupLayout,
mesh_uniform: &wgpu::Buffer,
data: &[[f32; 4]; 16],
storage: &[Vec<f32>; 3],
textures: &[std::sync::Arc<wgpu::TextureView>],
placeholder: &wgpu::TextureView,
sampler: &wgpu::Sampler,
) -> (wgpu::BindGroup, Vec<wgpu::Buffer>) {
use wgpu::util::DeviceExt;
let flat: Vec<f32> = data.iter().flat_map(|v| v.iter().copied()).collect();
let mut buffers = vec![
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("threers user uniform"),
contents: bytemuck::cast_slice(&flat),
usage: wgpu::BufferUsages::UNIFORM,
}),
];
for s in storage.iter() {
buffers.push(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("threers user storage"),
contents: bytemuck::cast_slice(s),
usage: wgpu::BufferUsages::STORAGE,
}),
);
}
let tex =
|i: usize| -> &wgpu::TextureView { textures.get(i).map(|t| &**t).unwrap_or(placeholder) };
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers custom mesh+user bg"),
layout: bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: mesh_uniform.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: buffers[0].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: buffers[1].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: buffers[2].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: buffers[3].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(tex(0)),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView(tex(1)),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::TextureView(tex(2)),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(tex(3)),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::Sampler(sampler),
},
],
});
(bg, buffers)
}
impl Renderer {
/// Shared device handle. Used by callers (e.g. async readback) that need
/// to encode commands or allocate buffers outside the renderer's own loop.
pub fn device_arc(&self) -> Arc<wgpu::Device> {
self.device.clone()
}
/// Shared queue handle (same use case as `device_arc`).
pub fn queue_arc(&self) -> Arc<wgpu::Queue> {
self.queue.clone()
}
/// Upload `geom` to the GPU now, instead of waiting for the first draw.
///
/// Only needed when something outside the renderer wants the buffer up
/// front — a compute pass that writes it, typically. See
/// [`vertex_buffer`](Self::vertex_buffer).
pub fn upload_geometry(&mut self, geom: &std::sync::Arc<BufferGeometry>) {
self.ensure_geometry(geom);
}
/// The GPU vertex buffer backing `geom`, if it has been uploaded.
///
/// Interleaved, `GpuMesh::VERTEX_STRIDE` bytes per vertex, laid out
/// position(3), normal(3), uv(2), colour(4), tangent(4) as `f32`.
///
/// Writing it from a compute pass requires
/// [`BufferGeometry::gpu_writable`], and the handle is only valid until the
/// geometry is re-uploaded — which happens whenever
/// [`geometry_version`](BufferGeometry::geometry_version) changes. Drive a
/// mesh one way or the other, not both.
pub fn vertex_buffer(&self, geom: &std::sync::Arc<BufferGeometry>) -> Option<&wgpu::Buffer> {
self.geom_cache
.get(&geom_cache_key(geom))
.map(|e| &e.mesh.vertex_buffer)
}
fn ensure_geometry(&mut self, geom: &std::sync::Arc<BufferGeometry>) {
let key = geom_cache_key(geom);
let ver = geom.geometry_version;
let stale = self
.geom_cache
.get(&key)
.map(|e| e.version != ver)
.unwrap_or(true);
if stale {
let mesh = GpuMesh::upload(&self.device, geom);
self.geom_cache
.insert(key, CachedGpuMesh { version: ver, mesh });
}
}
/// (Re)create the OIT accumulation + revealage targets at `w×h` and their
/// resolve bind group. No-op if already the right size.
/// (Re)create the mipmapped opaque-scene capture used by the screen-space
/// glass pass. Sized `w×h` in `format` (must match the framebuffer format so
/// the opaque pipelines can render into mip 0). The mip chain feeds the
/// roughness→LOD blur of the refracted/reflected image.
fn ensure_ss_targets(&mut self, w: u32, h: u32, format: wgpu::TextureFormat) {
let (w, h) = (w.max(1), h.max(1));
if let Some(c) = &self.ss_color {
if c.width == w && c.height == h && c.format == format {
return;
}
}
// ~8 mips is plenty for a roughness blur; cap so the smallest is ≥1px.
let max_mips = 32 - (w.max(h)).leading_zeros();
let mips = max_mips.clamp(1, 8);
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss color capture"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let all_mips_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut mip_render_views = Vec::with_capacity(mips as usize);
let mut mip_sample_views = Vec::with_capacity(mips as usize);
for m in 0..mips {
mip_render_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers ss mip render"),
base_mip_level: m,
mip_level_count: Some(1),
..Default::default()
}));
mip_sample_views.push(texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers ss mip sample"),
base_mip_level: m,
mip_level_count: Some(1),
..Default::default()
}));
}
self.ss_color = Some(SsColor {
width: w,
height: h,
texture,
all_mips_view,
mip_render_views,
mip_sample_views,
mips,
format,
});
// Sampleable copy of the opaque depth (marched by the glass shader).
let need_depth = match &self.ss_depth {
Some((cw, ch, ..)) => *cw != w || *ch != h,
None => true,
};
if need_depth {
let dtex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss depth copy"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let dview = dtex.create_view(&wgpu::TextureViewDescriptor::default());
self.ss_depth = Some((w, h, dtex, dview));
// Glass back-face depth target (rendered into, then sampled).
let btex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ss back depth"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let bview = btex.create_view(&wgpu::TextureViewDescriptor::default());
self.ss_back_depth = Some((w, h, btex, bview));
}
}
/// Enable/disable temporal anti-aliasing. When enabled, the renderer jitters
/// the projection each frame and blends against a reprojected history buffer.
/// Only active on the `render_to` path (needs a sampleable color target).
/// The depth buffer the last `render` wrote, for passes that run after it.
///
/// Not the offscreen target's depth: with MSAA the renderer takes a
/// surface-style path and writes its own, leaving a target's depth texture
/// untouched. A pass that read that one would sample an empty buffer and
/// produce nothing, silently — which is the whole reason this accessor
/// exists rather than callers reaching for the obvious field.
/// Inverse view-projection of the frame just drawn, and the view-projection
/// of the one before it — for passes that reproject after the render.
pub fn reprojection(&self) -> ([f32; 16], [f32; 16]) {
(self.mb_inv_vp, self.mb_prev_vp)
}
pub fn depth_texture(&self) -> &wgpu::Texture {
&self.depth_texture
}
pub fn set_taa(&mut self, enabled: bool) {
if !enabled {
self.taa_frame = 0;
self.taa_history = None;
}
self.taa_enabled = enabled;
}
/// Reset TAA accumulation (call on a hard cut / scene change to avoid ghosting).
pub fn reset_taa(&mut self) {
self.taa_frame = 0;
}
fn ensure_taa_targets(&mut self, w: u32, h: u32, format: wgpu::TextureFormat) {
let (w, h) = (w.max(1), h.max(1));
if let Some((cw, ch, ..)) = &self.taa_history {
if *cw == w && *ch == h {
return;
}
}
let mk = || {
let tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers taa history"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
};
let (a, av) = mk();
let (b, bv) = mk();
self.taa_history = Some((w, h, a, av, b, bv));
self.taa_frame = 0;
}
fn ensure_oit_targets(&mut self, w: u32, h: u32) {
let (w, h) = (w.max(1), h.max(1));
if let Some((cw, ch, ..)) = &self.oit_targets {
if *cw == w && *ch == h {
return;
}
}
let mk = |fmt: wgpu::TextureFormat, label: &str| {
let tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: fmt,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
};
let (accum, accum_view) = mk(wgpu::TextureFormat::Rgba16Float, "threers oit accum");
let (reveal, reveal_view) = mk(wgpu::TextureFormat::R16Float, "threers oit reveal");
let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers oit resolve bg"),
layout: &self.oit_resolve_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&accum_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&reveal_view),
},
],
});
self.oit_targets = Some((w, h, accum, accum_view, reveal, reveal_view, bg));
}
/// Create pipelines and default 1×1 fallback textures.
///
/// `color_format` is the swapchain or render-target format (typically
/// `Rgba8Unorm` or `Rgba8UnormSrgb` on web, `Bgra8UnormSrgb` on some desktops).
pub fn new(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
color_format: wgpu::TextureFormat,
width: u32,
height: u32,
) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers shader"),
source: wgpu::ShaderSource::Wgsl(SHADER_SOURCE.into()),
});
let uniform_entry = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let frame_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers frame bgl"),
entries: &[uniform_entry(0)],
});
let mesh_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers mesh bgl"),
entries: &[uniform_entry(0)],
});
// Skinned variant of the mesh BGL: same uniform at binding 0, plus a
// storage buffer of bone matrices at binding 1. This lets the skinned
// pipeline stay within the 4-bind-group WebGPU default limit.
let mesh_skinned_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers mesh skinned bgl"),
entries: &[
uniform_entry(0),
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
// 8 fragment textures (albedo, normal, roughness, metalness, ao,
// emissive, matcap, iridescence) + 1 sampler + a displacement map that
// is sampled in the *vertex* stage.
let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers tex bgl"),
entries: &[
tex_entry(0),
tex_entry(1),
tex_entry(2),
tex_entry(3),
tex_entry(4),
tex_entry(5),
tex_entry(6),
tex_entry(8),
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 7,
// The displacement sample needs the same sampler, from the
// vertex stage.
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let env_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers env bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::Cube,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 6,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::Cube,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 8,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
// 9/10: screen-space glass — mipmapped opaque-scene capture +
// its trilinear sampler (only read by the fs_ss_glass entry).
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 10,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
// 11: sampleable opaque depth; 12: glass back-face depth (both
// marched/read by fs_ss_glass via textureLoad, no sampler).
// 1×1 placeholders bound otherwise.
wgpu::BindGroupLayoutEntry {
binding: 11,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 12,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&mesh_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
// Skinned pipeline layout: same as the base 4 groups, but group 1 uses
// the skinned mesh BGL (uniform + bones storage). Stays at 4 groups —
// WebGPU's default `maxBindGroups` limit.
let pipeline_layout_skinned =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers skinned layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&mesh_skinned_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
// ShaderMaterial data rides in @group(1) alongside the mesh uniform
// (WebGPU's default maxBindGroups is 4, so we can't add a 5th group):
// binding 0 = mesh uniform (as usual), binding 1 = user uniform block,
// bindings 2..4 = read-only storage arrays.
let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let uniform_entry = |binding: u32, vis: wgpu::ShaderStages| wgpu::BindGroupLayoutEntry {
binding,
visibility: vis,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let custom_tex_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let custom_mesh_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers custom mesh+user bgl"),
entries: &[
uniform_entry(0, wgpu::ShaderStages::VERTEX_FRAGMENT),
uniform_entry(1, wgpu::ShaderStages::FRAGMENT),
storage_entry(2),
storage_entry(3),
storage_entry(4),
// User textures + their sampler. Unbound slots get a 1x1 white
// placeholder, so a shader that ignores them costs nothing.
custom_tex_entry(5),
custom_tex_entry(6),
custom_tex_entry(7),
custom_tex_entry(8),
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let custom_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers custom (shader material) layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&custom_mesh_bgl), Some(&tex_bgl), Some(&env_bgl)],
immediate_size: 0,
});
let vertex_buffers = [wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
}];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers = vertex_buffers.map(Some);
let make_pipeline = |fmt: wgpu::TextureFormat,
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
label: &str| {
let alpha = label.contains("alpha");
// Note: PolygonMode::Line needs the POLYGON_MODE_LINE feature, which
// is generally unavailable in browser WebGPU. The wireframe pipeline
// instead uses LineList primitives over the triangle indices (fed as
// edge indices at draw time), so every pipeline stays Fill.
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(if alpha {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(topology, cull),
// Transparent: don't write depth, so back fragments behind a
// transparent surface still composite correctly.
depth_stencil: Some(depth_stencil(!alpha, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
// Single-layer "glass" pipelines. `depth_only` (the prepass) writes the
// nearest glass depth with no color; the color pass alpha-blends only the
// fragments at that nearest depth (LessEqual) and doesn't write depth.
let make_glass_pipeline = |fmt: wgpu::TextureFormat, depth_only: bool, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: if depth_only {
wgpu::ColorWrites::empty()
} else {
wgpu::ColorWrites::ALL
},
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(
depth_only,
if depth_only {
wgpu::CompareFunction::Less
} else {
wgpu::CompareFunction::LessEqual
},
)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let f16_format = wgpu::TextureFormat::Rgba16Float;
let pipeline_glass_depth =
make_glass_pipeline(color_format, true, "threers glass depth pipeline");
let pipeline_glass_color =
make_glass_pipeline(color_format, false, "threers glass color pipeline");
let pipeline_glass_depth_f16 =
make_glass_pipeline(f16_format, true, "threers glass depth f16 pipeline");
let pipeline_glass_color_f16 =
make_glass_pipeline(f16_format, false, "threers glass color f16 pipeline");
// Screen-space refraction glass: opaque single-surface pass (writes depth,
// Less test, no blend — it composites the refracted/reflected background
// itself), sampling the captured ss-color from env-group binding 9.
let make_ss_glass_pipeline = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_ss_glass"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_ss_glass = make_ss_glass_pipeline(color_format, "threers ss glass pipeline");
let pipeline_ss_glass_f16 =
make_ss_glass_pipeline(f16_format, "threers ss glass f16 pipeline");
// Fullscreen "sample one texture → write" pipeline, used both to build
// the ss-color mip chain (downsample) and to blit the capture back to the
// frame target before the glass draws over it.
let ss_blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers ss blit bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let ss_blit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers ss blit layout"),
bind_group_layouts: &[Some(&ss_blit_bgl)],
immediate_size: 0,
});
let ss_blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers ss blit shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::SS_BLIT_SHADER.into()),
});
let make_ss_blit_pipeline = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&ss_blit_layout),
vertex: wgpu::VertexState {
module: &ss_blit_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &ss_blit_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_ss_blit = make_ss_blit_pipeline(color_format, "threers ss blit pipeline");
let pipeline_ss_blit_f16 =
make_ss_blit_pipeline(f16_format, "threers ss blit f16 pipeline");
// Depth-only pass over glass back faces (cull front) → the exit depth of
// the glass volume, for two-surface (thick) refraction. `vs_main` reads
// the displacement map out of group 2, so this needs the texture layout
// too — otherwise displaced glass would write back-face depth for
// geometry that is not where it is drawn.
let ss_back_depth_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers ss back depth layout"),
bind_group_layouts: &[Some(&frame_bgl), Some(&mesh_bgl), Some(&tex_bgl)],
immediate_size: 0,
});
let pipeline_ss_back_depth =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers ss back depth pipeline"),
layout: Some(&ss_back_depth_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: None,
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Front),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
// --- Temporal anti-aliasing resolve ---
let taa_uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers taa uniform"),
size: std::mem::size_of::<TaaUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let taa_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers taa sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let tex_entry = |binding, depth| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: if depth {
wgpu::TextureSampleType::Depth
} else {
wgpu::TextureSampleType::Float { filterable: true }
},
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let taa_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers taa bgl"),
entries: &[
tex_entry(0, false), // current
tex_entry(1, false), // history
tex_entry(2, true), // depth
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let taa_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers taa layout"),
bind_group_layouts: &[Some(&taa_bgl)],
immediate_size: 0,
});
let taa_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers taa shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::TAA_SHADER.into()),
});
let make_taa = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&taa_layout),
vertex: wgpu::VertexState {
module: &taa_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &taa_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_taa = make_taa(color_format, "threers taa pipeline");
let pipeline_taa_f16 = make_taa(f16_format, "threers taa f16 pipeline");
// --- Weighted-blended OIT ---
// Accumulation pass: fs_oit writes to accum (additive) + revealage
// (multiplicative), depth-tested against opaque but not writing depth.
let oit_accum_format = wgpu::TextureFormat::Rgba16Float;
let oit_reveal_format = wgpu::TextureFormat::R16Float;
let add_blend = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
};
let mul_blend = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
};
let pipeline_oit = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers oit accum pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_oit"),
targets: &[
Some(wgpu::ColorTargetState {
format: oit_accum_format,
blend: Some(wgpu::BlendState {
color: add_blend,
alpha: add_blend,
}),
write_mask: wgpu::ColorWrites::ALL,
}),
Some(wgpu::ColorTargetState {
format: oit_reveal_format,
blend: Some(wgpu::BlendState {
color: mul_blend,
alpha: mul_blend,
}),
write_mask: wgpu::ColorWrites::ALL,
}),
],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
// Resolve pass: composite accum/revealage over the opaque image.
let oit_resolve_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers oit resolve bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let resolve_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers oit resolve shader"),
source: wgpu::ShaderSource::Wgsl(super::shader::OIT_RESOLVE_SHADER.into()),
});
let resolve_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers oit resolve layout"),
bind_group_layouts: &[Some(&oit_resolve_bgl)],
immediate_size: 0,
});
let make_resolve = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&resolve_layout),
vertex: wgpu::VertexState {
module: &resolve_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &resolve_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_oit_resolve = make_resolve(color_format, "threers oit resolve pipeline");
let pipeline_oit_resolve_f16 = make_resolve(f16_format, "threers oit resolve f16 pipeline");
let pipeline_tri = make_pipeline(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri pipeline",
);
let pipeline_tri_alpha = make_pipeline(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri alpha pipeline",
);
let pipeline_tri_nocull = make_pipeline(
color_format,
wgpu::PrimitiveTopology::TriangleList,
None,
"threers tri nocull pipeline",
);
let make_sky_pipeline = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_tri_sky = make_sky_pipeline(color_format, "threers tri sky pipeline");
// PolygonMode::Line draws the triangle outline — used for `wireframe:true` materials.
// wgpu requires the NON_FILL_POLYGON_MODE feature for Line/Point polygon modes on
// some backends. If unsupported, this falls back to a no-op (renders nothing extra),
// but Chromium's WebGPU/SwiftShader path tends to allow it.
let pipeline_tri_wire = make_pipeline(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers tri wire pipeline",
);
let pipeline_line = make_pipeline(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers line pipeline",
);
let pipeline_point = make_pipeline(
color_format,
wgpu::PrimitiveTopology::PointList,
None,
"threers point pipeline",
);
// --- Hardware-MSAA variants of the opaque forward pipelines (surface
// path only). Identical to the ones above but with `count = MSAA_SAMPLES`;
// used when antialiasing is enabled and the scene has no glass/OIT/refract
// /instanced/skinned/custom draws (those fall back to the 1× path). ---
let make_pipeline_ms = |fmt: wgpu::TextureFormat,
topology: wgpu::PrimitiveTopology,
cull: Option<wgpu::Face>,
label: &str| {
let alpha = label.contains("alpha");
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(if alpha {
wgpu::BlendState::ALPHA_BLENDING
} else {
wgpu::BlendState::REPLACE
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(topology, cull),
depth_stencil: Some(depth_stencil(!alpha, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState {
count: MSAA_SAMPLES,
..Default::default()
},
multiview_mask: None,
cache: None,
})
};
let make_sky_pipeline_ms = |fmt: wgpu::TextureFormat, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: fmt,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState {
count: MSAA_SAMPLES,
..Default::default()
},
multiview_mask: None,
cache: None,
})
};
let pipeline_tri_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri msaa",
);
let pipeline_tri_alpha_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri alpha msaa",
);
let pipeline_tri_nocull_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::TriangleList,
None,
"threers tri nocull msaa",
);
let pipeline_tri_wire_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers tri wire msaa",
);
let pipeline_line_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers line msaa",
);
let pipeline_point_msaa = make_pipeline_ms(
color_format,
wgpu::PrimitiveTopology::PointList,
None,
"threers point msaa",
);
let pipeline_tri_sky_msaa = make_sky_pipeline_ms(color_format, "threers tri sky msaa");
let pipeline_tri_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri f16 pipeline",
);
let pipeline_tri_alpha_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
"threers tri alpha f16 pipeline",
);
let pipeline_tri_nocull_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::TriangleList,
None,
"threers tri nocull f16 pipeline",
);
let pipeline_tri_sky_f16 = make_sky_pipeline(f16_format, "threers tri sky f16 pipeline");
let pipeline_tri_wire_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers tri wire f16 pipeline",
);
let pipeline_line_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::LineList,
None,
"threers line f16 pipeline",
);
let pipeline_point_f16 = make_pipeline(
f16_format,
wgpu::PrimitiveTopology::PointList,
None,
"threers point f16 pipeline",
);
// Instanced pipeline: vertex layout slot 0 (per-vertex), slot 1 per-instance mat4.
let vertex_buffers_instanced = [
wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
},
wgpu::VertexBufferLayout {
array_stride: 64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 4,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 16,
shader_location: 5,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 6,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 7,
format: wgpu::VertexFormat::Float32x4,
},
],
},
];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers_instanced = vertex_buffers_instanced.map(Some);
// Skinned vertex layout: slot 0 = standard vertex, slot 1 = joints+weights.
let vertex_buffers_skinned = [
wgpu::VertexBufferLayout {
array_stride: GpuMesh::VERTEX_STRIDE as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 12,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: 24,
shader_location: 2,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: 32,
shader_location: 3,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 48,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
],
},
wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 4,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: 16,
shader_location: 5,
format: wgpu::VertexFormat::Float32x4,
},
],
},
];
// `buffers` takes a slice of `Option` in wgpu 30.
let vertex_buffers_skinned = vertex_buffers_skinned.map(Some);
let pipeline_skinned = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers skinned pipeline"),
layout: Some(&pipeline_layout_skinned),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_skinned"),
buffers: &vertex_buffers_skinned,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_skinned_f16 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers skinned f16 pipeline"),
layout: Some(&pipeline_layout_skinned),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_skinned"),
buffers: &vertex_buffers_skinned,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: f16_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_instanced = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers instanced pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_instanced"),
buffers: &vertex_buffers_instanced,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_instanced_f16 =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers instanced f16 pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_instanced"),
buffers: &vertex_buffers_instanced,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: f16_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Back),
),
depth_stencil: Some(depth_stencil(true, wgpu::CompareFunction::Less)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_sprite = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers sprite pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_sprite"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_sprite_f16 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers sprite f16 pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_sprite"),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: f16_format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: Some(depth_stencil(false, wgpu::CompareFunction::LessEqual)),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
// Depth-only pipeline used to render the scene from each shadow-casting
// light's POV. Reuses the per-vertex layout + per-mesh uniforms.
let make_shadow_pipeline = |entry: &str, label: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(entry),
buffers: &vertex_buffers,
compilation_options: Default::default(),
},
fragment: None,
primitive: primitive(
wgpu::PrimitiveTopology::TriangleList,
Some(wgpu::Face::Front),
),
// Shadow bias reduces acne; keep the explicit DepthStencilState.
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: wgpu::DepthBiasState {
constant: 2,
slope_scale: 2.0,
clamp: 0.0,
},
}),
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
let pipeline_shadow = make_shadow_pipeline("vs_shadow", "threers shadow pipeline");
let pipeline_shadow_spot =
make_shadow_pipeline("vs_shadow_spot", "threers spot shadow pipeline");
let pipeline_shadow_point =
make_shadow_pipeline("vs_shadow_point", "threers point shadow pipeline");
// Post-fx fullscreen-quad pipeline. Reads one input texture, writes
// to a render attachment matching the surface format.
let postfx_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("threers postfx shader"),
source: wgpu::ShaderSource::Wgsl(crate::renderer::shader::POSTFX_SHADER.into()),
});
let postfx_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("threers postfx bgl"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 6,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 8,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 9,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
count: None,
},
],
});
let postfx_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("threers postfx pipeline layout"),
bind_group_layouts: &[Some(&postfx_bgl)],
immediate_size: 0,
});
let pipeline_postfx = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let postfx_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers postfx sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
let postfx_nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers postfx nearest sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let postfx_noise_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers postfx noise sampler"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let ssao_kernel_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers ssao kernel buffer"),
size: (32 * 16) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let ssao_noise_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers ssao noise"),
size: wgpu::Extent3d {
width: 4,
height: 4,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let ssao_noise_view = ssao_noise_tex.create_view(&wgpu::TextureViewDescriptor::default());
let glitch_disp_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers glitch disp"),
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let glitch_disp_view = glitch_disp_tex.create_view(&wgpu::TextureViewDescriptor::default());
let glitch_snow_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers glitch snow"),
size: wgpu::Extent3d {
width: 800,
height: 600,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let glitch_snow_view = glitch_snow_tex.create_view(&wgpu::TextureViewDescriptor::default());
let rgba_upload_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers rgba upload"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let rgba_upload_view = rgba_upload_tex.create_view(&wgpu::TextureViewDescriptor::default());
// Same pipeline as `pipeline_postfx`, but with additive blending so
// the shader output adds to existing framebuffer pixels (bloom composite).
let pipeline_postfx_add = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx additive pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_postfx_outline_add =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx outline additive pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_postfx_multiply =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx multiply pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Dst,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let postfx_f16_format = wgpu::TextureFormat::Rgba16Float;
let pipeline_postfx_f16 = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx f16 pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: postfx_f16_format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let pipeline_postfx_add_f16 =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("threers postfx additive f16 pipeline"),
layout: Some(&postfx_pipeline_layout),
vertex: wgpu::VertexState {
module: &postfx_shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &postfx_shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: postfx_f16_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: Default::default(),
}),
primitive: primitive(wgpu::PrimitiveTopology::TriangleList, None),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let sprite_quad = {
let mut g = crate::core::BufferGeometry::new();
g.set_attribute(
"position",
crate::core::BufferAttribute::new(
vec![
-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.5, 0.5, 0.0, -0.5, 0.5, 0.0,
],
3,
),
);
g.set_attribute(
"uv",
crate::core::BufferAttribute::new(vec![0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], 2),
);
g.set_index(vec![0, 1, 2, 0, 2, 3]);
GpuMesh::upload(&device, &g)
};
let (depth_texture, depth_view) = create_depth_view(&device, width, height);
let hw_depth_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers postfx hw depth placeholder"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
// 1×1 depth bound at env-group binding 11 when no glass draws.
let ss_depth_placeholder_view =
hw_depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
let frame_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers frame uniform"),
size: std::mem::size_of::<FrameUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let frame_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers frame bg"),
layout: &frame_bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: frame_buffer.as_entire_binding(),
}],
});
// One uniform buffer per cube face, because a point light's six shadow
// passes each need a different view-projection and they are all encoded
// before anything runs. Writing one buffer six times inside an encoder
// does not do that: `queue.write_buffer` calls are applied before *any*
// submitted command, so all six faces would render with the last one.
let cube_face_buffers: [wgpu::Buffer; 6] = std::array::from_fn(|i| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(&format!("threers cube face uniform {i}")),
size: std::mem::size_of::<FrameUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
});
let cube_face_bind_groups: [wgpu::BindGroup; 6] = std::array::from_fn(|i| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers cube face bg"),
layout: &frame_bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: cube_face_buffers[i].as_entire_binding(),
}],
})
});
let sampler_linear = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers linear sampler"),
// three.js's DataTexture default is ClampToEdge — matching here
// prevents UV-1.0-corner samples from wrapping back to UV 0.
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
// Anisotropic filtering. Mip-mapping alone still blurs a texture seen
// at a grazing angle — the whole surface of a sphere near its limb —
// because the sampler has to pick one level for a footprint that is
// long in one direction and short in the other.
anisotropy_clamp: 16,
..Default::default()
});
let sampler_nearest_clamp = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers nearest-clamp sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let sampler_linear_repeat = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers linear-repeat sampler"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
// Anisotropic filtering. Mip-mapping alone still blurs a texture seen
// at a grazing angle — the whole surface of a sphere near its limb —
// because the sampler has to pick one level for a footprint that is
// long in one direction and short in the other.
anisotropy_clamp: 16,
..Default::default()
});
let sampler_nearest_repeat = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers nearest-repeat sampler"),
address_mode_u: wgpu::AddressMode::Repeat,
address_mode_v: wgpu::AddressMode::Repeat,
address_mode_w: wgpu::AddressMode::Repeat,
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
let default_white_srgb = GpuTexture::upload(
&device,
&queue,
&Texture::solid([255, 255, 255, 255], TextureFormat::Rgba8UnormSrgb),
);
let default_white_linear = GpuTexture::upload(
&device,
&queue,
&Texture::solid([255, 255, 255, 255], TextureFormat::Rgba8Unorm),
);
let default_normal = GpuTexture::upload(
&device,
&queue,
&Texture::solid([128, 128, 255, 255], TextureFormat::Rgba8Unorm),
);
let default_black = GpuTexture::upload(
&device,
&queue,
&Texture::solid([0, 0, 0, 255], TextureFormat::Rgba8Unorm),
);
let default_transparent = GpuTexture::upload(
&device,
&queue,
&Texture::solid([0, 0, 0, 0], TextureFormat::Rgba8Unorm),
);
// Default 1x1 environment cubemap: all-black faces (zero env contribution).
let default_env_cube = {
let face_data = [0u8; 4];
let faces = [
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
face_data.to_vec(),
];
let src = CubeTexture::new(1, TextureFormat::Rgba8UnormSrgb, faces);
GpuCubeTexture::upload(&device, &queue, &src)
};
let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers env sampler"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
// Trilinear sampler for the screen-space glass capture — roughness maps
// to a mip LOD so rough glass blurs its refracted/reflected image.
let ss_glass_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers ss glass sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
// Shadow depth texture for the directional light's depth pre-pass.
//
// 4096, up from 1024. The map covers whatever the light's `camera_size`
// spans, so its resolution is only meaningful as a ratio: a vehicle
// 8 m across got 8 mm of shadow per texel at 1024, which is coarse
// enough to see as staircase edges on every strut. At 4096 it is 2 mm,
// and the cost is one 64 MB depth target and a depth pass over the same
// geometry — nothing next to the colour pass at 8K.
//
// KEEP IN STEP with SHADOW_TEXEL in shader.rs, which sizes the PCF
// kernel and cannot read this constant.
const SHADOW_SIZE: u32 = 4096;
let shadow_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers shadow depth"),
size: wgpu::Extent3d {
width: SHADOW_SIZE,
height: SHADOW_SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let shadow_view = shadow_tex.create_view(&wgpu::TextureViewDescriptor::default());
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers shadow sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
compare: Some(wgpu::CompareFunction::LessEqual),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let spot_shadow_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers spot shadow depth"),
size: wgpu::Extent3d {
width: SHADOW_SIZE,
height: SHADOW_SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let spot_shadow_view = spot_shadow_tex.create_view(&wgpu::TextureViewDescriptor::default());
let spot_shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers spot shadow sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
compare: Some(wgpu::CompareFunction::LessEqual),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
// Point shadow cubemap depth (6 layers × 512×512 Depth32Float).
const POINT_SHADOW_SIZE: u32 = 512;
let point_shadow_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers point shadow depth cube"),
size: wgpu::Extent3d {
width: POINT_SHADOW_SIZE,
height: POINT_SHADOW_SIZE,
depth_or_array_layers: 6,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let point_shadow_cube_view = point_shadow_tex.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers point shadow cube view"),
dimension: Some(wgpu::TextureViewDimension::Cube),
..Default::default()
});
let mk_face = |i: u32| {
point_shadow_tex.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers point shadow face"),
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: i,
array_layer_count: Some(1),
..Default::default()
})
};
let point_shadow_face_views: [wgpu::TextureView; 6] = [
mk_face(0),
mk_face(1),
mk_face(2),
mk_face(3),
mk_face(4),
mk_face(5),
];
let point_shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("threers point shadow sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
compare: Some(wgpu::CompareFunction::LessEqual),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let default_cube_uv_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers default cube uv"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &default_cube_uv_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&[0u8, 0, 0, 255],
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4),
rows_per_image: Some(1),
},
wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
);
let default_cube_uv_view =
default_cube_uv_tex.create_view(&wgpu::TextureViewDescriptor::default());
let env_bind_group = env_bind_group!(
device,
&env_bgl,
"threers env bg",
&default_env_cube.view,
&env_sampler,
&shadow_view,
&shadow_sampler,
&spot_shadow_view,
&spot_shadow_sampler,
&point_shadow_cube_view,
&point_shadow_sampler,
&default_cube_uv_view,
&default_cube_uv_view,
&ss_glass_sampler,
&ss_depth_placeholder_view,
&ss_depth_placeholder_view,
);
// Dummy 1x1 depth textures used by `shadow_env_bind_group` so the
// shadow passes can satisfy the pipeline layout without binding the
// textures they're currently writing to (WebGPU forbids simultaneous
// RenderAttachment + TextureBinding usage of the same resource).
let dummy_depth_2d = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers dummy depth 2d"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let dummy_depth_2d_view =
dummy_depth_2d.create_view(&wgpu::TextureViewDescriptor::default());
let dummy_depth_cube = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers dummy depth cube"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 6,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let dummy_depth_cube_view = dummy_depth_cube.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers dummy depth cube view"),
dimension: Some(wgpu::TextureViewDimension::Cube),
..Default::default()
});
let shadow_env_bind_group = env_bind_group!(
device,
&env_bgl,
"threers shadow env bg (dummies)",
&default_env_cube.view,
&env_sampler,
&dummy_depth_2d_view,
&shadow_sampler,
&dummy_depth_2d_view,
&spot_shadow_sampler,
&dummy_depth_cube_view,
&point_shadow_sampler,
&default_cube_uv_view,
&default_cube_uv_view,
&ss_glass_sampler,
&ss_depth_placeholder_view,
&ss_depth_placeholder_view,
);
Self {
device,
queue,
pipeline_glass_depth,
pipeline_glass_color,
pipeline_glass_depth_f16,
pipeline_glass_color_f16,
pipeline_oit,
pipeline_oit_resolve,
pipeline_oit_resolve_f16,
oit_resolve_bgl,
oit_targets: None,
ss_color: None,
ss_glass_sampler,
ss_depth: None,
ss_back_depth: None,
pipeline_ss_back_depth,
ss_depth_placeholder_view,
pipeline_ss_blit,
pipeline_ss_blit_f16,
pipeline_ss_glass,
pipeline_ss_glass_f16,
ss_blit_bgl,
taa_enabled: false,
taa_frame: 0,
taa_prev_view_proj: [0.0; 16],
mb_inv_vp: [0.0; 16],
mb_prev_vp: [0.0; 16],
mb_last_vp: [0.0; 16],
taa_prev_cam: [0.0; 3],
taa_history: None,
taa_uniform,
taa_bgl,
taa_sampler,
pipeline_taa,
pipeline_taa_f16,
pipeline_tri,
pipeline_tri_alpha,
pipeline_tri_nocull,
pipeline_tri_sky,
pipeline_tri_wire,
pipeline_line,
pipeline_point,
pipeline_sprite,
pipeline_tri_msaa,
pipeline_tri_alpha_msaa,
pipeline_tri_nocull_msaa,
pipeline_tri_sky_msaa,
pipeline_tri_wire_msaa,
pipeline_line_msaa,
pipeline_point_msaa,
msaa: 1,
// Off by default: enabling tone mapping would silently re-grade
// every existing scene and the parity renders along with them.
tone_mapping: ToneMapping::None,
exposure: 1.0,
msaa_targets: None,
pipeline_tri_f16,
pipeline_tri_alpha_f16,
pipeline_tri_nocull_f16,
pipeline_tri_sky_f16,
pipeline_tri_wire_f16,
pipeline_line_f16,
pipeline_point_f16,
pipeline_sprite_f16,
pipeline_instanced_f16,
pipeline_skinned_f16,
pipeline_shadow,
pipeline_shadow_spot,
pipeline_shadow_point,
pipeline_instanced,
pipeline_skinned,
pipeline_postfx,
pipeline_postfx_add,
pipeline_postfx_outline_add,
pipeline_postfx_multiply,
pipeline_postfx_f16,
pipeline_postfx_add_f16,
postfx_bgl,
postfx_sampler,
postfx_nearest_sampler,
postfx_noise_sampler,
ssao_kernel_buffer,
ssao_noise_tex,
ssao_noise_view,
glitch_disp_tex,
glitch_disp_view,
glitch_snow_tex,
glitch_snow_view,
rgba_upload_tex,
rgba_upload_view,
caption_pass: None,
mesh_skinned_bgl,
sprite_quad,
frame_bgl,
mesh_bgl,
tex_bgl,
env_bgl,
custom_mesh_bgl,
custom_pipeline_layout,
custom_pipelines: HashMap::new(),
depth_view,
depth_texture,
hw_depth_tex,
depth_size: (width, height),
geom_cache: HashMap::new(),
skin_attr_cache: HashMap::new(),
tex_cache: HashMap::new(),
mipgen: None,
rt_view_cache: HashMap::new(),
rt_linear_view_cache: HashMap::new(),
rt_registry: HashMap::new(),
rt_depth_view_cache: HashMap::new(),
cube_rt_view_cache: HashMap::new(),
cube_cache: HashMap::new(),
env_bind_group,
shadow_env_bind_group,
env_sampler,
default_env_cube,
default_cube_uv_view,
cube_face_buffers,
cube_face_bind_groups,
env_cached_key: None,
env_dirty: true,
env_cached_rt_id: None,
shadow_view,
shadow_size: SHADOW_SIZE,
cube_pass: false,
shadow_sampler,
spot_shadow_view,
spot_shadow_sampler,
point_shadow_cube_view,
point_shadow_face_views,
point_shadow_sampler,
frame_buffer,
frame_bind_group,
per_mesh: Vec::new(),
sampler_linear,
sampler_nearest_clamp,
sampler_linear_repeat,
sampler_nearest_repeat,
default_white_srgb,
default_white_linear,
default_normal,
default_black,
default_transparent,
color_format,
}
}
pub fn color_format(&self) -> wgpu::TextureFormat {
self.color_format
}
pub fn resize(&mut self, width: u32, height: u32) {
if (width, height) != self.depth_size && width > 0 && height > 0 {
let (tex, view) = create_depth_view(&self.device, width, height);
self.depth_texture = tex;
self.depth_view = view;
self.depth_size = (width, height);
self.msaa_targets = None; // recreated on next MSAA pass at the new size
}
}
/// Enable/disable hardware MSAA on the **direct-to-surface** forward pass.
/// `samples <= 1` turns it off; anything else selects `MSAA_SAMPLES` (4×).
/// Render-to-texture, shadows, and scenes using glass/OIT/refraction stay
/// single-sampled (they transparently fall back).
pub fn set_msaa(&mut self, samples: u32) {
let s = if samples > 1 { MSAA_SAMPLES } else { 1 };
if s != self.msaa {
self.msaa = s;
self.msaa_targets = None;
}
}
pub fn msaa(&self) -> u32 {
self.msaa
}
/// Set the tone-mapping curve and exposure multiplier.
///
/// Off by default so existing scenes render byte-identically. Turn it on
/// whenever the scene carries an HDR environment, otherwise everything
/// above 1.0 clips flat:
///
/// ```no_run
/// # use threers::renderer::ToneMapping;
/// # fn f(renderer: &mut threers::Renderer) {
/// renderer.set_tone_mapping(ToneMapping::AcesFilmic, 1.0);
/// # }
/// ```
pub fn set_tone_mapping(&mut self, mode: ToneMapping, exposure: f32) {
self.tone_mapping = mode;
self.exposure = exposure;
}
pub fn tone_mapping(&self) -> (ToneMapping, f32) {
(self.tone_mapping, self.exposure)
}
/// Ensure the multisampled color+depth targets exist at `w×h` for the MSAA pass.
fn ensure_msaa_targets(&mut self, w: u32, h: u32) {
if matches!(self.msaa_targets, Some((cw, ch, ..)) if cw == w && ch == h) {
return;
}
let mk = |label, format| {
self.device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: self.msaa,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
})
};
// wgpu keeps a texture alive as long as one of its views exists, so we can
// store only the views.
let cv = mk("threers msaa color", self.color_format).create_view(&Default::default());
let dv = mk("threers msaa depth", DEPTH_FORMAT).create_view(&Default::default());
self.msaa_targets = Some((w, h, cv, dv));
}
/// Apply a post-fx pass from a registered render-target id (wasm path).
///
/// Same as [`Self::apply_postfx`] but resolves `input_rt_id` internally so
/// the caller does not hold a borrow against `&mut self`. When `additive`
/// is true, output is blended onto existing framebuffer pixels.
///
/// `kind` selects the WGSL branch in [`super::shader::POSTFX_SHADER`].
/// `time` carries effect-specific data (e.g. glitch RNG seed). `params2` /
/// `params3` are four-vectors whose meaning depends on `kind`.
#[allow(clippy::too_many_arguments)]
pub fn apply_postfx_by_id(
&mut self,
input_rt_id: u32,
output_rt_id: u32,
output_view: &wgpu::TextureView,
depth_rt_id: u32,
normal_rt_id: u32,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
additive: bool,
camera: PostFxCamera,
) {
let output_format = if output_rt_id != 0 {
self.rt_registry
.get(&output_rt_id)
.map(|rt| rt.format)
.unwrap_or(self.color_format)
} else {
self.color_format
};
let input_view = if let Some(v) = self.rt_view_cache.remove(&input_rt_id) {
v
} else if let Some(rt) = self.rt_registry.get(&input_rt_id) {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx input fallback"),
format: Some(rt_sample_format(rt.format)),
..Default::default()
})
} else {
return;
};
let depth_owned = if depth_rt_id != 0 && depth_rt_id != input_rt_id {
self.rt_view_cache.remove(&depth_rt_id).or_else(|| {
self.rt_registry.get(&depth_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx depth fallback"),
format: Some(rt_sample_format(rt.format)),
..Default::default()
})
})
})
} else {
None
};
let normal_owned = if normal_rt_id != 0 {
self.rt_view_cache.remove(&normal_rt_id)
} else {
None
};
let depth_ref = depth_owned.as_ref().unwrap_or(&input_view);
let input_is_f16 = self
.rt_registry
.get(&input_rt_id)
.map(|rt| rt.format == wgpu::TextureFormat::Rgba16Float)
.unwrap_or(false);
// Kind 0 copies stored RT texels 1:1. Default: linear (non-sRGB-decode)
// view so textureLoad returns the gamma-encoded bytes the main shader
// wrote (matches direct-to-canvas). params2.y > 0.5 selects the legacy
// sRGB-decode view for OutlinePass scene copy (three.js darkens there).
let kind0_legacy = kind == 0 && params2[1] > 0.5;
let output_is_f16 = output_format == wgpu::TextureFormat::Rgba16Float;
let kind0_byte_copy = kind == 0 && !kind0_legacy && !input_is_f16 && !output_is_f16;
let use_linear_input = if kind == 0 {
input_is_f16 && !kind0_legacy
} else {
(matches!(kind, 13 | 15) && !kind0_legacy)
|| input_is_f16
|| matches!(kind, 16 | 18 | 19)
};
let use_linear_depth = matches!(kind, 11 | 12 | 14);
let input_linear = if use_linear_input {
self.rt_registry.get(&input_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx linear input"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let input_raw = if kind0_byte_copy {
self.rt_registry.get(&input_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx raw input"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let depth_linear = if use_linear_depth && depth_rt_id != 0 {
self.rt_registry.get(&depth_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx linear depth"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let normal_linear = if use_linear_depth {
self.rt_registry.get(&normal_rt_id).map(|rt| {
rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx linear normal"),
format: Some(rt.format),
..Default::default()
})
})
} else {
None
};
let input_bind = input_raw
.as_ref()
.or(input_linear.as_ref())
.unwrap_or(&input_view);
let depth_bind = depth_linear.as_ref().unwrap_or(depth_ref);
let mut params2 = params2;
if kind0_byte_copy {
params2[2] = 1.0;
}
let use_hw_depth = kind == 11 && depth_rt_id != 0 && depth_rt_id == normal_rt_id;
let hw_depth_local = if use_hw_depth {
self.rt_depth_view_cache.remove(&normal_rt_id)
} else {
None
};
let hw_depth_fallback = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers postfx hw depth fallback"),
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
let hw_depth_bind = hw_depth_local.as_ref().unwrap_or(&hw_depth_fallback);
let flip_y = if output_rt_id == 0 {
if kind == 0 {
!kind0_byte_copy && params2[1] > 0.5
} else if matches!(kind, 4 | 5 | 25 | 26) {
// Halftone/glitch: pixel-space sampling on same-orientation RT.
false
} else {
true
}
} else {
false
};
match normal_owned {
Some(n) => {
let normal_bind = normal_linear.as_ref().unwrap_or(&n);
self.apply_postfx_ex(
input_bind,
output_view,
depth_bind,
normal_bind,
hw_depth_bind,
kind,
time,
params2,
params3,
width,
height,
additive,
camera,
use_hw_depth,
output_format,
flip_y,
);
self.rt_view_cache.insert(normal_rt_id, n);
}
None => {
let fallback_normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let normal_bind = normal_linear.as_ref().unwrap_or(&fallback_normal);
self.apply_postfx_ex(
input_bind,
output_view,
depth_bind,
normal_bind,
hw_depth_bind,
kind,
time,
params2,
params3,
width,
height,
additive,
camera,
use_hw_depth,
output_format,
flip_y,
);
}
}
if let Some(v) = hw_depth_local {
self.rt_depth_view_cache.insert(normal_rt_id, v);
}
self.rt_view_cache.insert(input_rt_id, input_view);
if let Some(d) = depth_owned {
self.rt_view_cache.insert(depth_rt_id, d);
}
}
/// Apply a post-fx pass: read from `input_view`, write to `output_view`.
/// Defaults to REPLACE blend / clear on load. Use `apply_postfx_ex` for
/// additive blend (bloom composite) or load-preserve behavior.
#[allow(clippy::too_many_arguments)]
pub fn apply_postfx(
&mut self,
input_view: &wgpu::TextureView,
output_view: &wgpu::TextureView,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
) {
let fallback_normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let hw_fallback = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
self.apply_postfx_ex(
input_view,
output_view,
input_view,
&fallback_normal,
&hw_fallback,
kind,
time,
params2,
params3,
width,
height,
false,
PostFxCamera::default(),
false,
self.color_format,
!matches!(kind, 4 | 5 | 25 | 26),
);
}
/// Extended post-fx pass with `additive` blend toggle.
#[allow(clippy::too_many_arguments)]
pub fn apply_postfx_ex(
&mut self,
input_view: &wgpu::TextureView,
output_view: &wgpu::TextureView,
depth_view: &wgpu::TextureView,
normal_view: &wgpu::TextureView,
hw_depth_view: &wgpu::TextureView,
kind: u32,
time: f32,
params2: [f32; 4],
params3: [f32; 4],
width: u32,
height: u32,
additive: bool,
camera: PostFxCamera,
use_hw_depth: bool,
output_format: wgpu::TextureFormat,
flip_y: bool,
) {
let linear_output = output_format == wgpu::TextureFormat::Rgba16Float;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct PostFxUniforms {
params: [f32; 4],
params2: [f32; 4],
params3: [f32; 4],
resolution: [f32; 4],
ssao0: [f32; 4],
inv_proj: [f32; 16],
proj: [f32; 16],
}
let uniforms = PostFxUniforms {
params: [
kind as f32,
time,
if kind == 5 || kind == 25 || kind == 26 {
params3[3]
} else {
0.0
},
if use_hw_depth { 1.0 } else { 0.0 },
],
params2,
params3,
resolution: [
width as f32,
height as f32,
if linear_output { 1.0 } else { 0.0 },
if flip_y { 1.0 } else { 0.0 },
],
ssao0: [
camera.near,
camera.far,
camera.kernel_radius,
camera.kernel_size as f32,
],
inv_proj: camera.inv_proj,
proj: camera.proj,
};
let buffer = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers postfx uniforms"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsages::UNIFORM,
},
);
let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers postfx bg"),
layout: &self.postfx_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(input_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.postfx_sampler),
},
wgpu::BindGroupEntry {
binding: 2,
resource: buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(depth_view),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::Sampler(
if kind == 5 || kind == 25 || kind == 26 {
&self.postfx_sampler
} else {
&self.postfx_nearest_sampler
},
),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(normal_view),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView(hw_depth_view),
},
wgpu::BindGroupEntry {
binding: 7,
resource: self.ssao_kernel_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(if kind == 26 {
&self.glitch_snow_view
} else if kind == 5 || kind == 25 {
&self.glitch_disp_view
} else if kind == 3 && params3[3] > 0.5 {
&self.glitch_snow_view
} else {
&self.ssao_noise_view
}),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::Sampler(&self.postfx_noise_sampler),
},
],
});
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers postfx encoder"),
});
{
let multiply = kind == 15;
let load_op = if additive || multiply {
wgpu::LoadOp::Load
} else {
wgpu::LoadOp::Clear(wgpu::Color::BLACK)
};
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers postfx pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: output_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: load_op,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
let output_is_f16 = output_format == wgpu::TextureFormat::Rgba16Float;
let pipe = if multiply {
&self.pipeline_postfx_multiply
} else if additive {
if kind == 17 {
&self.pipeline_postfx_outline_add
} else if output_is_f16 {
&self.pipeline_postfx_add_f16
} else {
&self.pipeline_postfx_add
}
} else if output_is_f16 {
&self.pipeline_postfx_f16
} else {
&self.pipeline_postfx
};
pass.set_pipeline(pipe);
pass.set_bind_group(0, &bind_group, &[]);
pass.draw(0..3, 0..1);
}
self.queue.submit(std::iter::once(encoder.finish()));
}
/// Upload SSAO hemisphere kernel samples (32 vec3 values, padded to vec4).
pub fn set_ssao_kernel(&mut self, kernel: &[f32]) {
let mut data = [0f32; 128];
for i in 0..32 {
let base = i * 3;
if base + 2 < kernel.len() {
data[i * 4] = kernel[base];
data[i * 4 + 1] = kernel[base + 1];
data[i * 4 + 2] = kernel[base + 2];
}
}
self.queue
.write_buffer(&self.ssao_kernel_buffer, 0, bytemuck::cast_slice(&data));
}
/// Upload GLSL-baked dotscreen pattern (R32Float; binding 8 when kind=3 params3.w>0.5).
pub fn set_dotscreen_pattern(&mut self, data: &[f32], width: u32, height: u32) {
self.set_glitch_snow(data, width, height);
}
/// Blit tightly-packed RGBA8 bytes (row-major, top-first) to an output view.
pub fn blit_rgba8(
&mut self,
data: &[u8],
width: u32,
height: u32,
output_view: &wgpu::TextureView,
output_format: wgpu::TextureFormat,
) {
let w = width.max(1);
let h = height.max(1);
let need = (w * h * 4) as usize;
if data.len() < need {
return;
}
if self.rgba_upload_tex.width() != w || self.rgba_upload_tex.height() != h {
self.rgba_upload_tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers rgba upload"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.rgba_upload_view = self
.rgba_upload_tex
.create_view(&wgpu::TextureViewDescriptor::default());
}
const ALIGN: u32 = 256;
let unpadded = w * 4;
let padded = unpadded.div_ceil(ALIGN) * ALIGN;
let mut upload = vec![0u8; (padded * h) as usize];
for row in 0..h {
let src = (row * w * 4) as usize;
let dst = (row * padded) as usize;
upload[dst..dst + (w * 4) as usize].copy_from_slice(&data[src..src + (w * 4) as usize]);
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.rgba_upload_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&upload,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(h),
},
wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
);
let upload_view = self
.rgba_upload_tex
.create_view(&wgpu::TextureViewDescriptor::default());
let fallback_normal = self
.default_normal
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let hw_fallback = self.hw_depth_tex.create_view(&wgpu::TextureViewDescriptor {
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
self.apply_postfx_ex(
&upload_view,
output_view,
&upload_view,
&fallback_normal,
&hw_fallback,
0,
0.0,
[1.0, 0.0, 0.0, 0.0],
[0.0; 4],
w,
h,
false,
PostFxCamera::default(),
false,
output_format,
true,
);
}
/// Drop every cached GPU mesh, freeing their buffers.
///
/// The cache is keyed by the address of the geometry's `Arc`, which is
/// stable only while that `Arc` is alive. Code that feeds the renderer a
/// *fresh* geometry every frame — a CAD model re-evaluated per frame, say —
/// must call this between frames: without it the cache grows without bound,
/// and an allocator that reuses a freed address could serve the old mesh
/// for the new geometry.
///
/// Scenes that keep their geometry alive (the usual case) never need this.
pub fn clear_geometry_cache(&mut self) {
self.geom_cache.clear();
self.skin_attr_cache.clear();
}
/// How many GPU meshes are currently cached.
pub fn cached_geometry_count(&self) -> usize {
self.geom_cache.len()
}
/// Drop every cached GPU texture.
///
/// The texture cache has exactly the same shape, and the same hazard, as
/// the geometry one: it is keyed by the address of the `Texture`'s `Arc`,
/// so code that builds fresh textures every frame must clear it or risk an
/// allocator handing a new texture the address of a freed one and getting
/// the previous upload back.
/// Upload a texture now, without drawing anything with it.
///
/// Textures normally upload lazily, on the first draw that binds them. That
/// is the wrong moment when the pixels are large and numerous: each has to
/// be held in system memory until something draws it, so the peak is the
/// sum of all of them. Preloading one at a time and swapping in
/// [`Texture::handle`] keeps the peak at one.
///
/// ```no_run
/// # use threers::{HeadlessRenderer, Texture, TextureFormat};
/// # use std::sync::Arc;
/// # let mut hr = HeadlessRenderer::builder().size(64, 64).build().unwrap();
/// # let load = |_: &str| Texture::new(1, 1, TextureFormat::Rgba8Unorm, vec![0; 4]);
/// let full = Arc::new(load("tile.tex"));
/// hr.renderer().preload_texture(&full);
/// let light = Arc::new(full.handle()); // same id, no pixels
/// drop(full); // system memory released
/// ```
pub fn preload_texture(&mut self, tex: &std::sync::Arc<crate::textures::Texture>) {
self.ensure_slot_uploaded(&Some(tex.clone()));
}
pub fn clear_texture_cache(&mut self) {
self.tex_cache.clear();
self.cube_cache.clear();
}
/// How many GPU textures are currently cached.
pub fn cached_texture_count(&self) -> usize {
self.tex_cache.len()
}
/// Blend a straight-alpha RGBA8 overlay over an already-rendered target.
///
/// Unlike [`blit_rgba8`](Self::blit_rgba8), which replaces the target, this
/// loads the existing contents and composites `data` on top — the 3D image
/// stays visible wherever the overlay is transparent. `data` must be
/// `width * height * 4` bytes, row-major from the top-left.
///
/// Draw it after [`render`](Self::render) and before presenting the frame.
pub fn draw_overlay_rgba8(
&mut self,
data: &[u8],
width: u32,
height: u32,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
let pass = self
.caption_pass
.get_or_insert_with(|| super::caption_pass::CaptionPass::new(&self.device));
pass.draw(
&self.device,
&self.queue,
data,
width,
height,
target,
format,
);
}
/// Draw the caption showing at `time` seconds over an already-rendered target.
///
/// Sizes the overlay to `target_width × target_height`, rasterizes the
/// active cue only when it changes, and blends it in. Cheap enough to call
/// every frame — a frame with no cue change costs one texture upload, and a
/// frame with no cue at all costs nothing.
///
/// ```no_run
/// # use threers::{Renderer, Scene, PerspectiveCamera, captions::{CaptionOverlay, CaptionTrack}};
/// # fn demo(renderer: &mut Renderer, scene: &mut Scene, camera: &PerspectiveCamera,
/// # view: &wgpu::TextureView, format: wgpu::TextureFormat, time: f64) {
/// let mut overlay = CaptionOverlay::new(CaptionTrack::new().cue(0.0, 3.0, "Hello"))
/// .auto_scale(true);
/// renderer.render(scene, camera, view, false);
/// renderer.draw_caption_overlay(&mut overlay, time, 1280, 720, view, format);
/// # }
/// ```
#[cfg(feature = "captions")]
pub fn draw_caption_overlay(
&mut self,
overlay: &mut crate::captions::CaptionOverlay,
time: f64,
target_width: u32,
target_height: u32,
target: &wgpu::TextureView,
format: wgpu::TextureFormat,
) {
overlay.set_size(target_width, target_height);
overlay.update(time);
if !overlay.is_visible() {
return;
}
let (w, h) = overlay.size();
// Borrow the buffer out of the overlay for the upload; the pass only
// reads it, but the borrow checker needs the copy-free split.
let pass = self
.caption_pass
.get_or_insert_with(|| super::caption_pass::CaptionPass::new(&self.device));
pass.draw(
&self.device,
&self.queue,
overlay.rgba(),
w,
h,
target,
format,
);
}
/// Upload full-screen glitch snow map (R32Float, point-sampled).
pub fn set_glitch_snow(&mut self, data: &[f32], width: u32, height: u32) {
let w = width.max(1);
let h = height.max(1);
if self.glitch_snow_tex.width() != w || self.glitch_snow_tex.height() != h {
self.glitch_snow_tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers glitch snow"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.glitch_snow_view = self
.glitch_snow_tex
.create_view(&wgpu::TextureViewDescriptor::default());
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.glitch_snow_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(data),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(w * 4),
rows_per_image: Some(h),
},
wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
);
}
/// Upload 64×64 glitch displacement heightmap (R32Float; manual bilinear in WGSL).
pub fn set_glitch_disp(&mut self, data: &[f32], size: u32) {
let sz = size.max(1);
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.glitch_disp_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(data),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(sz * 4),
rows_per_image: Some(sz),
},
wgpu::Extent3d {
width: sz,
height: sz,
depth_or_array_layers: 1,
},
);
}
/// Upload 4×4 SSAO rotation noise (R channel, repeat-wrapped).
pub fn set_ssao_noise(&mut self, noise: &[f32]) {
let mut texels = [0f32; 16];
for (dst, src) in texels.iter_mut().zip(noise.iter()) {
*dst = *src;
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.ssao_noise_tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&texels),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(16),
rows_per_image: Some(4),
},
wgpu::Extent3d {
width: 4,
height: 4,
depth_or_array_layers: 1,
},
);
}
/// Render `scene` from `camera` into one face of a cube render target.
/// Used by `CubeCamera.update()` which calls this 6 times per frame.
/// Reallocate the directional shadow map if a caster asks for a different
/// size. Powers of two only, and bounded: this is a render target, and a
/// caller who types 65536 should get the largest sane map rather than an
/// allocation failure three frames later.
fn ensure_shadow_size(&mut self, requested: u32) {
let size = requested.clamp(256, 8192).next_power_of_two();
if size == self.shadow_size {
return;
}
let tex = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers shadow depth"),
size: wgpu::Extent3d {
width: size,
height: size,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
self.shadow_view = tex.create_view(&wgpu::TextureViewDescriptor::default());
self.shadow_size = size;
// The environment bind group holds the old view. Invalidating the cache
// key is what makes the next frame rebuild it; without this the shader
// would keep sampling a texture nothing renders into any more.
self.env_cached_key = None;
self.env_cached_rt_id = None;
self.env_dirty = true;
}
pub fn render_to_cube_face(
&mut self,
scene: &mut crate::scene::Scene,
camera: &dyn Camera,
target: &super::CubeRenderTarget,
face: usize,
) {
// Tell the frame passes they are drawing a probe, not the picture.
let was_cube = std::mem::replace(&mut self.cube_pass, true);
let (orig_w, orig_h) = self.depth_size;
let orig_depth = std::mem::replace(
&mut self.depth_view,
target
.depth_texture
.create_view(&wgpu::TextureViewDescriptor::default()),
);
self.depth_size = (target.side, target.side);
let face_view = &target.face_views[face % 6];
self.render(scene, camera, face_view, false);
self.depth_view = orig_depth;
self.depth_size = (orig_w, orig_h);
self.cube_pass = was_cube;
}
/// Render `scene` from `camera` into an offscreen [`RenderTarget`](crate::RenderTarget). Uses
/// the target's own depth buffer (required even when RT size matches the canvas).
pub fn render_to(
&mut self,
scene: &mut crate::scene::Scene,
camera: &dyn Camera,
target: &super::RenderTarget,
) {
let (orig_w, orig_h) = self.depth_size;
let orig_depth = std::mem::replace(&mut self.depth_view, target.depth_view_clone());
self.depth_size = (target.width, target.height);
let linear_fb = target.format == wgpu::TextureFormat::Rgba16Float;
// The target owns the live depth this pass — pass it as the copy source
// for the screen-space glass ray march.
self.render_inner(
scene,
camera,
&target.color_view,
linear_fb,
Some(&target.depth_texture),
Some(&target.color_texture),
);
self.depth_view = orig_depth;
self.depth_size = (orig_w, orig_h);
}
/// Draw `scene` from `camera` into `target_view`.
/// `linear_framebuffer`: when true, skip sRGB encode (HalfFloat / postfx RT).
pub fn render(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
target_view: &wgpu::TextureView,
linear_framebuffer: bool,
) {
self.render_inner(scene, camera, target_view, linear_framebuffer, None, None);
}
/// Body of [`render`]. `depth_src` is the depth texture backing the current
/// depth attachment (the external target's, via `render_to`) — the copy
/// source for the screen-space glass `ss_depth`; `None` uses the renderer's
/// own depth (the direct-`render`/surface path).
fn render_inner(
&mut self,
scene: &mut Scene,
camera: &dyn Camera,
target_view: &wgpu::TextureView,
linear_framebuffer: bool,
depth_src: Option<&wgpu::Texture>,
color_src: Option<&wgpu::Texture>,
) {
scene.update_world();
// TAA active only when we have a sampleable color+depth target.
// NOT during a probe. A cube face is 48 pixels and is not the picture:
// running temporal AA over it reprojects the frame's history through
// the probe's camera and writes the result back, so the next real frame
// blends against six tiny views of the scene. On screen that reads as
// the whole vehicle going half transparent — which is what it looked
// like, and why the cause was not obvious from the symptom.
let taa_active =
self.taa_enabled && !self.cube_pass && color_src.is_some() && depth_src.is_some();
let view_m = camera.view_matrix();
let mut proj_m = camera.projection_matrix();
// Un-jittered view-projection is kept for TAA reprojection.
let unjittered = proj_m.multiply(&view_m);
if taa_active {
// Sub-pixel Halton jitter in NDC (± half a pixel).
let jx = (halton(self.taa_frame + 1, 2) - 0.5) * 2.0 / self.depth_size.0 as f32;
let jy = (halton(self.taa_frame + 1, 3) - 0.5) * 2.0 / self.depth_size.1 as f32;
proj_m.elements[8] += jx;
proj_m.elements[9] += jy;
}
let view_proj = proj_m.multiply(&view_m).elements;
let taa_inv_vp = unjittered.invert().elements;
let taa_unjittered_vp = unjittered.elements;
// tone_mapping_exposure[2] is the "IBL on" flag — the PBR shader's
// env-map branch is gated on it. Enable whenever the scene has any
// environment source (CPU cube texture or cube render target).
let has_env = scene.environment.is_some() || scene.environment_cube_rt.is_some();
let (cam_near, cam_far) = camera.near_far();
let mut frame_u = FrameUniforms {
view: view_m.elements,
projection: proj_m.elements,
view_proj,
camera_position: [
camera.position().x,
camera.position().y,
camera.position().z,
0.0,
],
fog_color: [scene.fog.color.r, scene.fog.color.g, scene.fog.color.b, 1.0],
fog_params: [
scene.fog.near,
scene.fog.far,
scene.fog.density,
scene.fog.mode as f32,
],
tone_mapping_exposure: [
self.tone_mapping.shader_mode(),
self.exposure,
if has_env { 1.0 } else { 0.0 },
if linear_framebuffer { 1.0 } else { 0.0 },
],
viewport_size: [
self.depth_size.0 as f32,
self.depth_size.1 as f32,
cam_near,
cam_far,
],
..FrameUniforms::default()
};
let mut ambient = [0.0_f32; 3];
let mut n_dir = 0usize;
let mut n_point = 0usize;
let mut n_spot = 0usize;
let mut n_hemi = 0usize;
let mut n_rect = 0usize;
let mut shadow_caster: Option<(Vector3, crate::lights::ShadowSettings)> = None;
let mut spot_caster: Option<(Vector3, Vector3, f32, crate::lights::ShadowSettings)> = None;
let mut point_caster: Option<(Vector3, f32, crate::lights::ShadowSettings)> = None;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Topology {
Triangle,
TriangleAlpha,
TriangleWire,
TriangleNoCull,
Sky,
Line,
#[allow(dead_code)]
Point,
Sprite,
Instanced,
Skinned,
/// Single-layer glass depth prepass (writes depth, no color).
GlassDepth,
/// Single-layer glass color pass (LessEqual, alpha blend, no depth write).
GlassColor,
/// Weighted-blended OIT surface (drawn into accum+revealage MRT).
Oit,
/// Screen-space refraction glass (drawn in a dedicated pass that
/// samples the captured opaque color + depth).
Refract,
/// Custom-shader material:
/// (fragment-source hash, is-transparent, wants-screen-space).
/// The last flag moves the draw into the screen-space pass, where the
/// captured opaque colour and depth are bound at `@group(3)`.
Custom(u64, bool, bool, u32),
}
struct DrawMesh {
key: *const BufferGeometry,
topology: Topology,
/// Z in view space, used to back-to-front sort transparent draws.
view_z: f32,
render_order: i32,
cast_shadow: bool,
refract_capture: bool,
alpha_test: f32,
model: [f32; 16],
normal_matrix: [f32; 16],
color: [f32; 4],
emissive: [f32; 4],
specular: [f32; 4],
shininess_or_near: f32,
opacity_or_far: f32,
roughness: f32,
metalness: f32,
ao_intensity: f32,
normal_scale: [f32; 2],
toon_steps: u32,
physical: [f32; 4],
physical2: [f32; 4],
physical3: [f32; 4],
physical4: [f32; 4],
physical5: [f32; 4],
displacement: [f32; 4],
uv_transform: [f32; 4],
atmos: [f32; 4],
twilight: [f32; 4],
eclipse: [f32; 4],
scatter: [f32; 4],
aurora: [f32; 4],
shader_flags: u32,
kind: MaterialKind,
slots: MaterialTextureSlots,
/// Index into `instance_buffers` for Topology::Instanced.
instance_buf_idx: usize,
instance_count: u32,
/// Index into `skin_data` for Topology::Skinned.
skin_idx: usize,
/// Index into `shader_data` for Topology::Custom.
shader_idx: usize,
}
let mut draws: Vec<DrawMesh> = Vec::new();
// Per-custom-shader-material draw data (parallel to Topology::Custom).
struct ShaderDrawData {
fragment: String,
data: [[f32; 4]; 16],
storage: [Vec<f32>; 3],
textures: Vec<std::sync::Arc<wgpu::TextureView>>,
}
let mut shader_data: Vec<ShaderDrawData> = Vec::new();
let mut instance_buffers: Vec<wgpu::Buffer> = Vec::new();
struct SkinData {
bone_buf: wgpu::Buffer,
bg: Option<wgpu::BindGroup>,
}
let mut skin_data: Vec<SkinData> = Vec::new();
// Helper: build a DrawMesh from a geometry+material pair under a given topology.
let make_draw = |geom: &std::sync::Arc<BufferGeometry>,
mat: &Material,
obj: &crate::core::Object3D,
topology: Topology|
-> DrawMesh {
let key = geom_cache_key(geom);
let nm3 = Matrix3::normal_matrix(&obj.matrix_world);
// Mirror materials repurpose the normal_matrix slot for the
// projective texture matrix supplied per-frame from JS.
let normal_matrix = match mat {
Material::Mirror(m) => m.texture_matrix,
_ => mat3_to_mat4_array(&nm3),
};
// Promote Triangle to TriangleAlpha / TriangleWire based on material
// flags. Pre-set view_z for later sort.
let world_pos = obj.world_position();
let view_z = view_m.elements[2] * world_pos.x
+ view_m.elements[6] * world_pos.y
+ view_m.elements[10] * world_pos.z
+ view_m.elements[14];
let topology = if topology == Topology::Triangle {
if matches!(mat, Material::Sky(_)) {
Topology::Sky
} else if mat.wireframe() {
Topology::TriangleWire
} else if mat.transparent() {
Topology::TriangleAlpha
} else if mat.side() != 0 {
Topology::TriangleNoCull
} else {
Topology::Triangle
}
} else {
topology
};
let c = mat.color();
let e = mat.emissive();
// For MeshDistanceMaterial, pack the reference position into the
// specular channel (unused by that path) so the shader can read it.
// For SkyMaterial, pack the sun position into specular.
let s = match mat {
Material::Distance(m) => crate::math::Color::new(
m.reference_position.x,
m.reference_position.y,
m.reference_position.z,
),
Material::Sky(m) => {
crate::math::Color::new(m.sun_position.x, m.sun_position.y, m.sun_position.z)
}
_ => mat.specular(),
};
// For SkyMaterial, pack atmospheric tuning into params.x/y (replacing
// shininess/opacity which it doesn't use).
let (shin_or_near, opacity_or_far) = match mat {
Material::Depth(m) => (m.near, m.far),
Material::Distance(m) => (m.near_distance, m.far_distance),
Material::Sky(m) => (m.turbidity, m.rayleigh),
_ => (mat.shininess(), mat.opacity()),
};
let physical = match mat {
Material::Physical(m) => {
[m.clearcoat, m.clearcoat_roughness, m.ior, m.transmission]
}
Material::Line(m) => [m.dash_scale, m.dash_size, m.gap_size, 0.0],
// The atmosphere shader intersects the view ray with both
// spheres, so it needs their radii rather than a surface
// description.
Material::Atmosphere(m) => {
[m.planet_radius, m.atmosphere_radius, m.intensity, m.falloff]
}
_ => [0.0; 4],
};
let physical2 = match mat {
Material::Physical(m) => [
m.thickness,
m.dispersion,
m.vertex_emissive,
m.anisotropy_rotation,
],
Material::Atmosphere(m) => [
m.sunset_color.r,
m.sunset_color.g,
m.sunset_color.b,
m.airglow,
],
_ => [0.0; 4],
};
let physical3 = match mat {
Material::Physical(m) => [
m.iridescence,
m.iridescence_ior,
m.iridescence_thickness,
m.sheen,
],
Material::Atmosphere(m) => {
[m.airglow_color.r, m.airglow_color.g, m.airglow_color.b, 0.0]
}
_ => [0.0; 4],
};
let physical4 = match mat {
Material::Physical(m) => [
m.sheen_color.r,
m.sheen_color.g,
m.sheen_color.b,
m.sheen_roughness,
],
_ => [0.0; 4],
};
let physical5 = match mat {
Material::Physical(m) => {
// attenuation_distance defaults to INFINITY. Feeding that to
// the GPU makes the Beer-Lambert coefficient -log(c)/inf,
// which is 0 for c>0 but NaN for a fully-black channel — and
// one NaN poisons the whole fragment. Collapse any
// non-finite/non-positive distance to 0, the shader's
// "absorption disabled" sentinel.
let dist = if m.attenuation_distance.is_finite() && m.attenuation_distance > 0.0
{
m.attenuation_distance
} else {
0.0
};
[
m.attenuation_color.r,
m.attenuation_color.g,
m.attenuation_color.b,
dist,
]
}
_ => [0.0; 4],
};
let displacement = {
let (scale, bias) = mat.displacement();
let night = mat.emissive_night_side();
[scale, bias, night, 0.0]
};
// three.js drives every slot from one texture matrix, taken from
// the primary map. Ours is the offset/repeat pair, which is the
// part that matters for atlasing and tiling. It is applied once, in
// the vertex stage, so it covers every slot — a material cannot
// window its normal map and leave its albedo alone.
let uv_transform = {
let slots = mat.texture_slots();
let t = slots.map.as_ref().or(slots.matcap_map.as_ref());
match t {
Some(t) => [t.offset.x, t.offset.y, t.repeat.x, t.repeat.y],
None => [0.0, 0.0, 1.0, 1.0],
}
};
let atmos = mat.atmosphere_params();
let (eclipse, sun_angle) = mat.eclipse();
let twilight = {
let c = mat.twilight_color();
[c.r, c.g, c.b, sun_angle]
};
let scatter = mat.scatter_params();
let aurora = mat.aurora_params();
let mut shader_flags = match mat {
Material::Line(m) if m.dash_size > 0.0 || m.gap_size > 0.0 => FLAG_DASHED,
Material::Basic(m) if m.shadow_only => FLAG_SHADOW_MAT,
_ => 0,
};
if obj.receive_shadow {
shader_flags |= FLAG_RECEIVE_SHADOW;
}
DrawMesh {
key,
topology,
view_z,
render_order: obj.render_order,
cast_shadow: obj.cast_shadow,
refract_capture: obj.refract_capture,
alpha_test: mat.alpha_test(),
model: obj.matrix_world.elements,
normal_matrix,
color: [c.r, c.g, c.b, mat.opacity()],
// emissive.w carries the physical-material anisotropy strength
// (0 = isotropic); the shader stretches the specular lobe along
// the surface tangent by this amount. Non-physical mats leave 0.
emissive: [
e.r,
e.g,
e.b,
match mat {
Material::Physical(m) => m.anisotropy,
_ => 0.0,
},
],
specular: [s.r, s.g, s.b, 0.0],
shininess_or_near: shin_or_near,
opacity_or_far,
// For SkyMaterial, repurpose roughness/metalness as
// params.z/w (mieCoefficient/mieDirectionalG).
roughness: match mat {
Material::Sky(m) => m.mie_coefficient,
_ => mat.roughness(),
},
metalness: match mat {
Material::Sky(m) => m.mie_directional_g,
_ => mat.metalness(),
},
ao_intensity: mat.ao_intensity(),
normal_scale: [mat.normal_scale().x, mat.normal_scale().y],
toon_steps: mat.toon_steps(),
physical,
physical2,
physical3,
physical4,
physical5,
displacement,
uv_transform,
atmos,
twilight,
eclipse,
scatter,
aurora,
shader_flags,
kind: mat.kind(),
slots: mat.texture_slots(),
instance_buf_idx: usize::MAX,
instance_count: 1,
skin_idx: usize::MAX,
shader_idx: usize::MAX,
}
};
let cam_layers = camera.layers();
let root = scene.root;
scene.arena.traverse_visible(root, &mut |_id, obj| {
if !cam_layers.test(&obj.layers) {
return;
}
match &obj.kind {
ObjectKind::Light(light) => match light {
Light::Ambient(l) => {
ambient[0] += l.color.r * l.intensity;
ambient[1] += l.color.g * l.intensity;
ambient[2] += l.color.b * l.intensity;
}
Light::Directional(l) => {
if n_dir >= MAX_DIR_LIGHTS {
return;
}
// three.js: direction = normalize(target - position); default target (0,0,0).
let pos = obj.world_position();
let dir = {
let d = Vector3::new(-pos.x, -pos.y, -pos.z);
if d.length_sq() > 1e-8 {
d.normalize()
} else {
transform_direction(&obj.matrix_world, l.direction).normalize()
}
};
let c = l.color;
frame_u.dir_lights[n_dir] = DirLightGpu {
direction: [dir.x, dir.y, dir.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
};
// First cast_shadow dir light becomes the shadow caster.
if l.cast_shadow && n_dir == 0 && shadow_caster.is_none() {
shadow_caster = Some((dir, l.shadow));
}
n_dir += 1;
}
Light::Point(l) => {
if n_point >= MAX_POINT_LIGHTS {
return;
}
let p = obj.world_position();
let c = l.color;
frame_u.point_lights[n_point] = PointLightGpu {
position: [p.x, p.y, p.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
params: [l.distance, l.decay, 0.0, 0.0],
};
if l.cast_shadow && n_point == 0 && point_caster.is_none() {
let radius = if l.distance > 0.0 { l.distance } else { 50.0 };
point_caster = Some((p, radius, l.shadow));
}
n_point += 1;
}
Light::Spot(l) => {
if n_spot >= MAX_SPOT_LIGHTS {
return;
}
let p = obj.world_position();
let dir = transform_direction(&obj.matrix_world, l.direction).normalize();
let c = l.color;
let cos_outer = l.angle.cos();
let cos_inner = (l.angle * (1.0 - l.penumbra)).cos();
frame_u.spot_lights[n_spot] = SpotLightGpu {
position: [p.x, p.y, p.z, 0.0],
direction: [dir.x, dir.y, dir.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
params: [l.distance, l.decay, cos_outer, cos_inner],
};
if l.cast_shadow && n_spot == 0 && spot_caster.is_none() {
spot_caster = Some((p, dir, l.angle, l.shadow));
}
n_spot += 1;
}
Light::Hemisphere(l) => {
if n_hemi >= MAX_HEMI_LIGHTS {
return;
}
let up = transform_direction(&obj.matrix_world, Vector3::UP).normalize();
frame_u.hemi_lights[n_hemi] = HemiLightGpu {
sky_color: [
l.sky_color.r * l.intensity,
l.sky_color.g * l.intensity,
l.sky_color.b * l.intensity,
0.0,
],
ground_color: [
l.ground_color.r * l.intensity,
l.ground_color.g * l.intensity,
l.ground_color.b * l.intensity,
0.0,
],
direction: [up.x, up.y, up.z, 0.0],
};
n_hemi += 1;
}
Light::RectArea(l) => {
if n_rect >= MAX_RECT_LIGHTS {
return;
}
// three.js orients a RectAreaLight by its matrixWorld:
// width runs along local +X, height along local +Y, and
// the emitting face looks down local -Z. Store half
// extents so the shader can form corners by ± directly.
let pos = obj.world_position();
let right = transform_direction(
&obj.matrix_world,
Vector3::new(l.width * 0.5, 0.0, 0.0),
);
let up = transform_direction(
&obj.matrix_world,
Vector3::new(0.0, l.height * 0.5, 0.0),
);
let c = l.color;
frame_u.rect_lights[n_rect] = RectLightGpu {
position: [pos.x, pos.y, pos.z, 0.0],
color: [c.r * l.intensity, c.g * l.intensity, c.b * l.intensity, 0.0],
right: [right.x, right.y, right.z, 0.0],
up: [up.x, up.y, up.z, 0.0],
};
n_rect += 1;
}
},
ObjectKind::Mesh(mesh) => {
self.ensure_geometry(&mesh.geometry);
let mut d = make_draw(&mesh.geometry, &mesh.material, obj, Topology::Triangle);
// Custom-shader material: route to a per-source pipeline and
// stash its user data for the @group(4) bind group.
if let Material::Shader(sm) = &*mesh.material {
let hash = custom_shader_hash(&sm.fragment);
let transparent = sm.transparent || sm.opacity < 1.0;
d.topology = Topology::Custom(hash, transparent, sm.screen_space, sm.side);
d.shader_idx = shader_data.len();
let pad = |s: &Vec<f32>| {
if s.is_empty() {
vec![0.0f32]
} else {
s.clone()
}
};
shader_data.push(ShaderDrawData {
fragment: sm.fragment.clone(),
data: sm.data_slots(),
storage: [pad(&sm.storage0), pad(&sm.storage1), pad(&sm.storage2)],
textures: sm.textures.clone(),
});
}
// Route transparent PhysicalMaterials to single-layer glass
// (depth prepass + color) or weighted-blended OIT.
if d.topology == Topology::TriangleAlpha {
match mesh.material.transparency_mode() {
crate::materials::TransparencyMode::Glass => {
draws.push(make_draw(
&mesh.geometry,
&mesh.material,
obj,
Topology::GlassDepth,
));
d.topology = Topology::GlassColor;
}
crate::materials::TransparencyMode::Oit => d.topology = Topology::Oit,
crate::materials::TransparencyMode::Refract => {
d.topology = Topology::Refract
}
crate::materials::TransparencyMode::Blend => {}
}
}
draws.push(d);
}
ObjectKind::LineSegments(ls) => {
self.ensure_geometry(&ls.geometry);
draws.push(make_draw(&ls.geometry, &ls.material, obj, Topology::Line));
}
ObjectKind::Points(p) => {
// three.js's PointsMaterial.size is a screen-space pixel
// size. WebGPU's PointList topology can't honor that —
// it always renders 1 fragment per point. We instead emit
// one camera-facing sprite-style draw per point, sized to
// match three.js's pixel-space convention.
let positions = p.geometry.get_attribute("position");
let size = match &*p.material {
crate::Material::Points(pm) => pm.size,
_ => 1.0,
};
let mat = &*p.material;
let nm3 = Matrix3::normal_matrix(&obj.matrix_world);
let c = mat.color();
if let Some(positions) = positions {
// three.js renders points as `size`-pixel squares via
// `gl_PointSize`. WebGPU has no per-vertex point size, so
// we emit a sprite quad. The sprite vertex shader scales
// by the model matrix's basis lengths and applies the
// perspective projection — so for the right at-distance
// size we work backwards from the desired NDC width.
//
// For a perspective camera, an object at view-z `vz` has
// a world-space width of `2 * vz / proj[0][0]` per unit
// of NDC. We want a sprite of `size` pixels wide on
// an 800-wide canvas (= size/400 NDC), so the model
// matrix's X basis length should be:
// sx = (size / 400) * vz / proj[0][0]
let viewport_h = 600.0_f32;
let proj00 = proj_m.elements[0];
let canvas_w = 800.0_f32;
let _ = viewport_h;
let cnt = positions.count();
for vi in 0..cnt {
let px = positions.array[vi * 3];
let py = positions.array[vi * 3 + 1];
let pz = positions.array[vi * 3 + 2];
let m_local = crate::math::Matrix4::translation(
crate::math::Vector3::new(px, py, pz),
);
let mut model = obj.matrix_world.multiply(&m_local);
// Project the point centre to view space to get its z, then
// size the quad to match the requested pixel size at that depth.
let wp = crate::math::Vector3::new(
model.elements[12],
model.elements[13],
model.elements[14],
);
let vz = (view_m.elements[2] * wp.x
+ view_m.elements[6] * wp.y
+ view_m.elements[10] * wp.z
+ view_m.elements[14])
.abs()
.max(0.0001);
let half_ndc = (size / canvas_w) * vz / proj00;
// Sprite vs uses `in.position * sx`; the unit quad has corners
// at ±0.5, so we want sx == size_in_world. Multiply by 2 because
// pixel size means total quad width, not half.
let sx = half_ndc * 2.0;
let mut e = model.elements;
for k in 0..3 {
e[k] *= sx;
e[4 + k] *= sx;
}
model.elements = e;
let world_pos = crate::math::Vector3::new(e[12], e[13], e[14]);
let svz = view_m.elements[2] * world_pos.x
+ view_m.elements[6] * world_pos.y
+ view_m.elements[10] * world_pos.z
+ view_m.elements[14];
draws.push(DrawMesh {
key: std::ptr::null::<BufferGeometry>(),
topology: Topology::Sprite,
view_z: svz,
render_order: obj.render_order,
cast_shadow: false,
refract_capture: true,
alpha_test: 0.0,
model: model.elements,
normal_matrix: mat3_to_mat4_array(&nm3),
color: [c.r, c.g, c.b, mat.opacity()],
emissive: [0.0; 4],
specular: [0.0; 4],
shininess_or_near: 0.0,
opacity_or_far: mat.opacity(),
roughness: 1.0,
metalness: 0.0,
ao_intensity: 1.0,
normal_scale: [1.0, 1.0],
toon_steps: 0,
physical: [0.0; 4],
physical2: [0.0; 4],
physical3: [0.0; 4],
physical4: [0.0; 4],
physical5: [0.0; 4],
displacement: [0.0; 4],
uv_transform: [0.0, 0.0, 1.0, 1.0],
atmos: [0.0; 4],
twilight: [0.0; 4],
eclipse: [0.0; 4],
scatter: [0.0; 4],
aurora: [0.0; 4],
shader_flags: 0,
kind: crate::materials::MaterialKind::Basic,
slots: mat.texture_slots(),
instance_buf_idx: usize::MAX,
instance_count: 1,
skin_idx: usize::MAX,
shader_idx: usize::MAX,
});
}
}
}
ObjectKind::Sprite(sprite) => {
// Inline construction — the sprite quad is built-in, so we
// can't reuse make_draw (which keys off an Arc<BufferGeometry>).
let mat = &*sprite.material;
let nm3 = Matrix3::normal_matrix(&obj.matrix_world);
let c = mat.color();
let sp = obj.world_position();
let svz = view_m.elements[2] * sp.x
+ view_m.elements[6] * sp.y
+ view_m.elements[10] * sp.z
+ view_m.elements[14];
draws.push(DrawMesh {
key: std::ptr::null::<BufferGeometry>(),
topology: Topology::Sprite,
view_z: svz,
render_order: obj.render_order,
cast_shadow: false,
refract_capture: true,
alpha_test: 0.0,
model: obj.matrix_world.elements,
normal_matrix: mat3_to_mat4_array(&nm3),
color: [c.r, c.g, c.b, mat.opacity()],
emissive: [0.0; 4],
specular: [0.0; 4],
shininess_or_near: 0.0,
opacity_or_far: mat.opacity(),
roughness: 1.0,
metalness: 0.0,
ao_intensity: 1.0,
normal_scale: [1.0, 1.0],
toon_steps: 0,
physical: [0.0; 4],
physical2: [0.0; 4],
physical3: [0.0; 4],
physical4: [0.0; 4],
physical5: [0.0; 4],
displacement: [0.0; 4],
uv_transform: [0.0, 0.0, 1.0, 1.0],
atmos: [0.0; 4],
twilight: [0.0; 4],
eclipse: [0.0; 4],
scatter: [0.0; 4],
aurora: [0.0; 4],
shader_flags: 0,
kind: mat.kind(),
slots: mat.texture_slots(),
instance_buf_idx: usize::MAX,
instance_count: 1,
skin_idx: usize::MAX,
shader_idx: usize::MAX,
});
}
ObjectKind::InstancedMesh(im) => {
self.ensure_geometry(&im.geometry);
if im.transforms.is_empty() {
return;
}
let mut matrices: Vec<f32> = Vec::with_capacity(im.transforms.len() * 16);
for t in &im.transforms {
matrices.extend_from_slice(&t.elements);
}
let buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers instance buffer"),
contents: bytemuck::cast_slice(&matrices),
usage: wgpu::BufferUsages::VERTEX,
},
);
let idx = instance_buffers.len();
instance_buffers.push(buf);
let mut d = make_draw(&im.geometry, &im.material, obj, Topology::Instanced);
d.instance_buf_idx = idx;
d.instance_count = im.transforms.len() as u32;
draws.push(d);
}
ObjectKind::SkinnedMesh(sm) => {
self.ensure_geometry(&sm.geometry);
let key = geom_cache_key(&sm.geometry);
// Upload joints+weights to slot-1 vertex buffer (cached per-geometry).
if !self.skin_attr_cache.contains_key(&key) {
let joints = sm.geometry.get_attribute("joint");
let weights = sm.geometry.get_attribute("weight");
let (Some(j), Some(w)) = (joints, weights) else {
// Geometry isn't skin-equipped; draw at rest.
draws.push(make_draw(
&sm.geometry,
&sm.material,
obj,
Topology::Triangle,
));
return;
};
let count = j.count();
let mut interleaved: Vec<f32> = Vec::with_capacity(count * 8);
for i in 0..count {
interleaved.extend_from_slice(&j.array[i * 4..i * 4 + 4]);
interleaved.extend_from_slice(&w.array[i * 4..i * 4 + 4]);
}
let buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers skin attrs"),
contents: bytemuck::cast_slice(&interleaved),
usage: wgpu::BufferUsages::VERTEX,
},
);
self.skin_attr_cache.insert(key, buf);
}
// Upload bone matrices (per-frame, per-skinned-mesh).
let mut bone_data: Vec<f32> =
Vec::with_capacity(sm.skeleton.bone_matrices.len() * 16);
if sm.skeleton.bone_matrices.is_empty() {
// Identity fallback to keep storage buffer non-empty.
let id = crate::math::Matrix4::identity();
bone_data.extend_from_slice(&id.elements);
} else {
for m in &sm.skeleton.bone_matrices {
bone_data.extend_from_slice(&m.elements);
}
}
let bone_buf = wgpu::util::DeviceExt::create_buffer_init(
&*self.device,
&wgpu::util::BufferInitDescriptor {
label: Some("threers bone matrices"),
contents: bytemuck::cast_slice(&bone_data),
usage: wgpu::BufferUsages::STORAGE,
},
);
// Defer creating the combined mesh+skin bind group until
// after per_mesh is populated below — we need the per-mesh
// uniform buffer at binding 0.
let idx = skin_data.len();
skin_data.push(SkinData { bone_buf, bg: None });
let mut d = make_draw(&sm.geometry, &sm.material, obj, Topology::Skinned);
d.skin_idx = idx;
draws.push(d);
}
ObjectKind::Group => {}
}
});
// Sort: opaque first (stable order), then transparents back-to-front so
// alpha blending composites correctly. Sprites are already alpha-blended
// and we treat them as transparent for ordering purposes.
// Draw order class: opaque(0) → glass depth prepass(1) → glass color(2) →
// ordinary alpha & OIT(3). Glass must run after opaque (so its prepass
// sees opaque depth) and before ordinary alpha (which blends over it).
fn ord_class(t: Topology) -> u8 {
match t {
Topology::GlassDepth => 1,
Topology::GlassColor => 2,
Topology::TriangleAlpha | Topology::Sprite | Topology::Oit | Topology::Refract => 3,
Topology::Custom(_, transparent, ..) if transparent => 3,
_ => 0,
}
}
draws.sort_by(|a, b| {
ord_class(a.topology)
.cmp(&ord_class(b.topology))
.then(a.render_order.cmp(&b.render_order))
.then_with(|| {
// For ordinary transparents we want farther-from-camera first.
// view_z is negative in front of the camera; smaller = farther.
if ord_class(a.topology) == 3 {
a.view_z
.partial_cmp(&b.view_z)
.unwrap_or(std::cmp::Ordering::Equal)
} else {
std::cmp::Ordering::Equal
}
})
});
frame_u.ambient = [ambient[0], ambient[1], ambient[2], 0.0];
frame_u.light_counts = [n_dir as u32, n_point as u32, n_spot as u32, n_hemi as u32];
frame_u.light_counts2 = [n_rect as u32, 0, 0, 0];
// Shadow VP: orthographic from the caster light's direction. Camera fits
// a fixed cube centered on the world origin (matches the default
// ShadowSettings.camera_size). For a richer integration the box would
// track the visible meshes' AABB.
if let Some((dir, settings)) = shadow_caster {
// The map is allocated before any light exists to ask for a size,
// so the first frame that names one reallocates. `map_size` used to
// be read and discarded, which is a worse failure than not offering
// it: the caller sets 4096, sees no error, and gets 1024.
self.ensure_shadow_size(settings.map_size);
frame_u.shadow_texel[0] = 1.0 / self.shadow_size as f32;
let s = settings.camera_size;
let light_eye = -dir.normalize() * (s * 1.5);
let light_view = Matrix4::look_at(light_eye, Vector3::ZERO, Vector3::UP);
let light_proj =
Matrix4::orthographic(-s, s, s, -s, settings.camera_near, settings.camera_far);
let light_vp = light_proj.multiply(&light_view);
frame_u.shadow_vp = light_vp.elements;
frame_u.shadow_params[0] = 1.0;
frame_u.shadow_params[1] = settings.bias.max(0.0);
// `normal_bias` was declared, documented and then never read — the
// same failure the `map_size` note above describes. It is read now.
frame_u.shadow_texel[1] = settings.normal_bias.max(0.0);
}
if let Some((pos, radius, _settings)) = point_caster {
frame_u.point_shadow_pos = [pos.x, pos.y, pos.z, radius];
}
if let Some((pos, dir, angle, settings)) = spot_caster {
let target = pos + dir.normalize();
let light_view = Matrix4::look_at(pos, target, Vector3::UP);
// Perspective frustum: fov = 2 * outer_angle to cover the cone.
let fov = (angle * 2.0).clamp(0.05, std::f32::consts::PI - 0.05);
let light_proj =
Matrix4::perspective(fov, 1.0, settings.camera_near, settings.camera_far);
let light_vp = light_proj.multiply(&light_view);
frame_u.spot_shadow_vp = light_vp.elements;
frame_u.shadow_params[2] = 1.0;
frame_u.shadow_params[3] = settings.bias.max(0.0);
}
// Sync environment cubemap. Upload on first sight, rebuild bind group on change.
let env_key = scene.environment.as_ref().map(cube_cache_key);
let env_rt_id = scene.environment_cube_rt;
if self.env_dirty || env_key != self.env_cached_key || env_rt_id != self.env_cached_rt_id {
let mut env_map_params = [0.0_f32; 4];
if let Some(env) = &scene.environment {
let k = cube_cache_key(env);
if !self.cube_cache.contains_key(&k) {
let gc = GpuCubeTexture::upload(&self.device, &self.queue, env);
self.cube_cache.insert(k, gc);
}
if let Some(atlas) = &env.cube_uv_atlas {
env_map_params = [
atlas.texel_width,
atlas.texel_height,
atlas.lod_max as f32,
1.0,
];
}
}
frame_u.env_map_params = env_map_params;
let cube_uv_view: &wgpu::TextureView = if let Some(env) = &scene.environment {
self.cube_cache
.get(&cube_cache_key(env))
.and_then(|gc| gc.cube_uv_view.as_ref())
.unwrap_or(&self.default_cube_uv_view)
} else {
&self.default_cube_uv_view
};
let view: &wgpu::TextureView = if let Some(rt_id) = scene.environment_cube_rt {
self.cube_rt_view_cache
.get(&rt_id)
.unwrap_or(&self.default_env_cube.view)
} else if let Some(env) = &scene.environment {
&self.cube_cache[&cube_cache_key(env)].view
} else {
&self.default_env_cube.view
};
self.env_bind_group = env_bind_group!(
self.device,
&self.env_bgl,
"threers env bg",
view,
&self.env_sampler,
&self.shadow_view,
&self.shadow_sampler,
&self.spot_shadow_view,
&self.spot_shadow_sampler,
&self.point_shadow_cube_view,
&self.point_shadow_sampler,
cube_uv_view,
&self.default_cube_uv_view,
&self.ss_glass_sampler,
&self.ss_depth_placeholder_view,
&self.ss_depth_placeholder_view,
);
self.env_dirty = false;
self.env_cached_key = env_key;
self.env_cached_rt_id = env_rt_id;
}
if let Some(env) = &scene.environment {
if let Some(atlas) = &env.cube_uv_atlas {
frame_u.env_map_params = [
atlas.texel_width,
atlas.texel_height,
atlas.lod_max as f32,
1.0,
];
}
}
// -- Ensure every texture referenced in this frame is uploaded. --
for d in &draws {
self.ensure_slot_uploaded(&d.slots.map);
self.ensure_slot_uploaded(&d.slots.normal_map);
self.ensure_slot_uploaded(&d.slots.roughness_map);
self.ensure_slot_uploaded(&d.slots.metalness_map);
self.ensure_slot_uploaded(&d.slots.ao_map);
self.ensure_slot_uploaded(&d.slots.emissive_map);
self.ensure_slot_uploaded(&d.slots.matcap_map);
self.ensure_slot_uploaded(&d.slots.displacement_map);
self.ensure_slot_uploaded(&d.slots.cloud_shadow_map);
}
// -- Ensure pool capacity. --
while self.per_mesh.len() < draws.len() {
let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("threers mesh uniform"),
size: std::mem::size_of::<MeshUniforms>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mesh_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers mesh bg"),
layout: &self.mesh_bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buf.as_entire_binding(),
}],
});
// Texture bind group is rebuilt per-frame per-mesh below, but we
// need a placeholder; we'll overwrite the pool entry in-place each
// frame. Build a "default everything" tex bg for initialization.
let tex_bg = self.make_default_tex_bg();
self.per_mesh.push((buf, mesh_bg, tex_bg));
}
// -- Build combined mesh+skin bind groups now that per_mesh is grown. --
for (i, d) in draws.iter().enumerate() {
if d.topology == Topology::Skinned && d.skin_idx < skin_data.len() {
let sd = &mut skin_data[d.skin_idx];
let mesh_uniform_buf = &self.per_mesh[i].0;
sd.bg = Some(self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers mesh skinned bg"),
layout: &self.mesh_skinned_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: mesh_uniform_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: sd.bone_buf.as_entire_binding(),
},
],
}));
}
}
// -- Upload uniforms + rebuild per-mesh tex bind groups. --
self.queue
.write_buffer(&self.frame_buffer, 0, bytemuck::bytes_of(&frame_u));
let mut new_tex_bgs: Vec<wgpu::BindGroup> = Vec::with_capacity(draws.len());
for (i, d) in draws.iter().enumerate() {
let mut flags: u32 = 0;
if d.slots.map.is_some() {
flags |= FLAG_MAP;
}
if d.slots.normal_map.is_some() {
flags |= FLAG_NORMAL_MAP;
}
if d.slots.roughness_map.is_some() {
flags |= FLAG_ROUGHNESS_MAP;
}
if d.slots.metalness_map.is_some() {
flags |= FLAG_METALNESS_MAP;
}
if d.slots.ao_map.is_some() {
flags |= FLAG_AO_MAP;
}
if d.slots.emissive_map.is_some() {
flags |= FLAG_EMISSIVE_MAP;
}
if d.slots.matcap_map.is_some() {
flags |= FLAG_MATCAP_MAP;
}
if d.slots.iridescence_thickness_map.is_some() {
flags |= FLAG_IRIDESCENCE_MAP;
}
if d.slots.displacement_map.is_some() {
flags |= FLAG_DISPLACEMENT_MAP;
}
if d.slots.cloud_shadow_map.is_some() && d.atmos[1] > 0.0 {
flags |= FLAG_CLOUD_SHADOW;
}
let u = MeshUniforms {
model: d.model,
normal_matrix: d.normal_matrix,
color: d.color,
emissive: d.emissive,
specular: d.specular,
params: [
d.shininess_or_near,
d.opacity_or_far,
d.roughness,
d.metalness,
],
params2: [
d.ao_intensity,
d.normal_scale[0],
d.normal_scale[1],
f32::from_bits(d.toon_steps),
],
params3: d.physical,
params4: d.physical2,
params5: d.physical3,
params6: d.physical4,
params7: d.physical5,
params8: d.displacement,
params9: d.uv_transform,
params10: d.atmos,
params11: d.twilight,
params12: d.eclipse,
params13: d.scatter,
params14: d.aurora,
flags: [d.kind as u32, flags, d.shader_flags, d.alpha_test.to_bits()],
};
self.queue
.write_buffer(&self.per_mesh[i].0, 0, bytemuck::bytes_of(&u));
new_tex_bgs.push(self.build_tex_bg(&d.slots));
}
// Apply new tex bgs (separate loop to keep borrow rules happy).
for (i, bg) in new_tex_bgs.into_iter().enumerate() {
self.per_mesh[i].2 = bg;
}
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers encoder"),
});
// Shadow depth pre-pass: render scene from the directional light's POV.
if shadow_caster.is_some() {
let mut spass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers shadow pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.shadow_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
spass.set_pipeline(&self.pipeline_shadow);
spass.set_bind_group(0, &self.frame_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if !d.cast_shadow {
continue;
}
if d.topology != Topology::Triangle && d.topology != Topology::TriangleNoCull {
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
spass.set_bind_group(1, &self.per_mesh[i].1, &[]);
spass.set_bind_group(2, &self.per_mesh[i].2, &[]);
spass.set_bind_group(3, &self.shadow_env_bind_group, &[]);
spass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
spass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
spass.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
spass.draw(0..gm.vertex_count, 0..1);
}
}
}
// Spot shadow depth pre-pass.
if spot_caster.is_some() {
let mut spass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers spot shadow pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.spot_shadow_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
spass.set_pipeline(&self.pipeline_shadow_spot);
spass.set_bind_group(0, &self.frame_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if !d.cast_shadow {
continue;
}
if d.topology != Topology::Triangle && d.topology != Topology::TriangleNoCull {
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
spass.set_bind_group(1, &self.per_mesh[i].1, &[]);
spass.set_bind_group(2, &self.per_mesh[i].2, &[]);
spass.set_bind_group(3, &self.shadow_env_bind_group, &[]);
spass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
spass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
spass.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
spass.draw(0..gm.vertex_count, 0..1);
}
}
}
// Point-light cubemap depth: 6 face passes, one per cube face.
if let Some((pos, radius, _)) = point_caster {
self.queue.submit(Some(encoder.finish()));
encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("threers point shadow encoder"),
});
let face_lookat: [(Vector3, Vector3); 6] = [
(Vector3::new(1.0, 0.0, 0.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(-1.0, 0.0, 0.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(0.0, 1.0, 0.0), Vector3::new(0.0, 0.0, 1.0)),
(Vector3::new(0.0, -1.0, 0.0), Vector3::new(0.0, 0.0, -1.0)),
(Vector3::new(0.0, 0.0, 1.0), Vector3::new(0.0, -1.0, 0.0)),
(Vector3::new(0.0, 0.0, -1.0), Vector3::new(0.0, -1.0, 0.0)),
];
let fov = std::f32::consts::FRAC_PI_2;
let proj = Matrix4::perspective(fov, 1.0, 0.1, radius.max(1.0));
for (face, &(forward, up)) in face_lookat.iter().enumerate() {
let target = pos + forward;
let view = Matrix4::look_at(pos, target, up);
let vp = proj.multiply(&view);
frame_u.cube_face_vp = vp.elements;
// Each face gets its own buffer — see `cube_face_buffers`.
self.queue.write_buffer(
&self.cube_face_buffers[face],
0,
bytemuck::bytes_of(&frame_u),
);
let mut spass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers point shadow face pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.point_shadow_face_views[face],
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
spass.set_pipeline(&self.pipeline_shadow_point);
spass.set_bind_group(0, &self.cube_face_bind_groups[face], &[]);
for (i, d) in draws.iter().enumerate() {
if d.topology != Topology::Triangle && d.topology != Topology::TriangleNoCull {
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
spass.set_bind_group(1, &self.per_mesh[i].1, &[]);
spass.set_bind_group(2, &self.per_mesh[i].2, &[]);
spass.set_bind_group(3, &self.shadow_env_bind_group, &[]);
spass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
spass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
spass.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
spass.draw(0..gm.vertex_count, 0..1);
}
}
}
}
// Screen-space refraction glass: when any Refract surface is present, the
// opaque scene is rendered into the mipped ss-color capture (instead of
// straight to the frame target); the glass pass below then refracts and
// reflects that capture. Otherwise the main pass targets the frame view
// directly, exactly as before.
// A custom shader that asked for the opaque-scene capture needs the same
// machinery the refraction glass does, so it turns it on too.
// SUPPRESSED while rendering an environment cube. The glass path
// copies the frame's depth into a screen-sized scratch texture, and a
// cube face's depth is 48 pixels, not 7680 — wgpu refuses the copy
// outright ("the entire texture must be copied when copying from depth
// texture") and the whole render dies. A reflection probe has no use
// for screen-space refraction anyway: it exists to light other
// surfaces, and what it would refract is not in it.
let refract_present = !self.cube_pass
&& draws.iter().any(|d| {
d.topology == Topology::Refract
|| matches!(d.topology, Topology::Custom(_, _, true, _))
});
let ss_format = if linear_framebuffer {
wgpu::TextureFormat::Rgba16Float
} else {
self.color_format
};
if refract_present {
let (w, h) = self.depth_size;
self.ensure_ss_targets(w, h, ss_format);
}
// Compile any not-yet-seen custom-shader pipelines and build their
// @group(1) user bind groups (buffers kept alive until submit). Hoisted
// above the passes because a screen-space custom material draws in the
// glass pass rather than the opaque one, and both need these.
let mut user_bgs: Vec<Option<wgpu::BindGroup>> = Vec::new();
user_bgs.resize_with(draws.len(), || None);
let mut _custom_keep_alive: Vec<wgpu::Buffer> = Vec::new();
for (i, d) in draws.iter().enumerate() {
if let Topology::Custom(hash, transparent, screen_space, side) = d.topology {
let sd = &shader_data[d.shader_idx];
let key = (hash, linear_framebuffer, transparent, screen_space, side);
if !self.custom_pipelines.contains_key(&key) {
let fmt = if linear_framebuffer {
wgpu::TextureFormat::Rgba16Float
} else {
self.color_format
};
let pipeline = build_custom_pipeline(
&self.device,
&self.custom_pipeline_layout,
&sd.fragment,
fmt,
transparent,
screen_space,
side,
);
self.custom_pipelines.insert(key, pipeline);
}
let (bg, bufs) = build_user_bind_group(
&self.device,
&self.custom_mesh_bgl,
&self.per_mesh[i].0,
&sd.data,
&sd.storage,
&sd.textures,
&self.default_white_linear.view,
&self.sampler_linear_repeat,
);
_custom_keep_alive.extend(bufs);
user_bgs[i] = Some(bg);
}
}
{
let bg_color = scene.background;
// HalfFloat postfx RTs store linear light; sRGB canvas clears use raw bytes
// (matches three.js gl.clearColor on an sRGB default framebuffer).
let bg_alpha = scene.background_alpha as f64;
let clear = if linear_framebuffer {
wgpu::Color {
r: bg_color.r.powf(2.2) as f64,
g: bg_color.g.powf(2.2) as f64,
b: bg_color.b.powf(2.2) as f64,
a: bg_alpha,
}
} else {
wgpu::Color {
r: bg_color.r as f64,
g: bg_color.g as f64,
b: bg_color.b as f64,
a: bg_alpha,
}
};
// Hardware MSAA on the direct-to-surface opaque pass. Falls back to
// single-sample for render-to-texture, linear/postfx targets, and any
// scene using glass/OIT/refraction/instanced/skinned/custom draws.
let use_msaa = self.msaa > 1
&& depth_src.is_none()
&& !linear_framebuffer
&& !refract_present
&& draws.iter().all(|d| {
matches!(
d.topology,
Topology::Triangle
| Topology::TriangleAlpha
| Topology::TriangleNoCull
| Topology::Sky
| Topology::TriangleWire
| Topology::Line
| Topology::Point
)
});
if use_msaa {
self.ensure_msaa_targets(self.depth_size.0, self.depth_size.1);
}
// Screen-space glass redirects the opaque pass into the ss-color capture
// (mip 0); MSAA renders into the multisampled color and resolves into the
// frame view; otherwise it targets the frame view directly.
let (main_color_view, msaa_resolve, depth_pass_view): (
&wgpu::TextureView,
Option<&wgpu::TextureView>,
&wgpu::TextureView,
) = if use_msaa {
let (_, _, cv, dv) = self.msaa_targets.as_ref().unwrap();
(cv, Some(target_view), dv)
} else if refract_present {
(
&self.ss_color.as_ref().unwrap().mip_render_views[0],
None,
&self.depth_view,
)
} else {
(target_view, None, &self.depth_view)
};
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers main pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: main_color_view,
depth_slice: None,
resolve_target: msaa_resolve,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(clear),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_pass_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, &self.frame_bind_group, &[]);
pass.set_bind_group(3, &self.env_bind_group, &[]);
let mut last_topology: Option<Topology> = None;
for (i, d) in draws.iter().enumerate() {
// OIT + screen-space-refraction surfaces are drawn in dedicated
// later passes, not here.
if d.topology == Topology::Oit
|| d.topology == Topology::Refract
|| matches!(d.topology, Topology::Custom(_, _, true, _))
{
continue;
}
// Objects opted out of glass capture draw *over* the glass (a
// later overlay pass), so they're not refracted — skip here.
if refract_present && !d.refract_capture {
continue;
}
if last_topology != Some(d.topology) {
let pipe = if use_msaa {
match d.topology {
Topology::Triangle => &self.pipeline_tri_msaa,
Topology::TriangleAlpha => &self.pipeline_tri_alpha_msaa,
Topology::TriangleNoCull => &self.pipeline_tri_nocull_msaa,
Topology::Sky => &self.pipeline_tri_sky_msaa,
Topology::TriangleWire => &self.pipeline_tri_wire_msaa,
Topology::Line => &self.pipeline_line_msaa,
Topology::Point => &self.pipeline_point_msaa,
// gated by `use_msaa`; other topologies never occur here
_ => &self.pipeline_tri_msaa,
}
} else if linear_framebuffer {
match d.topology {
Topology::Triangle => &self.pipeline_tri_f16,
Topology::TriangleAlpha => &self.pipeline_tri_alpha_f16,
Topology::TriangleNoCull => &self.pipeline_tri_nocull_f16,
Topology::GlassDepth => &self.pipeline_glass_depth_f16,
Topology::GlassColor => &self.pipeline_glass_color_f16,
Topology::Sky => &self.pipeline_tri_sky_f16,
Topology::TriangleWire => &self.pipeline_tri_wire_f16,
Topology::Line => &self.pipeline_line_f16,
Topology::Point => &self.pipeline_point_f16,
Topology::Sprite => &self.pipeline_sprite_f16,
Topology::Instanced => &self.pipeline_instanced_f16,
Topology::Skinned => &self.pipeline_skinned_f16,
Topology::Oit | Topology::Refract => continue,
Topology::Custom(h, tr, ss, sd) => {
&self.custom_pipelines[&(h, true, tr, ss, sd)]
}
}
} else {
match d.topology {
Topology::Triangle => &self.pipeline_tri,
Topology::TriangleAlpha => &self.pipeline_tri_alpha,
Topology::TriangleNoCull => &self.pipeline_tri_nocull,
Topology::GlassDepth => &self.pipeline_glass_depth,
Topology::GlassColor => &self.pipeline_glass_color,
Topology::Sky => &self.pipeline_tri_sky,
Topology::TriangleWire => &self.pipeline_tri_wire,
Topology::Line => &self.pipeline_line,
Topology::Point => &self.pipeline_point,
Topology::Sprite => &self.pipeline_sprite,
Topology::Instanced => &self.pipeline_instanced,
Topology::Skinned => &self.pipeline_skinned,
Topology::Oit | Topology::Refract => continue,
Topology::Custom(h, tr, ss, sd) => {
&self.custom_pipelines[&(h, false, tr, ss, sd)]
}
}
};
pass.set_pipeline(pipe);
last_topology = Some(d.topology);
}
let gm = if d.topology == Topology::Sprite {
&self.sprite_quad
} else {
&self.geom_cache[&d.key].mesh
};
if d.topology == Topology::Skinned {
// Skinned pipeline uses the combined mesh+skin BGL at group(1).
if let Some(bg) = skin_data.get(d.skin_idx).and_then(|s| s.bg.as_ref()) {
pass.set_bind_group(1, bg, &[]);
}
pass.set_bind_group(2, &self.per_mesh[i].2, &[]);
if let Some(skin_attrs) = self.skin_attr_cache.get(&d.key) {
pass.set_vertex_buffer(1, skin_attrs.slice(..));
}
} else if let Topology::Custom(..) = d.topology {
// Custom-shader draws use the combined mesh+user bind group
// at @group(1) (mesh uniform + user data/storage).
if let Some(bg) = &user_bgs[i] {
pass.set_bind_group(1, bg, &[]);
}
pass.set_bind_group(2, &self.per_mesh[i].2, &[]);
} else {
pass.set_bind_group(1, &self.per_mesh[i].1, &[]);
pass.set_bind_group(2, &self.per_mesh[i].2, &[]);
}
pass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
let instance_count = if d.topology == Topology::Instanced {
pass.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
d.instance_count
} else {
1
};
// For TriangleWire we draw the wireframe line-list index buffer
// (three.js WebGLGeometries: a,b,b,c,c,a per triangle).
let (ib_opt, idx_count) = if d.topology == Topology::TriangleWire {
(gm.wire_index_buffer.as_ref(), gm.wire_index_count)
} else {
(gm.index_buffer.as_ref(), gm.index_count)
};
if let Some(ib) = ib_opt {
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..idx_count, 0, 0..instance_count);
} else {
pass.draw(0..gm.vertex_count, 0..instance_count);
}
}
}
// --- Weighted-blended OIT: accumulate the OIT surfaces, then resolve
// (composite) over the opaque image already in `target_view`. ---
// Not during a probe, and this one bites hard. The order-independent
// transparency targets are sized from `depth_size`, which a cube pass
// has set to the face's 48 pixels — so a probe RESIZES them, and the
// next real frame resolves a 48-pixel transparency buffer stretched
// across the whole picture. It reads as the entire vehicle going
// translucent, which looks like an alpha bug in the materials and is
// nothing of the kind.
if !self.cube_pass && draws.iter().any(|d| d.topology == Topology::Oit) {
let (tw, th) = self.depth_size;
self.ensure_oit_targets(tw, th);
if let Some((_, _, _, accum_view, _, reveal_view, resolve_bg)) =
self.oit_targets.as_ref()
{
// 1) Accumulation pass (accum cleared to 0, revealage cleared to 1).
{
let mut opass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers oit accum pass"),
color_attachments: &[
Some(wgpu::RenderPassColorAttachment {
view: accum_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
}),
Some(wgpu::RenderPassColorAttachment {
view: reveal_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
}),
],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
opass.set_pipeline(&self.pipeline_oit);
opass.set_bind_group(0, &self.frame_bind_group, &[]);
opass.set_bind_group(3, &self.env_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if d.topology != Topology::Oit {
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
opass.set_bind_group(1, &self.per_mesh[i].1, &[]);
opass.set_bind_group(2, &self.per_mesh[i].2, &[]);
opass.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
opass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
opass.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
opass.draw(0..gm.vertex_count, 0..1);
}
}
}
// 2) Resolve over the opaque image (alpha-blended fullscreen).
{
let resolve_pipe = if linear_framebuffer {
&self.pipeline_oit_resolve_f16
} else {
&self.pipeline_oit_resolve
};
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers oit resolve pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rpass.set_pipeline(resolve_pipe);
rpass.set_bind_group(0, resolve_bg, &[]);
rpass.draw(0..3, 0..1);
}
}
}
// --- Screen-space refraction glass: build the ss-color mip chain from
// the opaque capture, blit the sharp capture to the frame target, then
// draw the glass surface sampling it for refraction + reflection. ---
if refract_present {
let ssc = self.ss_color.as_ref().unwrap();
// Copy the opaque depth into the sampleable ss_depth so the glass
// shader can ray-march it for refraction/reflection.
if let Some((_, _, ss_dtex, _)) = &self.ss_depth {
let src = depth_src.unwrap_or(&self.depth_texture);
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: src,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::DepthOnly,
},
wgpu::TexelCopyTextureInfo {
texture: ss_dtex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::DepthOnly,
},
wgpu::Extent3d {
width: ssc.width,
height: ssc.height,
depth_or_array_layers: 1,
},
);
}
let ss_depth_view = &self.ss_depth.as_ref().unwrap().3;
let ss_back_depth_view = &self.ss_back_depth.as_ref().unwrap().3;
// Two-surface: render glass back faces (cull front) into ss_back_depth
// so the shader can derive per-pixel glass thickness.
{
let mut bp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss back-depth pass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: ss_back_depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
bp.set_pipeline(&self.pipeline_ss_back_depth);
bp.set_bind_group(0, &self.frame_bind_group, &[]);
for (i, d) in draws.iter().enumerate() {
if d.topology != Topology::Refract {
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
bp.set_bind_group(1, &self.per_mesh[i].1, &[]);
bp.set_bind_group(2, &self.per_mesh[i].2, &[]);
bp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
bp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
bp.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
bp.draw(0..gm.vertex_count, 0..1);
}
}
}
let blit_pipe = if linear_framebuffer {
&self.pipeline_ss_blit_f16
} else {
&self.pipeline_ss_blit
};
// 1) Downsample chain: build mip m by box-filtering mip m-1.
for m in 1..ssc.mips as usize {
let src_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers ss mip src"),
layout: &self.ss_blit_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(
&ssc.mip_sample_views[m - 1],
),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
],
});
let mut mp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss mip gen"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &ssc.mip_render_views[m],
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
mp.set_pipeline(blit_pipe);
mp.set_bind_group(0, &src_bg, &[]);
mp.draw(0..3, 0..1);
}
// 2) Blit the sharp capture (mip 0) to the frame target so non-glass
// pixels show through; the glass draws over it next.
{
let blit_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers ss blit src"),
layout: &self.ss_blit_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&ssc.mip_sample_views[0]),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
],
});
let mut bp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss blit"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
bp.set_pipeline(blit_pipe);
bp.set_bind_group(0, &blit_bg, &[]);
bp.draw(0..3, 0..1);
}
// 3) group(3) bind group with the real ss-color at binding 9 (env cube
// + shadows mirror the frame's env bind group).
let cube_uv_view: &wgpu::TextureView = if let Some(env) = &scene.environment {
self.cube_cache
.get(&cube_cache_key(env))
.and_then(|gc| gc.cube_uv_view.as_ref())
.unwrap_or(&self.default_cube_uv_view)
} else {
&self.default_cube_uv_view
};
let env_cube_view: &wgpu::TextureView = if let Some(rt_id) = scene.environment_cube_rt {
self.cube_rt_view_cache
.get(&rt_id)
.unwrap_or(&self.default_env_cube.view)
} else if let Some(env) = &scene.environment {
&self.cube_cache[&cube_cache_key(env)].view
} else {
&self.default_env_cube.view
};
let glass_env_bg = env_bind_group!(
self.device,
&self.env_bgl,
"threers glass env bg",
env_cube_view,
&self.env_sampler,
&self.shadow_view,
&self.shadow_sampler,
&self.spot_shadow_view,
&self.spot_shadow_sampler,
&self.point_shadow_cube_view,
&self.point_shadow_sampler,
cube_uv_view,
&ssc.all_mips_view,
&self.ss_glass_sampler,
ss_depth_view,
ss_back_depth_view,
);
// 4) Glass surface pass (Less + depth-write, opaque composite).
let glass_pipe = if linear_framebuffer {
&self.pipeline_ss_glass_f16
} else {
&self.pipeline_ss_glass
};
let mut gp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers ss glass pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
gp.set_pipeline(glass_pipe);
gp.set_bind_group(0, &self.frame_bind_group, &[]);
gp.set_bind_group(3, &glass_env_bg, &[]);
for (i, d) in draws.iter().enumerate() {
if d.topology != Topology::Refract {
continue;
}
let gm = &self.geom_cache[&d.key].mesh;
gp.set_bind_group(1, &self.per_mesh[i].1, &[]);
gp.set_bind_group(2, &self.per_mesh[i].2, &[]);
gp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
gp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
gp.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
gp.draw(0..gm.vertex_count, 0..1);
}
}
// Custom shaders that asked for the capture draw here too, with the
// real ss-colour/ss-depth at group(3) — the whole point of the flag.
for (i, d) in draws.iter().enumerate() {
let Topology::Custom(h, tr, true, sd) = d.topology else {
continue;
};
let Some(bg) = &user_bgs[i] else { continue };
gp.set_pipeline(&self.custom_pipelines[&(h, linear_framebuffer, tr, true, sd)]);
gp.set_bind_group(1, bg, &[]);
gp.set_bind_group(2, &self.per_mesh[i].2, &[]);
let gm = &self.geom_cache[&d.key].mesh;
gp.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
if let Some(ib) = &gm.index_buffer {
gp.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
gp.draw_indexed(0..gm.index_count, 0, 0..1);
} else {
gp.draw(0..gm.vertex_count, 0..1);
}
}
drop(gp); // end glass pass before the overlay pass reuses the encoder
// Overlay pass: objects opted out of glass capture draw here, over the
// glass, depth-tested against it (so they stay crisp and un-refracted).
if draws.iter().any(|d| !d.refract_capture) {
let mut op = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers glass overlay pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
op.set_bind_group(0, &self.frame_bind_group, &[]);
op.set_bind_group(3, &self.env_bind_group, &[]);
let mut last: Option<Topology> = None;
for (i, d) in draws.iter().enumerate() {
if d.refract_capture {
continue;
}
let pipe = match (linear_framebuffer, d.topology) {
(false, Topology::Triangle) => &self.pipeline_tri,
(false, Topology::TriangleAlpha) => &self.pipeline_tri_alpha,
(false, Topology::TriangleNoCull) => &self.pipeline_tri_nocull,
(false, Topology::Line) => &self.pipeline_line,
(false, Topology::Sprite) => &self.pipeline_sprite,
(false, Topology::Instanced) => &self.pipeline_instanced,
(true, Topology::Triangle) => &self.pipeline_tri_f16,
(true, Topology::TriangleAlpha) => &self.pipeline_tri_alpha_f16,
(true, Topology::TriangleNoCull) => &self.pipeline_tri_nocull_f16,
(true, Topology::Line) => &self.pipeline_line_f16,
(true, Topology::Sprite) => &self.pipeline_sprite_f16,
(true, Topology::Instanced) => &self.pipeline_instanced_f16,
_ => continue, // skinned/custom/etc not supported as overlay
};
if last != Some(d.topology) {
op.set_pipeline(pipe);
last = Some(d.topology);
}
let gm = if d.topology == Topology::Sprite {
&self.sprite_quad
} else {
&self.geom_cache[&d.key].mesh
};
op.set_bind_group(1, &self.per_mesh[i].1, &[]);
op.set_bind_group(2, &self.per_mesh[i].2, &[]);
op.set_vertex_buffer(0, gm.vertex_buffer.slice(..));
let inst = if d.topology == Topology::Instanced {
op.set_vertex_buffer(1, instance_buffers[d.instance_buf_idx].slice(..));
d.instance_count
} else {
1
};
if let Some(ib) = &gm.index_buffer {
op.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
op.draw_indexed(0..gm.index_count, 0, 0..inst);
} else {
op.draw(0..gm.vertex_count, 0..inst);
}
}
}
}
// --- Temporal anti-aliasing: reproject + blend the rendered frame with
// the accumulated history, then blit the result back to the target. ---
if taa_active {
let color_tex = color_src.unwrap();
let depth_tex = depth_src.unwrap();
let (w, h) = self.depth_size;
self.ensure_taa_targets(w, h, ss_format);
let first = self.taa_frame == 0;
// Camera movement, carried for a caller that can distinguish its
// own pinned geometry. This pass cannot: see TAA_SHADER.
let cam = camera.position();
let d = [
cam.x - self.taa_prev_cam[0],
cam.y - self.taa_prev_cam[1],
cam.z - self.taa_prev_cam[2],
];
let taa_u = TaaUniforms {
inv_view_proj: taa_inv_vp,
prev_view_proj: self.taa_prev_view_proj,
params: [w as f32, h as f32, 0.9, if first { 1.0 } else { 0.0 }],
cam_delta: [d[0], d[1], d[2], 0.0],
};
self.queue
.write_buffer(&self.taa_uniform, 0, bytemuck::bytes_of(&taa_u));
let cur_view = color_tex.create_view(&wgpu::TextureViewDescriptor::default());
let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
// frame N reads what N-1 wrote, writes the other buffer.
let (a_view, b_view) = {
let (_, _, _, av, _, bv) = self.taa_history.as_ref().unwrap();
(av, bv)
};
let even = self.taa_frame.is_multiple_of(2);
let (read_view, write_view) = if even {
(b_view, a_view)
} else {
(a_view, b_view)
};
let resolve_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers taa bg"),
layout: &self.taa_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&cur_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(read_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&depth_view),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.taa_sampler),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.taa_uniform.as_entire_binding(),
},
],
});
let taa_pipe = if linear_framebuffer {
&self.pipeline_taa_f16
} else {
&self.pipeline_taa
};
{
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers taa resolve"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: write_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
rp.set_pipeline(taa_pipe);
rp.set_bind_group(0, &resolve_bg, &[]);
rp.draw(0..3, 0..1);
}
// Blit the resolved history back to the frame target.
let blit_bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers taa blit bg"),
layout: &self.ss_blit_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(write_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.ss_glass_sampler),
},
],
});
let blit_pipe = if linear_framebuffer {
&self.pipeline_ss_blit_f16
} else {
&self.pipeline_ss_blit
};
{
let mut bp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("threers taa blit"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
bp.set_pipeline(blit_pipe);
bp.set_bind_group(0, &blit_bg, &[]);
bp.draw(0..3, 0..1);
}
}
// Roll the motion-blur matrices on every frame -- but a PROBE IS NOT A
// FRAME. An environment cube is six renders from a camera that is not
// the picture's, and rolling on those leaves `mb_last_vp` holding a
// 90-degree view from somewhere else. The next real frame then blurs
// along the difference between the two, which is enormous: the vehicle
// smears into a translucent double of itself and streaks run across the
// whole image. It reads exactly like a transparency bug, and was chased
// as one for a long time -- through the OIT buffers, the cube format,
// the PMREM prefilter and the probe's brightness -- none of which it
// ever was.
if !self.cube_pass {
self.mb_inv_vp = taa_inv_vp;
self.mb_prev_vp = self.mb_last_vp;
self.mb_last_vp = taa_unjittered_vp;
}
if taa_active && !self.cube_pass {
// (separate block so the history-view borrows above have ended)
self.taa_prev_view_proj = taa_unjittered_vp;
{
let c = camera.position();
self.taa_prev_cam = [c.x, c.y, c.z];
}
self.taa_frame += 1;
}
self.queue.submit(Some(encoder.finish()));
let _ = (&self.frame_bgl,);
}
fn ensure_slot_uploaded(&mut self, slot: &Option<Arc<Texture>>) {
let Some(t) = slot else {
return;
};
// Skip upload for render-target-backed textures — the view lives in
// the RenderTarget itself.
if t.external_rt_id.is_some() {
return;
}
let key = tex_cache_key(t);
// No liveness check any more: the key is the texture's own id, which
// does not depend on where — or whether — its bytes are. That is what
// lets a data-less `Texture::handle` resolve to the upload its full
// twin made, and it closes the recycled-address hole the weak handle
// was guarding, since an id is never handed out twice.
if !self.tex_cache.contains_key(&key) {
// Drop stale GPU copies for this logical texture (older upload_seq).
self.tex_cache.retain(|k, _| k.0 != t.id);
if t.is_handle() {
// A handle carries no pixels: it can only ever resolve to an
// upload its full twin already made. Reaching here means that
// upload is missing, and what gets created instead is a texture
// of the right size with nothing in it -- which samples black
// and raises no error anywhere.
log::warn!(
"uploading a data-less handle: id {} {}x{} {:?} -- this samples black",
t.id,
t.width,
t.height,
t.format
);
if std::env::var("TEXWARN").is_ok() {
eprintln!(
" WARN data-less handle uploaded: id {} {}x{} {:?}",
t.id, t.width, t.height, t.format
);
}
}
// Downsampling is a texture read and a write, so let the GPU do it
// rather than computing the whole chain serially on this thread and
// uploading it level by level.
let mipgen = self
.mipgen
.get_or_insert_with(|| MipGenerator::new(&self.device));
let gt = GpuTexture::upload_with_mipgen(&self.device, &self.queue, t, mipgen);
self.tex_cache.insert(key, gt);
}
}
fn view_for<'a>(
&'a self,
slot: &Option<Arc<Texture>>,
default: &'a GpuTexture,
) -> &'a wgpu::TextureView {
match slot {
Some(t) => {
// If this Texture is RT-backed, sample from the RT's color view.
if let Some(rt_id) = t.external_rt_id {
if let Some(view) = self.rt_view_cache.get(&rt_id) {
return view;
}
}
&self.tex_cache[&tex_cache_key(t)].view
}
None => &default.view,
}
}
/// Borrow an RT's sample-side view by id. Caller must have previously
/// `register_render_target`'d this id. Used by post-fx to bind the input.
pub fn rt_view_cache_get(&self, rt_id: u32) -> &wgpu::TextureView {
self.rt_view_cache
.get(&rt_id)
.expect("rt id not registered")
}
/// Register a CubeRenderTarget so scene.environment_cube_rt can sample
/// from its 6-face cube view as an env map.
pub fn register_cube_render_target(&mut self, rt_id: u32, rt: &Arc<super::CubeRenderTarget>) {
let sample_format = rt.format.add_srgb_suffix();
let view = rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers cube rt sample view"),
format: Some(sample_format),
dimension: Some(wgpu::TextureViewDimension::Cube),
base_array_layer: 0,
array_layer_count: Some(6),
base_mip_level: 0,
mip_level_count: Some(1),
aspect: wgpu::TextureAspect::All,
usage: None,
});
self.cube_rt_view_cache.insert(rt_id, view);
}
/// Register a RenderTarget so RT-backed Textures can sample from its color view.
/// Creates a sample-side view using the sRGB-variant of the storage format
/// (when applicable) so the hardware does sRGB→linear decode on read,
/// matching three.js's WebGL behavior where RT textures auto-decode.
pub fn register_render_target(&mut self, rt_id: u32, rt: &Arc<super::RenderTarget>) {
let sample_format = rt_sample_format(rt.format);
let view = rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers rt sample view"),
format: Some(sample_format),
..Default::default()
});
self.rt_view_cache.insert(rt_id, view);
let linear_view = rt.color_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers rt linear sample view"),
format: Some(rt.format),
..Default::default()
});
self.rt_linear_view_cache.insert(rt_id, linear_view);
let depth_view = rt.depth_texture.create_view(&wgpu::TextureViewDescriptor {
label: Some("threers rt depth sample view"),
aspect: wgpu::TextureAspect::DepthOnly,
..Default::default()
});
self.rt_depth_view_cache.insert(rt_id, depth_view);
self.rt_registry.insert(rt_id, Arc::clone(rt));
}
fn build_tex_bg(&self, slots: &MaterialTextureSlots) -> wgpu::BindGroup {
let albedo = self.view_for(&slots.map, &self.default_white_srgb);
let normal = self.view_for(&slots.normal_map, &self.default_normal);
let roughness = self.view_for(&slots.roughness_map, &self.default_white_linear);
let metalness = self.view_for(&slots.metalness_map, &self.default_white_linear);
let ao = self.view_for(&slots.ao_map, &self.default_white_linear);
let emissive = self.view_for(&slots.emissive_map, &self.default_white_srgb);
// Matcap and cloud cover share a binding. WebGPU guarantees only 16
// sampled textures per fragment stage and we are at that ceiling, so a
// seventeenth is not available — but the two can never both be set: a
// matcap belongs to `MatcapMaterial`, a cloud deck to a Standard or
// Physical surface.
let matcap = match &slots.cloud_shadow_map {
Some(_) => self.view_for(&slots.cloud_shadow_map, &self.default_transparent),
None => self.view_for(&slots.matcap_map, &self.default_white_srgb),
};
let iridescence_thickness =
self.view_for(&slots.iridescence_thickness_map, &self.default_white_linear);
// Black default: no map means no displacement, so the vertex stage can
// sample unconditionally and still move nothing.
let displacement = self.view_for(&slots.displacement_map, &self.default_black);
// Pick sampler based on the primary texture's filter/wrap. We use
// `slots.map` as the canonical choice (matcap uses `matcap_map`).
let chosen = slots.map.as_ref().or(slots.matcap_map.as_ref());
let sampler = match chosen {
Some(t) => self.pick_sampler(t),
None => &self.sampler_linear,
};
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("threers tex bg"),
layout: &self.tex_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(albedo),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(normal),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(roughness),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(metalness),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView(ao),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(emissive),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::TextureView(displacement),
},
wgpu::BindGroupEntry {
binding: 6,
resource: wgpu::BindingResource::TextureView(matcap),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::Sampler(sampler),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(iridescence_thickness),
},
],
})
}
/// Select one of the 4 pre-built samplers based on a Texture's filter/wrap
/// fields. Mirrors three.js: NearestFilter→nearest, LinearFilter→linear;
/// RepeatWrapping→repeat, ClampToEdgeWrapping→clamp.
fn pick_sampler<'a>(&'a self, t: &Texture) -> &'a wgpu::Sampler {
use crate::textures::{TextureFilter, TextureWrap};
let nearest = matches!(t.mag_filter, TextureFilter::Nearest);
let repeat =
matches!(t.wrap_s, TextureWrap::Repeat) || matches!(t.wrap_t, TextureWrap::Repeat);
match (nearest, repeat) {
(false, false) => &self.sampler_linear,
(true, false) => &self.sampler_nearest_clamp,
(false, true) => &self.sampler_linear_repeat,
(true, true) => &self.sampler_nearest_repeat,
}
}
fn make_default_tex_bg(&self) -> wgpu::BindGroup {
self.build_tex_bg(&MaterialTextureSlots::default())
}
}
/// Halton low-discrepancy sequence — the standard source of TAA sub-pixel jitter.
fn halton(mut index: u32, base: u32) -> f32 {
let (mut f, mut r) = (1.0f32, 0.0f32);
while index > 0 {
f /= base as f32;
r += f * (index % base) as f32;
index /= base;
}
r
}
/// `PrimitiveState` with the fields that never vary across our pipelines filled
/// in (Ccw front, fill, clipped, non-conservative) — only topology + cull differ.
fn primitive(topology: wgpu::PrimitiveTopology, cull: Option<wgpu::Face>) -> wgpu::PrimitiveState {
wgpu::PrimitiveState {
topology,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: cull,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
}
}
/// `DepthStencilState` at [`DEPTH_FORMAT`] with default stencil/bias — only the
/// write flag and compare function differ across our pipelines.
fn depth_stencil(write: bool, compare: wgpu::CompareFunction) -> wgpu::DepthStencilState {
wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(write),
depth_compare: Some(compare),
stencil: Default::default(),
bias: Default::default(),
}
}
fn create_depth_view(
device: &wgpu::Device,
width: u32,
height: u32,
) -> (wgpu::Texture, wgpu::TextureView) {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("threers depth"),
size: wgpu::Extent3d {
width: width.max(1),
height: height.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DEPTH_FORMAT,
// COPY_SRC so the opaque depth can be copied into the sampleable ss_depth
// for the screen-space glass ray march.
// TEXTURE_BINDING as well: passes that run after the frame — ambient
// occlusion, and anything else reconstructing geometry from depth —
// have to sample this, and a depth buffer that can only be rendered
// into and copied out of is no use to them.
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
(tex, view)
}
fn transform_direction(m: &Matrix4, v: Vector3) -> Vector3 {
let e = &m.elements;
Vector3::new(
e[0] * v.x + e[4] * v.y + e[8] * v.z,
e[1] * v.x + e[5] * v.y + e[9] * v.z,
e[2] * v.x + e[6] * v.y + e[10] * v.z,
)
}
fn mat3_to_mat4_array(m: &Matrix3) -> [f32; 16] {
let e = &m.elements;
[
e[0], e[1], e[2], 0.0, e[3], e[4], e[5], 0.0, e[6], e[7], e[8], 0.0, 0.0, 0.0, 0.0, 1.0,
]
}