concinnity-device 0.19.0

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
// src/vulkan/init.rs
//
// VkContext construction: platform window creation and the one-time GPU
// resource setup performed by VkContext::new.
use concinnity_core::gfx::transform::IDENTITY;
use std::ffi::{CStr, CString, c_char};

use ash::vk;

use crate::vulkan::owned::{
    OwnedDescriptorPool, OwnedPipeline, OwnedPipelineLayout, OwnedRenderPass, OwnedSetLayout,
    VkDevice,
};

use crate::gfx::render_types::*;

use super::context::*;
use super::device::*;
use super::draw::*;
use super::pipeline::*;
use super::post::bloom::{
    BloomDeviceContext, MAX_BLOOM_MIPS, alloc_bloom_input_sets, compile_bloom_shaders,
    create_bloom_chain, create_bloom_framebuffers, create_bloom_pipeline, rebind_bloom_input0,
};
use super::post::taa::*;
use super::render_pass::*;
use super::resources::*;
use super::swapchain::*;
use super::texture::{self, *};

//  Construction

impl VkContext {
    // Construct a fresh context, acquiring its own OS window + Vulkan
    // instance / device / surface / swapchain.
    pub(crate) fn new(init: crate::gfx::backend_init::BackendInit<'_>) -> Result<Self, String> {
        Self::build(init, None)
    }

    // Construct from the assembled backend inputs (see
    // `crate::gfx::backend_init::BackendInit` for per-field docs); the
    // Vulkan-specific behaviour of each input is documented inline below.
    //
    // `reuse` is `Some` only on a live editor `reload_world` (see
    // `apply_world_reload`): the shared hardware (window / instance / device /
    // surface / swapchain / queues / capabilities / debug messenger / timestamp
    // pool) is inherited from the outgoing context instead of acquired fresh,
    // and every per-world resource below is rebuilt on it. `None` acquires it
    // all fresh, the normal launch path.
    fn build(
        init: crate::gfx::backend_init::BackendInit<'_>,
        reuse: Option<VkReuse>,
    ) -> Result<Self, String> {
        use crate::gfx::backend_init::{
            BackendInit, MediaPayloads, PostSettings, SceneData, ShaderBytes, ShadowParams, WorldFx,
        };
        let BackendInit {
            window,
            validation,
            frames_in_flight,
            vsync,
            clear_color,
            hot_reload,
            // Vulkan retains the presented swapchain index unconditionally, so
            // capture needs no arming here.
            capture: _,
            scene:
                SceneData {
                    vertices,
                    indices,
                    draw_objects,
                    instanced_clusters,
                    // Skinned draw-object count, threaded to size the shared
                    // GPU-cull buffers' reserved skinned tail at init
                    // (`n_objects + n_instances + n_skinned`). The skinned
                    // geometry is uploaded later by `upload_skinned`, which sets
                    // the live `self.draw.n_skinned`; this only reserves capacity.
                    n_skinned,
                    // Reserves a chunk record region in the shared cull buffers
                    // at init (`[n_objects + n_instances, +n_chunk_max)`);
                    // resident chunks fold into the indirect path each frame.
                    // Sets the live `self.draw.n_chunk`.
                    n_chunk_max,
                },
            shaders: world_shaders,
            media:
                MediaPayloads {
                    textures,
                    text_atlases,
                    env_map_bytes,
                    color_lut_bytes,
                },
            light_uniforms,
            // Per-scene local lights uploaded once into a static SSBO below
            // (global set 0 binding 9).
            local_lights,
            spot_shadows,
            area_lights,
            shadows:
                ShadowParams {
                    map_size: shadow_map_size,
                    update: shadow_update,
                    distance: shadow_distance,
                    cascades: shadow_cascades,
                },
            // Clamped to the device limit where the sampler is built below.
            anisotropy,
            planar_planes,
            post:
                PostSettings {
                    post_process: post_tunables,
                    taa_enabled,
                    ssao: ssao_settings,
                    ssr: ssr_settings,
                    ssgi: ssgi_settings,
                    rt_reflections: rt_settings,
                    rt_dynamic: rt_dynamic_mode,
                    rt_skinned_geometry,
                    reflection_blur_scale,
                    auto_exposure: auto_exposure_settings,
                    auto_exposure_bias_ev,
                    hdr_display,
                    hdr_pq,
                    temporal_upscaling,
                    upscale_scale,
                    // Only FSR is available on Vulkan (DLSS / XeSS are
                    // DirectX-only); a DX-only request logs a note and uses FSR.
                    upscale_backend,
                    occlusion_two_pass,
                },
            fx:
                WorldFx {
                    decals,
                    particles,
                    fog: fog_settings,
                    water_surfaces,
                    glass_panels,
                    sdf_volumes,
                },
            requirements: _,
        } = init;
        // Entry 0 is the world default program; entries 1.. are the
        // material-referenced shader buckets (see `world_shaders.rs`).
        let &ShaderBytes {
            vert: vert_bytes,
            frag: frag_bytes,
            shadow: shadow_bytes,
            vert_instanced: vert_instanced_bytes,
            // The world default program is never deferred (bucket 0 always
            // decodes at init); only the material-referenced buckets can be.
            deferred: _,
        } = world_shaders
            .first()
            .ok_or_else(|| "BackendInit carried no shaders".to_string())?;
        let (title, width, height, title_bar) = (
            window.title.as_str(),
            window.width,
            window.height,
            window.title_bar,
        );
        // Record this (main) thread so the `RenderBackend` mutation entry points
        // can `debug_assert_main_thread` against it; the Send invariant rests on
        // the context being touched from this thread alone.
        super::context::record_main_thread();

        // Temporal upscaling (FSR) consumes the velocity pre-pass's
        // render-resolution motion + depth, which TaaResources owns, so force
        // the TAA stack built when upscaling is on (the TAA *resolve* is still
        // dropped from the frame graph; only the velocity pre-pass is reused).
        let taa_enabled = taa_enabled || temporal_upscaling;
        let frames = frames_in_flight.max(1);

        // Acquire the shared hardware (fresh launch), or inherit it from the
        // outgoing context on a live editor reload. Every per-world resource
        // further below is built on it regardless of which path produced it.
        let SharedHardware {
            window,
            entry,
            instance,
            device,
            physical_device,
            surface,
            surface_loader,
            graphics_queue,
            present_queue,
            graphics_family,
            swapchain_loader,
            swapchain,
            swapchain_images,
            swapchain_format,
            swapchain_extent,
            swapchain_image_views,
            msaa_samples,
            hdr_mode,
            memory_budget_supported,
            rt_capable,
            update_after_bind,
            device_local_heaps,
            timestamp_query_pool,
            timestamp_period,
            alloc,
        } = match reuse {
            Some(r) => r.into_shared()?,
            None => {
                //  Platform window (native Win32 on Windows, GLFW on Linux)
                let mut window = super::PlatformWindow::new(
                    title,
                    width,
                    height,
                    &crate::components::WindowMode::Windowed,
                    true,
                    title_bar,
                )?;

                //  Vulkan entry
                let entry = super::loader::load_entry()?;

                // Resolve which (if any) upscaler SDK needs Vulkan instance / device
                // extensions enabled at creation time (DLSS / XeSS). Queried before
                // instance creation (it needs at most the loaded SDK), then threaded
                // into `create_logical_device` for the device extensions / features.
                // Inert (`choice == Native`) when upscaling is off or the backend needs
                // nothing; held in scope until after device creation so its
                // instance-ext pointers + XeSS feature chain stay valid. Resolved before
                // `app_info` so its `min_api_version` can raise the instance apiVersion.
                let upscale_sdk =
                    super::post::UpscaleSdk::prepare(temporal_upscaling, upscale_backend);

                //  Instance
                let app_name = CString::new(title).unwrap_or_default();
                let engine_name = CString::new("Concinnity").unwrap();
                // Vulkan 1.2 baseline: FidelityFX FSR's precompiled shaders are SPIR-V
                // 1.5, valid only under a 1.2+ instance. XeSS 3.x raises the floor to
                // 1.3 (its shaders use SPV_KHR_integer_dot_product, a 1.3 capability),
                // reported via `min_api_version`. Take the max, clamped to what the
                // loader actually supports so an unsupported request can't fail instance
                // creation (the backend then falls back). The engine's own shaders are
                // unaffected by the bump.
                // SAFETY: an enumeration query on a live instance handle; it only reads, and ash
                // sizes the output vector from the count the driver reports.
                let loader_version = unsafe { entry.try_enumerate_instance_version() }
                    .ok()
                    .flatten()
                    .unwrap_or(vk::API_VERSION_1_2);
                let api_version = vk::API_VERSION_1_2
                    .max(upscale_sdk.min_api_version())
                    .min(loader_version);
                let app_info = vk::ApplicationInfo::default()
                    .application_name(&app_name)
                    .application_version(vk::make_api_version(0, 0, 1, 0))
                    .engine_name(&engine_name)
                    .engine_version(vk::make_api_version(0, 0, 1, 0))
                    .api_version(api_version);

                // Hold the windowing extension name CStrings in scope so their pointers
                // stay valid through instance creation, then drop with the rest of init
                // (mirrors `device.rs`'s `enabled`/`ext_names` pairing). The later
                // pushes are all `'static` NAME pointers, so they need no backing store.
                let instance_ext_cstrings: Vec<CString> = window
                    .required_instance_extensions()
                    .iter()
                    .map(|s| CString::new(s.as_str()).unwrap())
                    .collect();
                let mut ext_names_raw: Vec<*const c_char> =
                    instance_ext_cstrings.iter().map(|c| c.as_ptr()).collect();

                let debug_ext = ash::ext::debug_utils::NAME.as_ptr();
                if validation {
                    ext_names_raw.push(debug_ext);
                }

                // The optional instance extensions the loader actually exposes:
                // `VK_EXT_swapchain_colorspace` for the extended-range surface
                // formats HDR output needs, and `VK_KHR_portability_enumeration`
                // so a portability driver (MoltenVK) is enumerable at all. A
                // missing one degrades rather than failing instance creation.
                let available_ext_props =
                    // SAFETY: an enumeration query on a live instance handle; it only reads, and
                    // ash sizes the output vector from the count the driver reports.
                    unsafe { entry.enumerate_instance_extension_properties(None) }
                        .unwrap_or_default();
                let optional_exts = super::instance_exts::select(
                    &super::instance_exts::names_of(&available_ext_props),
                    hdr_display,
                );
                let swapchain_colorspace_ext_available = optional_exts.swapchain_colorspace;
                if hdr_display && !swapchain_colorspace_ext_available {
                    tracing::warn!(
                        "HDR display requested but VK_EXT_swapchain_colorspace is not exposed by the \
                 Vulkan loader; falling back to SDR (BGRA8 sRGB) output"
                    );
                }
                ext_names_raw.extend(optional_exts.names().iter().map(|n| n.as_ptr()));

                // Instance extensions the chosen upscaler SDK requires (DLSS / XeSS).
                // The pointers borrow from `upscale_sdk`, which outlives this scope.
                for ptr in upscale_sdk.instance_extension_ptrs() {
                    ext_names_raw.push(ptr);
                }

                let layer_names_raw: Vec<*const c_char> = if validation {
                    // Leaked: the instance borrows the name for its whole lifetime.
                    let layer = CString::new("VK_LAYER_KHRONOS_validation").unwrap();
                    vec![layer.into_raw().cast_const()]
                } else {
                    vec![]
                };

                let instance_info = vk::InstanceCreateInfo::default()
                    .application_info(&app_info)
                    .flags(optional_exts.flags())
                    .enabled_extension_names(&ext_names_raw)
                    .enabled_layer_names(&layer_names_raw);

                // SAFETY: the create-info and every slice it borrows are live for the call, and
                // each handle it names belongs to this device.
                let instance = unsafe { entry.create_instance(&instance_info, None) }
                    .map_err(|e| format!("create instance: {e}"))?;
                // A run with no layer messages looks exactly like a run the layer
                // found nothing wrong with, so say which one happened. Reaching
                // here with the layer requested means it loaded: a missing
                // `VK_LAYER_KHRONOS_validation` fails instance creation above.
                if validation {
                    tracing::info!("vulkan validation layer: enabled");
                }

                //  Debug messenger
                // Budget the messenger callback consumes to drop benign DLSS first-frame
                // layout errors; set after `build_upscaler` resolves to DLSS. Heap-boxed
                // so its address stays stable, and handed to the owning device
                // handle alongside the messenger: the callback reads it for as long
                // as the messenger can fire, which is past the device teardown.
                // `None` when validation (the messenger) is off.
                let debug_filter: Option<Box<std::sync::atomic::AtomicU32>> =
                    validation.then(|| Box::new(std::sync::atomic::AtomicU32::new(0)));
                let (debug_utils, debug_messenger) = if validation {
                    let du = ash::ext::debug_utils::Instance::new(&entry, &instance);
                    let user_data = debug_filter
                        .as_ref()
                        .map(|b| {
                            &**b as *const std::sync::atomic::AtomicU32 as *mut std::ffi::c_void
                        })
                        .unwrap_or(std::ptr::null_mut());
                    let info = vk::DebugUtilsMessengerCreateInfoEXT::default()
                        .message_severity(
                            vk::DebugUtilsMessageSeverityFlagsEXT::ERROR
                                | vk::DebugUtilsMessageSeverityFlagsEXT::WARNING,
                        )
                        .message_type(
                            vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
                                | vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
                                | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE,
                        )
                        .pfn_user_callback(Some(debug_callback))
                        .user_data(user_data);
                    // SAFETY: the create-info and every slice it borrows are live for the call, and
                    // each handle it names belongs to this device.
                    let messenger = unsafe { du.create_debug_utils_messenger(&info, None) }
                        .map_err(|e| format!("debug messenger: {e}"))?;
                    (Some(du), Some(messenger))
                } else {
                    (None, None)
                };

                //  Surface
                let surface_loader = ash::khr::surface::Instance::new(&entry, &instance);
                let surface = window.create_surface(&entry, &instance)?;

                //  Physical device
                let (physical_device, graphics_family, present_family) =
                    pick_physical_device(&instance, &surface_loader, surface)?;

                //  Logical device. `rt_capable` comes back true when the device exposes
                //  the ray-query extension set (and XeSS is not the active backend); the
                //  RT extensions are enabled whenever capable so a live RT toggle works,
                //  independent of whether the world wants RT at launch. The
                //  acceleration-structure build + RT pass below are gated on
                //  `rt_settings.is_some() && rt_capable` (everything falls back to SSR
                //  when RT is off or the device is incapable).
                let super::device::LogicalDevice {
                    device,
                    memory_budget: memory_budget_supported,
                    rt_capable,
                    update_after_bind,
                } = create_logical_device(
                    &instance,
                    physical_device,
                    graphics_family,
                    present_family,
                    validation,
                    &upscale_sdk,
                )?;
                // Hand the raw device to the owning wrapper straight away: from
                // here on the device, the instance and the entry are destroyed
                // by the last handle to them, and every Vulkan object the
                // backend owns retires through this device's queue.
                let device = super::owned::VkDevice::new(
                    entry.clone(),
                    instance.clone(),
                    device,
                    frames,
                    super::owned::DebugMessenger {
                        utils: debug_utils,
                        messenger: debug_messenger,
                        filter: debug_filter,
                    },
                );

                // SAFETY: a property query on a live handle; it only reads.
                let graphics_queue = unsafe { device.get_device_queue(graphics_family, 0) };
                // SAFETY: a property query on a live handle; it only reads.
                let present_queue = unsafe { device.get_device_queue(present_family, 0) };

                //  Timestamp support: the per-frame GPU-time chip uses a query pool
                //  with `2 * frames` slots, a pair per in-flight frame. `timestamp_period`
                //  is nanoseconds-per-tick; `timestamp_valid_bits` on the graphics queue
                //  family must be non-zero for `cmd_write_timestamp` to be valid. Without
                //  either the renderer leaves `gpu_frame_us` at zero. Mirrors
                //  `directx::build_timestamp_resources`.
                let device_props =
                    // SAFETY: a property query on a live handle; it only reads.
                    unsafe { instance.get_physical_device_properties(physical_device) };

                //  Persisted pipeline cache: seeded from disk when a blob for
                //  this device exists, handed to every pipeline creation below.
                super::pipeline_cache::install(&device, &device_props);

                // SAFETY: a property query on a live handle; it only reads.
                let queue_family_props = unsafe {
                    instance.get_physical_device_queue_family_properties(physical_device)
                };
                let timestamp_period = device_props.limits.timestamp_period;
                let timestamp_valid_bits = queue_family_props
                    .get(graphics_family as usize)
                    .map(|f| f.timestamp_valid_bits)
                    .unwrap_or(0);
                let timestamps_supported = timestamp_period > 0.0 && timestamp_valid_bits > 0;
                let timestamp_query_pool = if timestamps_supported {
                    // One per-frame block of `SLOTS_PER_FRAME` slots (whole-frame pair +
                    // one pair per render pass) per frame in flight.
                    let info = vk::QueryPoolCreateInfo::default()
                        .query_type(vk::QueryType::TIMESTAMP)
                        .query_count((super::pass_timing::SLOTS_PER_FRAME * frames) as u32);
                    // SAFETY: the create-info and every slice it borrows are live for the call, and
                    // each handle it names belongs to this device.
                    match unsafe { device.create_query_pool(&info, None) } {
                        Ok(p) => Some(p),
                        Err(e) => {
                            tracing::warn!("timestamp query pool create failed: {e}");
                            None
                        }
                    }
                } else {
                    None
                };

                //  Device-local heap indices for the VRAM-residency chip. Sums
                //  `heap_usage` on every DEVICE_LOCAL heap when `VK_EXT_memory_budget`
                //  is supported; otherwise the field stays empty and the chip reports
                //  zero (matching DirectX's adapter-without-QueryVideoMemoryInfo
                //  fallback).
                let memory_props =
                    // SAFETY: a property query on a live handle; it only reads.
                    unsafe { instance.get_physical_device_memory_properties(physical_device) };
                let device_local_heaps: Vec<u32> = if memory_budget_supported {
                    (0..memory_props.memory_heap_count as usize)
                        .filter(|i| {
                            memory_props.memory_heaps[*i]
                                .flags
                                .contains(vk::MemoryHeapFlags::DEVICE_LOCAL)
                        })
                        .map(|i| i as u32)
                        .collect()
                } else {
                    Vec::new()
                };

                //  MSAA sample count
                let msaa_samples = get_max_usable_sample_count(&instance, physical_device);

                // HDR-output resolve. The world's `hdr_display` toggle is the
                // gate; even on a capable display, no HDR unless the asset opts
                // in. The reverse (`hdr_display = true` on an SDR-only surface,
                // or with the colour-space loader extension missing) falls back
                // to SDR with a logged warning. Vulkan has no portable max-EDR
                // query: when the surface advertises the scRGB-linear colour
                // space we synthesise a placeholder `max_edr = 2.0` (the
                // HDR400-class minimum) so the shared `HdrOutputMode::resolve`
                // logic stays uniform across backends.
                // Probe which HDR colour-space pairs the surface advertises. An
                // advertised HDR colour space is Vulkan's "HDR available" signal (there
                // is no portable max-EDR query), so we synthesise the placeholder
                // `max_edr` from it. scRGB-linear drives the extended-linear path; an
                // `HDR10_ST2084_EXT` pair (float or 10-bit packed) drives the PQ path.
                // SAFETY: a property query on a live handle; it only reads.
                let surface_formats = unsafe {
                    surface_loader.get_physical_device_surface_formats(physical_device, surface)
                }
                .unwrap_or_default();
                let advertises = |fmt: vk::Format, cs: vk::ColorSpaceKHR| {
                    surface_formats
                        .iter()
                        .any(|f| f.format == fmt && f.color_space == cs)
                };
                let scrgb_advertises = swapchain_colorspace_ext_available
                    && advertises(
                        vk::Format::R16G16B16A16_SFLOAT,
                        vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT,
                    );
                let pq_advertises = swapchain_colorspace_ext_available
                    && (advertises(
                        vk::Format::R16G16B16A16_SFLOAT,
                        vk::ColorSpaceKHR::HDR10_ST2084_EXT,
                    ) || advertises(
                        vk::Format::A2B10G10R10_UNORM_PACK32,
                        vk::ColorSpaceKHR::HDR10_ST2084_EXT,
                    ));
                // PQ needs the HDR10 colour space. When `hdr_pq` is requested but only
                // scRGB is advertised, fall back to the extended-linear path so the
                // shader encode and the swapchain colour space never diverge (sending
                // PQ-encoded values to an scRGB-linear swapchain would look wrong).
                let pq_capable = hdr_pq && pq_advertises;
                if hdr_display && hdr_pq && !pq_advertises {
                    tracing::warn!(
                        "HDR display + hdr_pq:true requested but no surface format advertises HDR10 PQ \
                 (RGBA16F / A2B10G10R10_UNORM_PACK32 + HDR10_ST2084_EXT); falling back to \
                 scRGB-linear extended-range output"
                    );
                }
                let max_edr = if scrgb_advertises || pq_advertises {
                    2.0
                } else {
                    1.0
                };
                let hdr_mode = crate::gfx::hdr_output::HdrOutputMode::resolve(
                    hdr_display,
                    pq_capable,
                    max_edr,
                );
                if hdr_display && !hdr_mode.is_hdr() {
                    tracing::warn!(
                        "HDR display requested but no surface format advertises an HDR colour space \
                 (scRGB linear or HDR10 PQ): falling back to SDR (BGRA8 sRGB) output"
                    );
                } else if hdr_mode.pq_flag() > 0.5 {
                    tracing::info!(
                        "HDR display output enabled: HDR10 PQ swapchain (SMPTE ST 2084)"
                    );
                } else if hdr_mode.is_hdr() {
                    tracing::info!(
                        "HDR display output enabled: scRGB-linear swapchain (RGBA16F + \
                 EXTENDED_SRGB_LINEAR_EXT)"
                    );
                }
                //  Swapchain
                let swapchain_loader = ash::khr::swapchain::Device::new(&instance, &device);
                let (swapchain, swapchain_images, swapchain_format, swapchain_extent) =
                    create_swapchain_inner(
                        &SwapchainSurface {
                            instance: &instance,
                            device: &device,
                            pd: physical_device,
                            surface_loader: &surface_loader,
                            surface,
                            swapchain_loader: &swapchain_loader,
                        },
                        SwapchainQueueFamilies {
                            graphics_family,
                            present_family,
                        },
                        SwapchainConfig {
                            width,
                            height,
                            old_swapchain: vk::SwapchainKHR::null(),
                            hdr_mode,
                            vsync,
                        },
                    )?;
                let swapchain_image_views =
                    create_swapchain_image_views(&device, &swapchain_images, swapchain_format)?;

                // The device allocator every pooled buffer / image is placed
                // through, built before any resource creation so init-time
                // resources can pool. A reload inherits the outgoing
                // context's instead (the other match arm), so the rebuilt
                // world places into the blocks the old world releases.
                let alloc = super::allocator::DeviceAllocator::new(
                    &instance,
                    physical_device,
                    &device,
                    frames,
                );

                SharedHardware {
                    window,
                    entry,
                    instance,
                    device,
                    physical_device,
                    surface,
                    surface_loader,
                    graphics_queue,
                    present_queue,
                    graphics_family,
                    swapchain_loader,
                    swapchain,
                    swapchain_images,
                    swapchain_format,
                    swapchain_extent,
                    swapchain_image_views,
                    msaa_samples,
                    hdr_mode,
                    memory_budget_supported,
                    rt_capable,
                    update_after_bind,
                    device_local_heaps,
                    timestamp_query_pool,
                    timestamp_period,
                    alloc,
                }
            }
        };

        // Pair the authored tunables with the resolved HDR mode (freshly
        // negotiated or inherited on a reload), which drives the composite
        // shader's `hdr_output > 0.5` branch and its in-branch `pq_output`
        // encode flag. Mirrors `DxContext::new`.
        let post_process = hdr_mode.post_process_params(post_tunables);

        //  Command pool
        let command_pool = {
            let info = vk::CommandPoolCreateInfo::default()
                .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER)
                .queue_family_index(graphics_family);
            // SAFETY: the create-info and every slice it borrows are live for the call, and each
            // handle it names belongs to this device.
            unsafe { device.create_command_pool(&info, None) }
                .map_err(|e| format!("command pool: {e}"))?
        };

        // Temporal upscaling (FSR / DLSS / XeSS). Built here, before the
        // off-screen attachments, because its render dims drive `render_extent`:
        // when an upscaler builds, the whole scene pipeline renders at
        // `round(swapchain_extent * upscale_scale)` and the upscaler
        // reconstructs the swapchain resolution. When `temporal_upscaling` is
        // off (or no backend is available) `render_extent == swapchain_extent`
        // and the pipeline collapses to native-resolution rendering. Bloom /
        // composite / swapchain always stay at `swapchain_extent`.
        // `build_upscaler` resolves `upscale_backend` against availability with
        // a DLSS -> XeSS -> FSR -> native fallback (the DLSS / XeSS device
        // extensions were enabled above via `upscale_sdk`).
        let upscale = if temporal_upscaling {
            let (built, resolved) = super::post::build_upscaler(
                super::post::upscale::UpscalerGpu {
                    alloc: &alloc,
                    instance: &instance,
                    device: &device,
                    physical_device,
                    command_pool,
                    queue: graphics_queue,
                },
                swapchain_extent.width,
                swapchain_extent.height,
                upscale_scale,
                upscale_backend,
            )?;
            // Arm the messenger's benign-error budget for DLSS (see
            // `DLSS_FIRST_FRAME_LAYOUT_SUPPRESS`); a no-op for other backends.
            if resolved == super::post::ResolvedBackend::Dlss
                && let Some(f) = device.debug_filter()
            {
                f.store(
                    DLSS_FIRST_FRAME_LAYOUT_SUPPRESS,
                    std::sync::atomic::Ordering::Relaxed,
                );
            }
            built
        } else {
            None
        };
        let render_extent = match &upscale {
            Some(u) => {
                let (w, h) = u.render_dims();
                vk::Extent2D {
                    width: w,
                    height: h,
                }
            }
            None => swapchain_extent,
        };

        //  Initial reset of every timestamp query slot. Without this the first
        //  `vkGetQueryPoolResults` call on each slot (before that slot has
        //  ever been written) hits an uninitialised query and the validation
        //  layer emits a "query not reset" error. After the reset, the slot
        //  is in "unavailable" state, so `get_query_pool_results` returns
        //  NOT_READY → 0 cleanly until `record_frame` writes the first pair.
        if let Some(pool) = timestamp_query_pool {
            // SAFETY: `cmd` is a command buffer in the recording state, and every handle and slice
            // these commands name is live for the call.
            super::texture::one_shot_submit(&device, command_pool, graphics_queue, |cmd| unsafe {
                device.cmd_reset_query_pool(
                    cmd,
                    pool,
                    0,
                    (super::pass_timing::SLOTS_PER_FRAME * frames) as u32,
                );
            })?;
        }

        //  Shadow map (4-layer D32_SFLOAT array image, one slice per cascade)
        // CSM is gated on `shadow_map_size` (from GraphicsConfig; 0 disables
        // shadows). The shadow vertex shader is engine-internal (the baked
        // shadow.vert), so an empty `shadow_bytes` override no longer means
        // "no shadows": it just selects the built-in shader. Mirrors the Metal
        // internal-shadow path.
        let effective_shadow_size = shadow_map_size;
        let shadow_map = create_shadow_map_array(
            &GpuUploadContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            },
            effective_shadow_size,
            NUM_SHADOW_CASCADES as u32,
        )?;

        // Rectangular area lights: the edge vectors that do not fit in
        // `GpuLight`, indexed by its `data_index`, plus the two LTC tables the
        // shading path samples. A world with no area light still gets a
        // one-element buffer, since the shader never reads it (`data_index`
        // stays -1) but the descriptor must be valid. The tables are
        // scene-independent, so they are uploaded either way.
        let area_light_data = if area_lights.is_empty() {
            vec![crate::gfx::render_types::AreaLightData::ZERO]
        } else {
            area_lights.clone()
        };
        let area_light_size = std::mem::size_of_val(area_light_data.as_slice()) as u64;
        let area_light_buffer = alloc.create_buffer(
            area_light_size,
            vk::BufferUsageFlags::STORAGE_BUFFER,
            vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
        )?;
        upload_static_records(&area_light_buffer, &area_light_data);
        let ltc_size = crate::gfx::ltc::LTC_LUT_SIZE as u32;
        let ltc_upload = GpuUploadContext {
            alloc: &alloc,
            device: &device,
            command_pool,
            queue: graphics_queue,
        };
        let ltc_matrix_image =
            upload_float_lut(&ltc_upload, ltc_size, 4, crate::gfx::ltc::matrix_texels())?;
        let ltc_magnitude_image = upload_float_lut(
            &ltc_upload,
            ltc_size,
            2,
            crate::gfx::ltc::magnitude_texels(),
        )?;
        // Linear clamp-to-edge: the LUT is indexed by roughness / view angle, so
        // an edge sample must not wrap.
        let ltc_sampler = create_sampler_cube_linear(&device)?;

        // Spot shadow map array: one layer per shadow-casting spot, at a quarter
        // the cascade resolution (a spot slice covers a single cone, not a
        // view-frustum slab). Passing size 0 yields the 1x1 fallback, which is
        // what a world with no shadowed spot binds.
        let spot_shadow_slice_size =
            crate::gfx::render_types::spot_shadow_slice_size(effective_shadow_size);
        let spot_shadow_map = create_shadow_map_array(
            &GpuUploadContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            },
            if spot_shadows.is_empty() {
                0
            } else {
                spot_shadow_slice_size
            },
            spot_shadows.len().max(1) as u32,
        )?;

        //  Textures
        let gpu_textures: Vec<GpuImage> = if textures.is_empty() {
            vec![texture::create_fallback_white(&GpuUploadContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            })?]
        } else {
            textures
                .iter()
                .enumerate()
                .map(|(i, image)| {
                    texture::upload_texture_image(
                        &GpuUploadContext {
                            alloc: &alloc,
                            device: &device,
                            command_pool,
                            queue: graphics_queue,
                        },
                        image,
                    )
                    .map_err(|e| format!("texture[{i}]: {e}"))
                })
                .collect::<Result<Vec<_>, _>>()?
        };

        // Reserved fallbacks, in the order `FALLBACK_TEXTURE_COUNT` documents:
        // the flat-normal image a draw with no normal map samples, then the
        // white image a draw with no albedo samples. Real normal maps and
        // albedos are textures in `gpu_textures` (the shared pool) at their own
        // handle; only these two live in `fallback_textures`, past the last
        // real texture.
        let upload_ctx = GpuUploadContext {
            alloc: &alloc,
            device: &device,
            command_pool,
            queue: graphics_queue,
        };
        let gpu_fallbacks = vec![
            texture::create_fallback_flat_normal(&upload_ctx)?,
            texture::create_fallback_white(&upload_ctx)?,
        ];

        let gpu_text_atlases: Vec<GpuImage> = text_atlases
            .iter()
            .enumerate()
            .map(|(i, (w, h, px))| {
                upload_texture(
                    &GpuUploadContext {
                        alloc: &alloc,
                        device: &device,
                        command_pool,
                        queue: graphics_queue,
                    },
                    *w,
                    *h,
                    px,
                )
                .map_err(|e| format!("text_atlas[{i}]: {e}"))
            })
            .collect::<Result<Vec<_>, _>>()?;

        //  Samplers
        // Anisotropic degree for the scene sampler: enabled only when the device
        // supports `samplerAnisotropy` (the matching feature is turned on in
        // `device.rs`). Clamp the requested degree (GraphicsConfig.anisotropy) to
        // the GPU's 1..16 range and then to the device limit.
        let scene_aniso = {
            // SAFETY: a property query on a live handle; it only reads.
            let feats = unsafe { instance.get_physical_device_features(physical_device) };
            if feats.sampler_anisotropy != 0 {
                // SAFETY: a property query on a live handle; it only reads.
                let limit = unsafe { instance.get_physical_device_properties(physical_device) }
                    .limits
                    .max_sampler_anisotropy;
                (anisotropy.clamp(1, 16) as f32).min(limit)
            } else {
                1.0
            }
        };
        let linear_sampler = create_sampler_linear_repeat(&device, scene_aniso)?;
        let shadow_sampler = create_sampler_shadow(&device)?;
        let text_sampler = create_sampler_linear_clamp(&device)?;
        // Linear-clamp sampler the composite pass reads the HDR resolve with;
        // clamp keeps the FXAA neighbour taps from wrapping at screen edges.
        let composite_sampler = create_sampler_linear_clamp(&device)?;

        //  Render passes
        let main_render_pass = create_main_render_pass(&device, HDR_FORMAT, msaa_samples)?;
        let shadow_render_pass = create_shadow_render_pass(&device)?;
        let composite_render_pass = create_composite_render_pass(&device, swapchain_format)?;
        let bloom_write_pass = create_bloom_render_pass(&device, HDR_FORMAT, false)?;
        let bloom_blend_pass = create_bloom_render_pass(&device, HDR_FORMAT, true)?;

        //  Off-screen HDR attachments (one set per frame-in-flight slot)
        let (color_images, depth_images, hdr_resolve_images) = create_attachments(
            &AttachmentDeviceCtx {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            },
            render_extent.width,
            render_extent.height,
            msaa_samples,
            frames,
        )?;

        //  Framebuffers
        let framebuffers = create_main_framebuffers(
            &device,
            main_render_pass.handle(),
            &color_images,
            &depth_images,
            &hdr_resolve_images,
            render_extent,
            msaa_samples,
        )?;
        let composite_framebuffers = create_composite_framebuffers(
            &device,
            composite_render_pass.handle(),
            &swapchain_image_views,
            swapchain_extent,
        )?;

        //  Transient image pool: the graph-owned transients (`ao_output`,
        //  `bloom_top`, and the three G-buffer colour channels). Built before the
        //  bloom chain so bloom mip 0 binds the pooled `bloom_top` image, before
        //  SSAO (below) so its blur framebuffers + the main pass binding 6 bind
        //  the pooled `ao_output`, and before the G-buffer pre-pass so its
        //  framebuffers bind the pooled MRT channels.
        let bloom_on = post_process.bloom_intensity > 0.0;
        let rt_wanted = rt_settings.is_some() && rt_capable;
        //  The unified pre-pass exists when any screen-space consumer needs it.
        //  Derived once here rather than restated at the build site below: the
        //  pool gate and the feature gate disagreeing would mean the pool places
        //  no images while the feature expects them, or the reverse.
        let gbuffer_on = taa_enabled
            || ssao_settings.is_some()
            || ssr_settings.is_some()
            || ssgi_settings.is_some()
            || rt_wanted;
        let transient_pool = super::transient_pool::TransientImagePool::build(
            &super::transient_pool::TransientPoolGpu {
                instance: &instance,
                device: &device,
                physical_device,
                command_pool,
                queue: graphics_queue,
            },
            frames,
            &super::transient_pool::transient_slots(
                ssao_settings.is_some(),
                bloom_on,
                gbuffer_on,
                render_extent,
                swapchain_extent,
            )?,
        )?;
        let bloom_top_pairs = transient_pool.pairs_for_frames("bloom_top", frames);
        let gbuffer_pooled = transient_pool.gbuffer_pooled(frames);

        //  Bloom chain (per frame-in-flight slot)
        let (bloom_mips, bloom_mip_extents) = create_bloom_chain(
            &BloomDeviceContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            },
            swapchain_extent,
            frames,
            &bloom_top_pairs,
        )?;
        let (bloom_write_framebuffers, bloom_blend_framebuffers) = create_bloom_framebuffers(
            &device,
            bloom_write_pass.handle(),
            bloom_blend_pass.handle(),
            &bloom_mips,
            &bloom_mip_extents,
        )?;

        //  Geometry buffers. See `shared_geometry_usage` for why an RT-capable
        //  device carries the acceleration-structure / storage usage here even
        //  when RT is off at launch. Inert when RT is never built.
        let rt_geo_usage = super::resources::shared_geometry_usage(rt_capable);
        let vertex_buffer = upload_geometry_buffer(
            &alloc,
            &device,
            command_pool,
            graphics_queue,
            vertices,
            vk::BufferUsageFlags::VERTEX_BUFFER | rt_geo_usage,
        )?;
        let index_buffer = upload_geometry_buffer(
            &alloc,
            &device,
            command_pool,
            graphics_queue,
            indices,
            vk::BufferUsageFlags::INDEX_BUFFER | rt_geo_usage,
        )?;
        // Empty geometry still allocates a 4-byte buffer (see
        // `upload_geometry_buffer_raw`); track the real allocation size so
        // `setup_chunk_streaming` copies the right prefix when it grows them.
        let vertex_buffer_bytes = (std::mem::size_of_val(vertices) as u64).max(4);
        let index_buffer_bytes = (std::mem::size_of_val(indices) as u64).max(4);

        //  Uniform buffers
        let view_ubo_size = std::mem::size_of::<super::draw::ViewUniforms>() as u64;
        let light_ubo_size = std::mem::size_of::<LightUniforms>() as u64;
        let shadow_ubo_size = std::mem::size_of::<ShadowUniforms>() as u64;
        // Per-scene local-light SSBO (global set 0 binding 9): created once from
        // `local_lights` and never updated per-frame. A zero-length buffer is
        // invalid, so an empty scene gets a 1-element placeholder;
        // `num_local_lights == 0` keeps the shader from reading it. Mirrors the
        // Metal `local_light_buffer`.
        let local_light_buffer_size =
            (local_lights.len().max(1) * std::mem::size_of::<GpuLight>()) as u64;

        let mut view_ubo_buffers = Vec::with_capacity(frames);
        for _ in 0..frames {
            view_ubo_buffers.push(alloc.create_buffer(
                view_ubo_size,
                vk::BufferUsageFlags::UNIFORM_BUFFER,
                vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
            )?);
        }

        // Per-frame `ProbeSet` UBO ring (global set 0 binding 7): the
        // reflection-probe count + per-probe parallax boxes. Persistently mapped;
        // `record_frame` writes `self.probe.set` here each frame.
        let probe_set_ubo_size =
            std::mem::size_of::<concinnity_core::render::uniforms::ProbeSet>() as u64;
        let mut probe_set_ubo_buffers = Vec::with_capacity(frames);
        for _ in 0..frames {
            probe_set_ubo_buffers.push(alloc.create_buffer(
                probe_set_ubo_size,
                vk::BufferUsageFlags::UNIFORM_BUFFER,
                vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
            )?);
        }

        let light_ubo = alloc.create_buffer(
            light_ubo_size,
            vk::BufferUsageFlags::UNIFORM_BUFFER,
            vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
        )?;
        // Per-frame-in-flight `ShadowUniforms` UBO ring, persistently mapped.
        // One slot per frame so writing this frame's cascade VPs cannot land in
        // memory an in-flight frame is still sampling: under `Hybrid` a far
        // cascade's VP is frozen for several frames and then jumps a whole
        // texel-snap quantum, so an aliased read samples that cascade with the
        // jumped VP against depth rasterized with the old one.
        let mut shadow_ubos = Vec::with_capacity(frames);
        for _ in 0..frames {
            shadow_ubos.push(alloc.create_buffer(
                shadow_ubo_size,
                vk::BufferUsageFlags::UNIFORM_BUFFER,
                vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
            )?);
        }
        // Static per-scene local-light SSBO; uploaded once below, never per-frame.
        let local_light_buffer = alloc.create_buffer(
            local_light_buffer_size,
            vk::BufferUsageFlags::STORAGE_BUFFER,
            vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
        )?;

        // Per-frame CSM updates use the first directional light's direction;
        // we cache it here at init so subsequent frames don't have to look it
        // up. Matches the Metal/DirectX pattern.
        let shadow_light_dir = crate::gfx::lights::sun_direction(&light_uniforms);
        // Sun direction + intensity-weighted colour for the volumetric-fog
        // encoder, cached because the light UBO is uploaded rather than pushed
        // each frame. `update_directional_lights` re-derives both.
        let fog_sun_dir = shadow_light_dir;
        let fog_sun_color = crate::gfx::lights::sun_color(&light_uniforms);
        let shadow_uniforms = crate::gfx::csm::empty_shadow_uniforms();
        for ubo in &shadow_ubos {
            upload_shadow_uniforms(ubo, &shadow_uniforms);
        }
        upload_light_uniforms(&light_ubo, &light_uniforms);
        // Empty scene keeps the 1-element placeholder (nothing copied in).
        upload_static_records(&local_light_buffer, &local_lights);

        // Clustered light binning. The per-cluster list + `ClusterParams` buffers
        // are always allocated (the forward shaders reference bindings 10 + 11
        // unconditionally, guarded by `use_clusters`); the compute pipeline is
        // built only when the world has local lights to bin, which is also what
        // gates the `LightCull` graph node.
        let light_cull = super::light_cull::build_light_cull(
            &alloc,
            &device,
            frames,
            local_light_buffer.buffer(),
            local_light_buffer_size,
            !local_lights.is_empty(),
            hot_reload,
        )?;

        //  IBL resources (always created so descriptor bindings 4/5 are valid)
        let cube_sampler = create_sampler_cube_linear(&device)?;
        let env_map = if let Some(bytes) = env_map_bytes {
            let view = crate::bake::environment_map::deserialise(bytes)
                .map_err(|e| format!("EnvironmentMap payload malformed: {}", e))?;
            upload_environment_map(
                &GpuUploadContext {
                    alloc: &alloc,
                    device: &device,
                    command_pool,
                    queue: graphics_queue,
                },
                view.irradiance_face,
                view.irradiance_bytes,
                view.prefilter_face,
                &view.prefilter_mip_bytes,
            )?
        } else {
            EnvironmentMapTextures {
                irradiance: texture::create_fallback_cubemap(
                    &GpuUploadContext {
                        alloc: &alloc,
                        device: &device,
                        command_pool,
                        queue: graphics_queue,
                    },
                    [0.05, 0.05, 0.05, 1.0],
                )?,
                prefilter: texture::create_fallback_cubemap(
                    &GpuUploadContext {
                        alloc: &alloc,
                        device: &device,
                        command_pool,
                        queue: graphics_queue,
                    },
                    [0.05, 0.05, 0.05, 1.0],
                )?,
                prefilter_mip_count: 0,
            }
        };

        // Colour-grading LUT: upload the declared `ColorLut` payload, or build a
        // 2x2x2 identity LUT so the composite pass always binds a valid 3D
        // texture. With the identity LUT the grade is a no-op at any strength.
        let color_lut = if let Some(bytes) = color_lut_bytes {
            let (size, data) = crate::bake::color_lut::deserialise(bytes)
                .map_err(|e| format!("ColorLut payload malformed: {e}"))?;
            upload_color_lut(
                &GpuUploadContext {
                    alloc: &alloc,
                    device: &device,
                    command_pool,
                    queue: graphics_queue,
                },
                size,
                data,
            )?
        } else {
            create_fallback_color_lut(&GpuUploadContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            })?
        };

        //  Descriptor set layouts
        // Global set 0 is bound by the geometry path, glass, and the SSR resolve
        // alike, so its sampler cost is paid by all three pipeline layouts.
        // `maxPerStageDescriptorSamplers` is 16 on MoltenVK (Metal's per-stage
        // sampler argument table, reported the same under every argument-buffer
        // mode) against six figures on desktop drivers, which is not enough for
        // the set plus the widest of those passes. Such a device declares the set
        // update-after-bind so it budgets against
        // `maxPerStageDescriptorUpdateAfterBindSamplers` (1024 on MoltenVK) and
        // drops out of the plain per-layout count entirely. Desktop stays on the
        // plain path untouched.
        let max_per_stage_samplers =
            // SAFETY: a property query on a live handle; it only reads.
            unsafe { instance.get_physical_device_properties(physical_device) }
                .limits
                .max_per_stage_descriptor_samplers;
        let global_constrained =
            super::descriptor_layout::sampler_budget_is_constrained(max_per_stage_samplers);
        if global_constrained && !update_after_bind {
            tracing::warn!(
                "global descriptor set: per-stage sampler budget ({max_per_stage_samplers}) is \
                 too tight for the widest pass and update-after-bind is unavailable; the \
                 reflection-probe cube array will be clamped"
            );
        }
        let global_update_after_bind = global_constrained && update_after_bind;
        // Reflection-probe cube-array length this device affords. Sizes the
        // binding below, the descriptor pool, every probe cube write, the GLSL
        // arrays, and the placement list, so they can never disagree.
        let probe_cube_count = super::descriptor_layout::probe_cube_array_count(
            max_per_stage_samplers,
            global_update_after_bind,
        );
        if (probe_cube_count as usize) < concinnity_core::render::uniforms::MAX_PROBES {
            tracing::info!(
                "reflection probes: device sampler headroom binds {probe_cube_count} of {}",
                concinnity_core::render::uniforms::MAX_PROBES
            );
        }
        // Global set (set 0): view UBO, light UBO, shadow UBO, shadow array
        // sampler (binding 3), IBL irradiance cube (4), IBL prefilter cube (5),
        // SSAO occlusion (binding 6, bound to the live `ssao.ao` image when
        // SSAO is enabled, otherwise to the 1×1 `ssao_white` fallback so the
        // main pass's `ambient *= ao` multiplier collapses to a pass-through).
        // Global set (set 0): the geometry path's view / light / shadow UBOs +
        // shadow-map + IBL cubes + SSAO sampler + ProbeSet UBO (binding 7) + the
        // reflection-probe cube array (binding 8). Binding table + lock-down test
        // live in `descriptor_layout.rs`. Built inline (not via the count-1
        // `create_descriptor_set_layout` helper) because binding 8 is a
        // `probe_cube_count` cube array; the count-1 bindings come from the locked
        // `global_set()` table, then the array binding is appended (the same shape
        // as the bindless texture pool's array binding below).
        let global_set_layout = {
            let mut bindings: Vec<vk::DescriptorSetLayoutBinding> =
                super::descriptor_layout::global_set()
                    .iter()
                    .map(|&(b, ty, stage)| {
                        vk::DescriptorSetLayoutBinding::default()
                            .binding(b)
                            .descriptor_type(ty)
                            .descriptor_count(1)
                            .stage_flags(stage)
                    })
                    .collect();
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::PROBE_CUBE_ARRAY_BINDING)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .descriptor_count(probe_cube_count)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            // Binding 9: per-scene local-light SSBO (count-1 STORAGE_BUFFER, FS).
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::LOCAL_LIGHT_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            // Binding 10: ClusterParams UBO + binding 11: the per-cluster
            // light-index lists the LightCull compute pass writes.
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::CLUSTER_PARAMS_UBO_BINDING)
                    .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::CLUSTER_LIGHT_LIST_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            // Spot shadows: the depth array the forward pass compares against
            // and the per-slice projections it projects through.
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::SPOT_SHADOW_MAP_BINDING)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::SPOT_SHADOW_DATA_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            // Area lights: the per-scene table and the two LTC lookups.
            bindings.push(
                vk::DescriptorSetLayoutBinding::default()
                    .binding(super::descriptor_layout::AREA_LIGHT_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            );
            for b in [
                super::descriptor_layout::LTC_MATRIX_BINDING,
                super::descriptor_layout::LTC_MAGNITUDE_BINDING,
            ] {
                bindings.push(
                    vk::DescriptorSetLayoutBinding::default()
                        .binding(b)
                        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                        .descriptor_count(1)
                        .stage_flags(vk::ShaderStageFlags::FRAGMENT),
                );
            }
            // On a sampler-constrained device the whole set is declared
            // update-after-bind, which is purely how it is budgeted: no binding
            // takes `VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT`, so the update
            // timing rules are unchanged and no extra descriptor-indexing feature
            // is required. Every pool that allocates the set must declare the
            // matching flag in turn.
            let mut info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings);
            if global_update_after_bind {
                info = info.flags(vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL);
            }
            device
                .create_descriptor_set_layout(&info)
                .map_err(|e| format!("global set layout: {e}"))?
        };
        // Per-object set (set 1): albedo + normal map.
        let object_set_layout =
            create_descriptor_set_layout(&device, &super::descriptor_layout::object_set())?;
        // Text set (set 0 for text pass): atlas sampler.
        let text_set_layout = create_descriptor_set_layout(
            &device,
            &[(
                0,
                vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
                vk::ShaderStageFlags::FRAGMENT,
            )],
        )?;
        // Shadow global set (set 0 for shadow pass): ShadowUniforms UBO.
        let shadow_global_set_layout =
            create_descriptor_set_layout(&device, &super::descriptor_layout::shadow_global_set())?;
        // Composite set (set 0 for composite pass): HDR resolve image at
        // binding 0, bloom mip 0 at binding 1, the 3D colour LUT at binding 2,
        // then the G-buffer channels the debug view modes visualize (3 =
        // normal+depth, 4 = roughness, 5 = SSAO occlusion).
        let composite_set_layout = create_descriptor_set_layout(
            &device,
            &(0..6)
                .map(|b| {
                    (
                        b,
                        vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
                        vk::ShaderStageFlags::FRAGMENT,
                    )
                })
                .collect::<Vec<_>>(),
        )?;
        // Bloom set (set 0 for every bloom pass): the single input image.
        let bloom_set_layout = create_descriptor_set_layout(
            &device,
            &[(
                0,
                vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
                vk::ShaderStageFlags::FRAGMENT,
            )],
        )?;

        //  Pipeline layouts
        // Main push constants: 112 bytes for model (64) + material (48).
        let main_pc_range = vk::PushConstantRange::default()
            .stage_flags(vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT)
            .offset(0)
            .size(112);
        let main_set_layouts = [global_set_layout.handle(), object_set_layout.handle()];
        let main_pipeline_layout = device
            .create_pipeline_layout(
                &vk::PipelineLayoutCreateInfo::default()
                    .set_layouts(&main_set_layouts)
                    .push_constant_ranges(std::slice::from_ref(&main_pc_range)),
            )
            .map_err(|e| format!("main pipeline layout: {e}"))?;

        let shadow_pc_range = vk::PushConstantRange::default()
            .stage_flags(vk::ShaderStageFlags::VERTEX)
            .offset(0)
            // 64 bytes for model + 16 bytes for cascade_idx + padding.
            .size(80);
        let shadow_set_layouts = [shadow_global_set_layout.handle()];
        let shadow_pipeline_layout = device
            .create_pipeline_layout(
                &vk::PipelineLayoutCreateInfo::default()
                    .set_layouts(&shadow_set_layouts)
                    .push_constant_ranges(std::slice::from_ref(&shadow_pc_range)),
            )
            .map_err(|e| format!("shadow pipeline layout: {e}"))?;

        let text_pc_range = vk::PushConstantRange::default()
            .stage_flags(vk::ShaderStageFlags::VERTEX)
            .offset(0)
            .size(16);
        let text_set_layouts = [text_set_layout.handle()];
        let text_pipeline_layout = device
            .create_pipeline_layout(
                &vk::PipelineLayoutCreateInfo::default()
                    .set_layouts(&text_set_layouts)
                    .push_constant_ranges(std::slice::from_ref(&text_pc_range)),
            )
            .map_err(|e| format!("text pipeline layout: {e}"))?;

        // Post-process push constant: the full `PostProcessParams` struct,
        // fragment-stage. Read by the bloom-prefilter shader.
        let post_pc_range = vk::PushConstantRange::default()
            .stage_flags(vk::ShaderStageFlags::FRAGMENT)
            .offset(0)
            .size(std::mem::size_of::<crate::gfx::render_types::PostProcessParams>() as u32);

        // The composite shader reads the same tunables plus the scene fade, so
        // its range covers the wider `CompositeParams`.
        let composite_pc_range = vk::PushConstantRange::default()
            .stage_flags(vk::ShaderStageFlags::FRAGMENT)
            .offset(0)
            .size(std::mem::size_of::<crate::gfx::render_types::CompositeParams>() as u32);

        // Composite layout: one descriptor set (HDR resolve + bloom mip 0).
        let composite_set_layouts = [composite_set_layout.handle()];
        let composite_pipeline_layout = device
            .create_pipeline_layout(
                &vk::PipelineLayoutCreateInfo::default()
                    .set_layouts(&composite_set_layouts)
                    .push_constant_ranges(std::slice::from_ref(&composite_pc_range)),
            )
            .map_err(|e| format!("composite pipeline layout: {e}"))?;

        // Bloom layout: one descriptor set (the input image) + the shared
        // post-process push constant (read only by the prefilter).
        let bloom_set_layouts = [bloom_set_layout.handle()];
        let bloom_pipeline_layout = device
            .create_pipeline_layout(
                &vk::PipelineLayoutCreateInfo::default()
                    .set_layouts(&bloom_set_layouts)
                    .push_constant_ranges(std::slice::from_ref(&post_pc_range)),
            )
            .map_err(|e| format!("bloom pipeline layout: {e}"))?;

        //  Pipelines
        let (vert_spv, frag_spv) = resolve_main_shaders(hot_reload, vert_bytes, frag_bytes)?;
        let main_pipeline = create_main_pipeline(
            &device,
            MeshPipelineTargets {
                render_pass: main_render_pass.handle(),
                layout: main_pipeline_layout.handle(),
                vert_spv: &vert_spv,
                frag_spv: &frag_spv,
            },
            msaa_samples,
            swapchain_format,
        )?;

        //  Instanced pipeline (optional)
        // Set 2 binding 0 is a storage buffer of per-instance world matrices.
        let need_instanced = !instanced_clusters.is_empty();
        let instance_set_layout_opt = if need_instanced {
            Some(create_descriptor_set_layout(
                &device,
                &[(
                    0,
                    vk::DescriptorType::STORAGE_BUFFER,
                    vk::ShaderStageFlags::VERTEX,
                )],
            )?)
        } else {
            None
        };

        let (instanced_pipeline_opt, instanced_pipeline_layout_opt) = if need_instanced {
            let instance_set_layout = instance_set_layout_opt
                .as_ref()
                .expect("instance set layout was created because instanced draws are needed");
            let instanced_set_layouts = [
                global_set_layout.handle(),
                object_set_layout.handle(),
                instance_set_layout.handle(),
            ];
            let instanced_pl = device
                .create_pipeline_layout(
                    &vk::PipelineLayoutCreateInfo::default()
                        .set_layouts(&instanced_set_layouts)
                        .push_constant_ranges(std::slice::from_ref(&main_pc_range)),
                )
                .map_err(|e| format!("instanced pipeline layout: {e}"))?;

            let inst_spv_opt =
                resolve_instanced_shader(hot_reload, vert_instanced_bytes, need_instanced)?
                    .ok_or("instanced shader payload missing")?;
            let pipeline = create_instanced_pipeline(
                &device,
                MeshPipelineTargets {
                    render_pass: main_render_pass.handle(),
                    layout: instanced_pl.handle(),
                    vert_spv: &inst_spv_opt,
                    frag_spv: &frag_spv,
                },
                msaa_samples,
                swapchain_format,
            )?;
            (Some(pipeline), Some(instanced_pl))
        } else {
            (None, None)
        };

        let (shadow_pipeline_opt, shadow_framebuffers_vec) = if effective_shadow_size > 0
            && let Ok(Some(shadow_spv)) = resolve_shadow_shader(hot_reload, shadow_bytes)
        {
            let pl = create_shadow_pipeline(
                &device,
                shadow_render_pass.handle(),
                shadow_pipeline_layout.handle(),
                &shadow_spv,
            )?;
            let fbs = create_shadow_framebuffers(
                &device,
                shadow_render_pass.handle(),
                &shadow_map,
                effective_shadow_size,
            )?;
            (Some(pl), fbs)
        } else {
            // No shadow pipeline: no transition needed. create_shadow_map_array
            // already rests the (1x1 fallback) shadow_map in SHADER_READ_ONLY,
            // the layout the main-pass descriptor expects, and with no shadow
            // loop nothing ever moves it out of that layout.
            (None, Vec::new())
        };

        // Spot shadows reuse the cascade pass's depth-only render pass, pipeline
        // and one-UBO set layout; only the framebuffers, the per-slice
        // projections, and the per-slice uniform slots are their own. Built even
        // with no shadowed spot (the 1x1 fallback array + a one-element buffer)
        // so the main pass's bindings 12/13 are always valid.
        let spot_shadow =
            super::spot_shadow::build_spot_shadow(super::spot_shadow::SpotShadowBuild {
                alloc: &alloc,
                instance: &instance,
                device: &device,
                physical_device,
                map: spot_shadow_map,
                render_pass: shadow_render_pass.handle(),
                set_layout: shadow_global_set_layout.handle(),
                slice_size: spot_shadow_slice_size,
                spot_shadows: &spot_shadows,
            })?;

        // Text renders in the composite pass (post-tonemap, single-sample), so
        // its pipeline targets the composite render pass.
        let text_pipeline_opt = if !gpu_text_atlases.is_empty() {
            let (tv, tf) = compile_text_shaders(hot_reload)?;
            let tp = create_text_pipeline(
                &device,
                composite_render_pass.handle(),
                text_pipeline_layout.handle(),
                &tv,
                &tf,
                vk::SampleCountFlags::TYPE_1,
            )?;
            Some(tp)
        } else {
            None
        };

        //  Composite (post-process) pipeline
        let composite_pipeline = {
            let (cv, cf) = compile_composite_shaders(hot_reload)?;
            create_composite_pipeline(
                &device,
                composite_render_pass.handle(),
                composite_pipeline_layout.handle(),
                &cv,
                &cf,
            )?
        };

        //  Bloom pipelines (prefilter / downsample / upsample)
        let (bloom_pipeline_prefilter, bloom_pipeline_downsample, bloom_pipeline_upsample) = {
            let bs = compile_bloom_shaders(hot_reload)?;
            let prefilter = create_bloom_pipeline(
                &device,
                bloom_write_pass.handle(),
                bloom_pipeline_layout.handle(),
                &bs.vert,
                &bs.prefilter,
                false,
            )?;
            let downsample = create_bloom_pipeline(
                &device,
                bloom_write_pass.handle(),
                bloom_pipeline_layout.handle(),
                &bs.vert,
                &bs.downsample,
                false,
            )?;
            // The upsample pipeline targets the LOAD blend pass and blends
            // additively onto the mip already there.
            let upsample = create_bloom_pipeline(
                &device,
                bloom_blend_pass.handle(),
                bloom_pipeline_layout.handle(),
                &bs.vert,
                &bs.upsample,
                true,
            )?;
            (prefilter, downsample, upsample)
        };

        //  SSAO (GTAO): pre-pass + kernel + blur, plus a 1×1 white fallback
        //  that is always bound at set 0 binding 6 when SSAO is off so the
        //  main pass's `ambient *= ao` multiplier collapses to a pass-through.
        let ssao_white = texture::create_fallback_white(&GpuUploadContext {
            alloc: &alloc,
            device: &device,
            command_pool,
            queue: graphics_queue,
        })?;
        // The transient image pool was built above (before the bloom chain); it
        // already holds this frame's pooled `ao_output` views when SSAO is on.
        let ssao_opt = if let Some(settings) = ssao_settings {
            let ao_views = transient_pool.views_for_frames("ao_output", frames);
            Some(super::post::ssao::SsaoResources::new(
                &super::post::ssao::SsaoDeviceCtx {
                    alloc: &alloc,
                    device: &device,
                },
                render_extent.width,
                render_extent.height,
                frames,
                settings,
                &ao_views,
                hot_reload,
            )?)
        } else {
            None
        };

        //  SSR (screen-space reflections): depth + normal + roughness pre-pass
        //  and a fullscreen ray-march resolve. The pre-pass G-buffer is shared
        //  with SSGI, so `SsrResources` is built whenever SSR *or* SSGI is on;
        //  the resolve half only does its work (and owns the post-stack scene
        //  image) when SSR reflections are actually enabled (`ssr_resolve_on`).
        //  When the resolve is on, the bloom prefilter + composite + (optional)
        //  TAA scene input is re-pointed at `SsrResources::output` further down
        //  so the post stack consumes the HDR scene with reflections composited
        //  in; a SSGI-only build leaves those pointed at the raw HDR resolve
        //  (SSGI composites its bounce into it earlier on the RMW chain).
        // The SSR resolve runs only when SSR is authored AND ray-traced
        // reflections are not live (RT replaces the resolve in the same graph
        // slot; resolved below once `rt_wanted` + the AS build are known).
        let ssr_authored = ssr_settings.is_some();
        // For the pre-pass build the resolve settings drive the resolve
        // pipeline's tunables; a SSGI-only / RT-only build has no authored SSR
        // settings, so fall back to the defaults (the resolve never runs, so the
        // values are inert, but `SsrResources::new` needs a concrete `SsrSettings`).
        let ssr_build_settings =
            ssr_settings.unwrap_or_else(|| crate::gfx::ssr::SsrSettings::resolve(0.0, 0.0));
        // RT reflections reuse the SSR depth + normal + roughness pre-pass
        // G-buffer (like SSGI), so the pre-pass half is built whenever SSR, SSGI,
        // *or* RT (and the device supports it) is on. `rt_wanted` is derived up
        // with the transient pool's gates.
        let ssr_opt = if ssr_settings.is_some() || ssgi_settings.is_some() || rt_wanted {
            let settings = ssr_build_settings;
            let hdr_views: Vec<vk::ImageView> =
                hdr_resolve_images.iter().map(|img| img.view).collect();
            Some(super::post::ssr::SsrResources::new(
                &super::post::ssr::SsrGpuContext {
                    alloc: &alloc,
                    device: &device,
                    command_pool,
                    queue: graphics_queue,
                },
                super::post::ssr::SsrExtent {
                    width: render_extent.width,
                    height: render_extent.height,
                },
                frames,
                super::post::ssr::SsrInitInputs {
                    settings,
                    hdr_resolve_views: &hdr_views,
                    prefilter_view: env_map.prefilter.view,
                    cube_sampler: cube_sampler.handle(),
                    global_set_layout: global_set_layout.handle(),
                    probe_cube_count,
                },
                hot_reload,
            )?)
        } else {
            None
        };

        //  Unified geometry G-buffer pre-pass. Built whenever any screen-space
        //  consumer of the merged buffer is on: SSR resolve / SSGI / RT (all
        //  fold into `ssr_opt`), SSAO, or the velocity channel a TAA / upscale
        //  consumer needs (`taa_enabled`). One jittered traversal rasterises the
        //  normal+depth / roughness / velocity MRT every reader then samples,
        //  replacing the separate SSR / SSAO / velocity pre-passes. The skinned
        //  variant is built lazily by `upload_skinned` once the joint-set layout
        //  exists (it doesn't at init). Mirrors the DirectX `self.gbuffer` build.
        //  The gate is `gbuffer_on`, the same value the transient pool was built
        //  from, so the pool cannot place the MRT channels for a pre-pass that is
        //  not built (harmless) or -- the dangerous direction -- leave them
        //  unplaced for one that is.
        let gbuffer_opt = if gbuffer_on {
            Some(super::post::gbuffer::GbufferResources::new(
                super::post::gbuffer::GbufferDeviceCtx {
                    alloc: &alloc,
                    device: &device,
                },
                super::post::gbuffer::GbufferQueueCtx {
                    command_pool,
                    queue: graphics_queue,
                },
                super::post::gbuffer::GbufferExtent {
                    width: render_extent.width,
                    height: render_extent.height,
                    frames,
                },
                super::post::gbuffer::GbufferSsboLayouts {
                    instance: instance_set_layout_opt.as_ref().map(|l| l.handle()),
                    // Skinned variant built lazily by `upload_skinned` via
                    // `ensure_skinned_gbuffer_pso` (the joint-set layout does not
                    // exist yet at init time), matching the gbuffer / TAA.
                    skinned: None,
                },
                draw_objects.len(),
                hot_reload,
                &gbuffer_pooled,
            )?)
        } else {
            None
        };

        //  SSGI (screen-space global illumination): the hemisphere-gather +
        //  depth-aware-blur GI pass. Built only when the world selected
        //  `indirect_lighting: ssgi`; it samples the unified pre-pass G-buffer
        //  (`gbuffer_opt` is guaranteed `Some` here because SSGI forces `ssr_opt`
        //  on, which the gbuffer gate ORs in). The gather samples each frame's
        //  HDR resolve as the bounce-radiance source and the composite additively
        //  blends the denoised indirect term back into the same image on the RMW
        //  chain. Its G-buffer binding is re-pointed at the unified per-frame
        //  views further down; the first view is the valid init placeholder.
        let ssgi_opt = if let Some(settings) = ssgi_settings {
            let gb = gbuffer_opt
                .as_ref()
                .expect("SSGI build forces the unified G-buffer pre-pass to exist");
            let nd_views = gb.normal_depth_views();
            let hdr_views: Vec<vk::ImageView> =
                hdr_resolve_images.iter().map(|img| img.view).collect();
            Some(super::post::ssgi::SsgiResources::new(
                super::post::ssgi::SsgiDevice {
                    alloc: &alloc,
                    device: &device,
                },
                render_extent.width,
                render_extent.height,
                frames,
                settings,
                super::post::ssgi::SsgiInputViews {
                    hdr_resolve_views: &hdr_views,
                    gbuffer_view: nd_views[0],
                },
                hot_reload,
            )?)
        } else {
            None
        };

        // Instanced props fold into the GPU-driven bindless cull buffers: each
        // instance becomes a `GpuObjectData` record appended after the `n_objects`
        // static records (written once at init below), so the object / draw-args /
        // indirect / cull-status buffers size for the combined `n_cull` count and
        // the cull kernel tests every instance independently. Skinned objects fold
        // in after the instances (a per-frame-rebuilt tail of `n_skinned` records),
        // so `n_cull` reserves their slots too. Mirrors `directx/init`.
        let n_instances: usize = instanced_clusters.iter().map(|c| c.instances.len()).sum();
        // Streamed-chunk record reserve (`[n_objects + n_instances, +n_chunk_max)`),
        // between the instances and the skinned tail; resident chunks fold in per
        // frame. 0 for a non-voxel world.
        let n_cull = draw_objects.len() + n_instances + n_chunk_max + n_skinned;

        // Bindless static pass: active when the world uses the built-in shader AND
        // there is ANYTHING to GPU-drive -- build-time static geometry, instances,
        // streamed chunks, or skinned meshes (`n_cull > 0`). A pure-voxel world has
        // no build-time geometry but folds its chunks here. Its texture pool is the
        // deduplicated [albedo..] ++ [normal-map..] image set
        // (`gpu_textures.len() + gpu_normal_maps.len()`); the helper derives the
        // same value from the texture table so the export-time precompile matches.
        let bindless_active = !is_spirv(vert_bytes) && !is_spirv(frag_bytes) && n_cull > 0;
        // Whether this device can declare the pool at its fixed ceiling rather
        // than sizing it to the world. Two things have to hold, and both are
        // about never needing to clamp or truncate: the ceiling has to fit the
        // plain per-stage sampler budget (six figures on every desktop driver,
        // 16 on MoltenVK), and the world's own textures have to fit inside the
        // ceiling. Where either fails the pool is sized to the world exactly as
        // before, which is also what keeps every index in range by construction.
        //
        // The payoff is that `POOL_SIZE` stops depending on the world, so the
        // build script can compile these shaders ahead of time; a device that
        // falls back simply misses those artifacts and compiles.
        let ceiling_fits = bindless_active
            && !super::descriptor_layout::bindless_pool_needs_update_after_bind(
                max_per_stage_samplers,
                probe_cube_count,
                concinnity_core::render::uniforms::BINDLESS_POOL_SIZE as u32,
                global_update_after_bind,
            )
            && super::builtins::world_pool_size(textures.len())
                <= concinnity_core::render::uniforms::BINDLESS_POOL_SIZE;
        let bindless_pool_size = if bindless_active {
            super::builtins::bindless_pool_size(textures.len(), ceiling_fits)
        } else {
            0
        };
        if bindless_active && !ceiling_fits {
            tracing::debug!(
                "bindless texture pool: sized to the world ({bindless_pool_size}); this device \
                 cannot seat the {} slot ceiling, so its shaders compile at init",
                concinnity_core::render::uniforms::BINDLESS_POOL_SIZE
            );
        }
        // The texture pool's length is the world's texture table, so it cannot be
        // clamped to the device's per-stage sampler headroom the way the probe
        // cube array is. Where it does not fit, its set layout is declared
        // update-after-bind, which moves it off `maxPerStageDescriptorSamplers`
        // (16 on MoltenVK) and onto the update-after-bind limit (1024 there). This
        // reshapes the layout, its binding flags, and the descriptor pool it is
        // allocated from, so it is resolved once here. Desktop drivers report six
        // figures and always stay on the plain path.
        let pool_overflows_samplers = bindless_active
            && super::descriptor_layout::bindless_pool_needs_update_after_bind(
                max_per_stage_samplers,
                probe_cube_count,
                bindless_pool_size as u32,
                global_update_after_bind,
            );
        if pool_overflows_samplers && !update_after_bind {
            tracing::warn!(
                "bindless texture pool: {bindless_pool_size} samplers exceed the device's \
                 per-stage budget ({max_per_stage_samplers}) and update-after-bind is \
                 unavailable"
            );
        }
        let bindless_uab = pool_overflows_samplers && update_after_bind;

        //  Descriptor pool
        let n_obj = draw_objects.len().max(1) as u32;
        let n_cluster = instanced_clusters.len() as u32;
        let n_atlas = gpu_text_atlases.len().max(1) as u32;
        let n_frames = frames as u32;
        let bindless_sets_count = if bindless_active { n_frames } else { 0 };
        // GPU-driven G-buffer pre-pass: one set 0 per frame (1 UBO + 1 SSBO),
        // allocated only when the bindless cull path is active AND the G-buffer is
        // enabled. The depth/MRT draw reuses the bindless GpuObjectData set (set 1),
        // so it adds no further sets here.
        let gbuffer_active = bindless_active && gbuffer_opt.is_some();
        let gbuffer_sets_count = if gbuffer_active { n_frames } else { 0 };

        // A pool size with descriptorCount 0 is invalid, so the storage-buffer
        // entry is only added when there are instanced clusters / bindless sets
        // to size it.
        let mut pool_sizes = vec![
            vk::DescriptorPoolSize::default()
                .ty(vk::DescriptorType::UNIFORM_BUFFER)
                // global (5 per frame: view + light + shadow + ProbeSet +
                // ClusterParams) + shadow global (1 per frame) + gbuffer bindless
                // GbView UBO (1 per frame).
                .descriptor_count(n_frames * 5 + n_frames + gbuffer_sets_count),
            vk::DescriptorPoolSize::default()
                .ty(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                // per-obj(2) + per-frame {shadow + spot shadow + IBL
                // irradiance + IBL prefilter + SSAO occlusion + the 2 area-light
                // LTC tables} + per-frame probe cube array + text
                // atlas + per-cluster(2) + per-frame composite(6: HDR resolve +
                // bloom mip 0 + 3D colour LUT + the 3 view-mode G-buffer
                // channels) + per-frame bindless texture pool.
                .descriptor_count(
                    n_obj * 2
                        + n_frames * 7
                        + n_frames * probe_cube_count
                        + n_atlas
                        + n_cluster * 2
                        + n_frames * 6
                        + bindless_pool_size as u32 * bindless_sets_count,
                ),
        ];
        // GPU-driven shadow: one cull set per (frame, cascade), each with 3
        // STORAGE_BUFFER descriptors (objects + draw-args + that cascade's
        // indirect-command buffer). Allocated only when the bindless cull path is
        // active AND shadows are enabled. The depth-only shadow draw reuses the
        // shadow-global + bindless sets, so it adds no sets here.
        let shadow_cull_set_count = if bindless_active && shadow_pipeline_opt.is_some() {
            n_frames * crate::gfx::render_types::NUM_SHADOW_CASCADES as u32
        } else {
            0
        };
        // Storage buffers: one per cluster per frame (instance matrices) + one
        // per frame for the bindless GpuObjectData buffer + four per frame for
        // the GPU-cull set (object + draw-args + indirect-command + cull-status
        // SSBOs) + three per (frame, cascade) for the shadow cull sets. The
        // phase-2 cull sets (two-pass occlusion) draw from their own dedicated
        // pool, so they don't enter this count.
        let storage_count = n_cluster * n_frames
            + bindless_sets_count
            + 4 * bindless_sets_count
            + 3 * shadow_cull_set_count
            // GPU-driven G-buffer: one prev_model SSBO per frame.
            + gbuffer_sets_count
            // Per-scene local-light SSBO, the per-cluster light-list SSBO, the
            // spot shadow projections SSBO, and the area-light table: one of each
            // per global set (per frame).
            + n_frames
            + n_frames
            + n_frames
            + n_frames;
        if storage_count > 0 {
            pool_sizes.push(
                vk::DescriptorPoolSize::default()
                    .ty(vk::DescriptorType::STORAGE_BUFFER)
                    .descriptor_count(storage_count),
            );
        }
        // total sets: global (n_frames) + shadow global (n_frames) + per-obj +
        // per-cluster object set + atlas + per-frame×cluster instance sets +
        // per-frame composite sets + per-frame bindless sets + per-frame
        // GPU-cull sets.
        let total_sets = n_frames
            + n_obj
            + n_frames
            + n_atlas
            + n_cluster
            + n_frames * n_cluster
            + n_frames
            + bindless_sets_count
            + bindless_sets_count
            + shadow_cull_set_count
            + gbuffer_sets_count;
        // An update-after-bind set layout can only be allocated from a pool that
        // declares the same. This pool allocates both the global sets and the
        // bindless set, so either opting in forces the flag.
        let mut pool_info = vk::DescriptorPoolCreateInfo::default()
            .pool_sizes(&pool_sizes)
            .max_sets(total_sets);
        if bindless_uab || global_update_after_bind {
            pool_info = pool_info.flags(vk::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND);
        }
        let descriptor_pool = device
            .create_descriptor_pool(&pool_info)
            .map_err(|e| format!("descriptor pool: {e}"))?;

        //  Descriptor sets
        // Global sets (one per frame).
        let global_layouts: Vec<_> = (0..frames).map(|_| global_set_layout.handle()).collect();
        let global_sets =
            alloc_descriptor_sets(&device, descriptor_pool.handle(), &global_layouts)?;
        // Update global sets.
        for (i, &set) in global_sets.iter().enumerate() {
            let view_info = vk::DescriptorBufferInfo::default()
                .buffer(view_ubo_buffers[i].buffer())
                .offset(0)
                .range(view_ubo_size);
            let light_info = vk::DescriptorBufferInfo::default()
                .buffer(light_ubo.buffer())
                .offset(0)
                .range(light_ubo_size);
            let shadow_info = vk::DescriptorBufferInfo::default()
                .buffer(shadow_ubos[i].buffer())
                .offset(0)
                .range(shadow_ubo_size);
            // Layout must match the post-cascade transition in draw.rs, which
            // flips the shadow array to SHADER_READ_ONLY_OPTIMAL.
            let shadow_img_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(shadow_map.view)
                .sampler(shadow_sampler.handle());
            // Same resting layout as the cascade array: the SpotShadow producer
            // barrier opens it for the depth loop and Main returns it here.
            let spot_shadow_img_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(spot_shadow.map.view)
                .sampler(shadow_sampler.handle());
            let spot_shadow_data_info = vk::DescriptorBufferInfo::default()
                .buffer(spot_shadow.data_buffer.buffer())
                .offset(0)
                .range(vk::WHOLE_SIZE);
            let area_light_info = vk::DescriptorBufferInfo::default()
                .buffer(area_light_buffer.buffer())
                .offset(0)
                .range(vk::WHOLE_SIZE);
            let ltc_matrix_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(ltc_matrix_image.view)
                .sampler(ltc_sampler.handle());
            let ltc_magnitude_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(ltc_magnitude_image.view)
                .sampler(ltc_sampler.handle());
            let irr_img_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(env_map.irradiance.view)
                .sampler(cube_sampler.handle());
            let pre_img_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(env_map.prefilter.view)
                .sampler(cube_sampler.handle());
            // SSAO occlusion: this frame's blurred occlusion when SSAO is on
            // (per frame in flight, pooled), or the 1×1 white fallback when it
            // is off. Either way the descriptor is bound so the main pass's
            // `ambient *= ao` always samples a valid texture.
            let ssao_view = transient_pool
                .view_for("ao_output", i)
                .unwrap_or(ssao_white.view);
            let ssao_img_info = vk::DescriptorImageInfo::default()
                .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                .image_view(ssao_view)
                .sampler(linear_sampler.handle());
            // ProbeSet UBO (binding 7): this frame's reflection-probe set.
            let probe_set_info = vk::DescriptorBufferInfo::default()
                .buffer(probe_set_ubo_buffers[i].buffer())
                .offset(0)
                .range(probe_set_ubo_size);
            // Local-light SSBO (binding 9): the single static buffer, bound into
            // every frame's global set.
            let local_light_info = vk::DescriptorBufferInfo::default()
                .buffer(local_light_buffer.buffer())
                .offset(0)
                .range(local_light_buffer_size);
            // Clustered lighting: this frame's live ClusterParams (binding 10)
            // and the shared per-cluster light lists (binding 11).
            let cluster_params_info = vk::DescriptorBufferInfo::default()
                .buffer(light_cull.params_buffers[i].buffer())
                .offset(0)
                .range(std::mem::size_of::<crate::gfx::render_types::ClusterParams>() as u64);
            let cluster_list_info = vk::DescriptorBufferInfo::default()
                .buffer(light_cull.cluster_buffer.buffer())
                .offset(0)
                .range(super::light_cull::cluster_list_size());
            // Probe cube array (binding 8): every slot points at the IBL prefilter
            // cube until a probe bakes. No descriptor-indexing extension is
            // enabled, so every one of the `probe_cube_count` descriptors must hold
            // a valid cube (an unwritten slot is UB); the EMPTY ProbeSet (count 0)
            // keeps the shader on the sky path, so these are never actually sampled
            // yet.
            let probe_cube_infos: Vec<vk::DescriptorImageInfo> = (0..probe_cube_count)
                .map(|_| {
                    vk::DescriptorImageInfo::default()
                        .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                        .image_view(env_map.prefilter.view)
                        .sampler(cube_sampler.handle())
                })
                .collect();
            let writes = [
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(0)
                    .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                    .buffer_info(std::slice::from_ref(&view_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(1)
                    .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                    .buffer_info(std::slice::from_ref(&light_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(2)
                    .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                    .buffer_info(std::slice::from_ref(&shadow_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(3)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&shadow_img_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(4)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&irr_img_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(5)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&pre_img_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(6)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&ssao_img_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(7)
                    .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                    .buffer_info(std::slice::from_ref(&probe_set_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::PROBE_CUBE_ARRAY_BINDING)
                    .dst_array_element(0)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(&probe_cube_infos),
                // Binding 9: per-scene local-light SSBO.
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::LOCAL_LIGHT_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .buffer_info(std::slice::from_ref(&local_light_info)),
                // Binding 10: ClusterParams UBO (this frame's live params).
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::CLUSTER_PARAMS_UBO_BINDING)
                    .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                    .buffer_info(std::slice::from_ref(&cluster_params_info)),
                // Binding 11: per-cluster light-index lists.
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::CLUSTER_LIGHT_LIST_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .buffer_info(std::slice::from_ref(&cluster_list_info)),
                // Binding 12: spot shadow depth array.
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::SPOT_SHADOW_MAP_BINDING)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&spot_shadow_img_info)),
                // Binding 13: per-slice spot shadow projections.
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::SPOT_SHADOW_DATA_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .buffer_info(std::slice::from_ref(&spot_shadow_data_info)),
                // Binding 14: the per-scene area-light table.
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::AREA_LIGHT_SSBO_BINDING)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .buffer_info(std::slice::from_ref(&area_light_info)),
                // Bindings 15 + 16: the two area-light LTC lookup tables.
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::LTC_MATRIX_BINDING)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&ltc_matrix_info)),
                vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(super::descriptor_layout::LTC_MAGNITUDE_BINDING)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&ltc_magnitude_info)),
            ];
            // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
            // every set and resource it names belongs to this device.
            unsafe { device.update_descriptor_sets(&writes, &[]) };
        }

        // Shadow global sets (one per frame).
        let shadow_global_layouts: Vec<_> = (0..frames)
            .map(|_| shadow_global_set_layout.handle())
            .collect();
        let shadow_global_sets =
            alloc_descriptor_sets(&device, descriptor_pool.handle(), &shadow_global_layouts)?;
        for (i, &set) in shadow_global_sets.iter().enumerate() {
            let su_info = vk::DescriptorBufferInfo::default()
                .buffer(shadow_ubos[i].buffer())
                .offset(0)
                .range(shadow_ubo_size);
            let write = vk::WriteDescriptorSet::default()
                .dst_set(set)
                .dst_binding(0)
                .descriptor_type(vk::DescriptorType::UNIFORM_BUFFER)
                .buffer_info(std::slice::from_ref(&su_info));
            // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
            // every set and resource it names belongs to this device.
            unsafe { device.update_descriptor_sets(std::slice::from_ref(&write), &[]) };
        }

        // Per-object sets.
        let object_set_layouts: Vec<_> = draw_objects
            .iter()
            .map(|_| object_set_layout.handle())
            .collect();
        let object_sets = if object_set_layouts.is_empty() {
            vec![]
        } else {
            let sets =
                alloc_descriptor_sets(&device, descriptor_pool.handle(), &object_set_layouts)?;
            let last_tex = gpu_textures.len().saturating_sub(1);
            // Resolve the image view a `normal_map_slot` samples: a real normal
            // map is a texture in the shared pool at its own slot;
            // `NO_NORMAL_MAP_SLOT` selects the flat-normal fallback (the first
            // entry of `gpu_fallbacks`). `NO_ALBEDO_SLOT` likewise selects the
            // white fallback, so an untextured material shows its tint.
            let normal_view = |nms: usize| {
                if nms == NO_NORMAL_MAP_SLOT {
                    gpu_fallbacks[0].view
                } else {
                    gpu_textures[nms.min(last_tex)].view
                }
            };
            let albedo_view = |ts: usize| {
                if ts == NO_ALBEDO_SLOT {
                    gpu_fallbacks[1].view
                } else {
                    gpu_textures[ts.min(last_tex)].view
                }
            };
            for (&set, obj) in sets.iter().zip(draw_objects.iter()) {
                let albedo_info = vk::DescriptorImageInfo::default()
                    .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                    .image_view(albedo_view(obj.texture_slot))
                    .sampler(linear_sampler.handle());
                let nm_info = vk::DescriptorImageInfo::default()
                    .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                    .image_view(normal_view(obj.normal_map_slot))
                    .sampler(linear_sampler.handle());
                let writes = [
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(0)
                        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                        .image_info(std::slice::from_ref(&albedo_info)),
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(1)
                        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                        .image_info(std::slice::from_ref(&nm_info)),
                ];
                // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
                // every set and resource it names belongs to this device.
                unsafe { device.update_descriptor_sets(&writes, &[]) };
            }
            sets
        };

        // Bindless static pass: bindless static main pass resources. A dedicated
        // set layout (set 1: SSBO + bindless texture pool), pipeline layout,
        // pipeline, per-frame GpuObjectData storage buffers, and one descriptor
        // set per frame. `None`/empty when the bindless pass is inactive.
        let (
            bindless_pipeline,
            bindless_pipeline_layout,
            bindless_set_layout,
            bindless_sets,
            object_buffers,
            bindless_main_spv,
        ) = if bindless_active {
            let set_bindings = [
                vk::DescriptorSetLayoutBinding::default()
                    .binding(0)
                    .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                    .descriptor_count(1)
                    .stage_flags(vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT),
                vk::DescriptorSetLayoutBinding::default()
                    .binding(1)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .descriptor_count(bindless_pool_size as u32)
                    .stage_flags(vk::ShaderStageFlags::FRAGMENT),
            ];
            // On a sampler-constrained device the pool binding is declared
            // update-after-bind so it budgets against the update-after-bind
            // sampler limit instead of the plain one. The pool is written once at
            // init, before any frame binds it, so nothing depends on the relaxed
            // update timing itself: this is purely how the layout is budgeted.
            let binding_flags = [
                vk::DescriptorBindingFlags::empty(),
                vk::DescriptorBindingFlags::UPDATE_AFTER_BIND,
            ];
            let mut flags_info = vk::DescriptorSetLayoutBindingFlagsCreateInfo::default()
                .binding_flags(&binding_flags);
            let mut set_info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&set_bindings);
            if bindless_uab {
                set_info = set_info
                    .flags(vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL)
                    .push_next(&mut flags_info);
            }
            let set_layout = device
                .create_descriptor_set_layout(&set_info)
                .map_err(|e| format!("bindless set layout: {e}"))?;

            let layouts = [global_set_layout.handle(), set_layout.handle()];
            let pipeline_layout = device
                .create_pipeline_layout(
                    &vk::PipelineLayoutCreateInfo::default().set_layouts(&layouts),
                )
                .map_err(|e| format!("bindless pipeline layout: {e}"))?;

            let (bvs, bfs) =
                compile_bindless_shaders(hot_reload, bindless_pool_size, probe_cube_count)?;
            let pipeline = create_main_pipeline(
                &device,
                MeshPipelineTargets {
                    render_pass: main_render_pass.handle(),
                    layout: pipeline_layout.handle(),
                    vert_spv: &bvs,
                    frag_spv: &bfs,
                },
                msaa_samples,
                swapchain_format,
            )?;

            // Per-frame GpuObjectData storage buffers, persistently mapped.
            // Sized for `n_cull` so the instanced merge's records fit past the
            // `n_objects` static prefix.
            let object_buffer_size =
                (n_cull * std::mem::size_of::<crate::gfx::render_types::GpuObjectData>()) as u64;
            let mut buffers = Vec::with_capacity(frames);
            for _ in 0..frames {
                buffers.push(alloc.create_buffer(
                    object_buffer_size,
                    vk::BufferUsageFlags::STORAGE_BUFFER,
                    vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
                )?);
            }

            // One bindless set per frame: binding 0 = that frame's SSBO,
            // binding 1 = the shared pool ([albedo views..] ++ [normal..]).
            let set_layouts: Vec<_> = (0..frames).map(|_| set_layout.handle()).collect();
            let sets = alloc_descriptor_sets(&device, descriptor_pool.handle(), &set_layouts)?;
            // Every slot the layout declares has to be written, and at the
            // ceiling there are more of them than the world fills: the world's
            // textures, then the reserved fallbacks (flat-normal, white), then
            // white again across the unused tail so a slot the shader can index
            // still names a live view. Mirrors the Metal pool's fill. Sizing
            // guarantees the world fits, so this only ever pads.
            let mut pool_infos: Vec<vk::DescriptorImageInfo> = gpu_textures
                .iter()
                .chain(gpu_fallbacks.iter())
                .map(|img| {
                    vk::DescriptorImageInfo::default()
                        .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                        .image_view(img.view)
                        .sampler(linear_sampler.handle())
                })
                .collect();
            if let Some(&tail) = pool_infos.last() {
                pool_infos.resize(bindless_pool_size, tail);
            }
            for (i, &set) in sets.iter().enumerate() {
                let buf_info = vk::DescriptorBufferInfo::default()
                    .buffer(buffers[i].buffer())
                    .offset(0)
                    .range(object_buffer_size);
                let writes = [
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(0)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .buffer_info(std::slice::from_ref(&buf_info)),
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(1)
                        .dst_array_element(0)
                        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                        .image_info(&pool_infos),
                ];
                // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
                // every set and resource it names belongs to this device.
                unsafe { device.update_descriptor_sets(&writes, &[]) };
            }

            (
                Some(pipeline),
                Some(pipeline_layout),
                Some(set_layout),
                sets,
                buffers,
                (bvs, bfs),
            )
        } else {
            (
                None,
                None,
                None,
                Vec::new(),
                Vec::new(),
                (Vec::new(), Vec::new()),
            )
        };

        // Material-referenced shaders (ShaderHandle 1..) each get their own
        // bindless main-pass pipeline, so their draws route into their own region
        // of the GPU-culled command buffer. They exist only on the bindless path:
        // a world with a legacy per-draw main shader carries no bucket routing.
        let bucket_shaders = world_shaders.get(1..).unwrap_or(&[]);
        let world_pipelines = match (bindless_pipeline_layout.as_ref(), bucket_shaders.is_empty()) {
            (Some(layout), false) => {
                let max = crate::gfx::render_types::MAX_SHADER_BUCKETS;
                if bucket_shaders.len() + 1 > max {
                    return Err(format!(
                        "world declares {} Shaders but at most {max} can be routed",
                        bucket_shaders.len() + 1
                    ));
                }
                build_world_pipeline_table(
                    &device,
                    BucketPipelineTargets {
                        render_pass: main_render_pass.handle(),
                        layout: layout.handle(),
                        msaa_samples,
                        swapchain_format,
                    },
                    bucket_shaders,
                    &bindless_main_spv,
                )?
            }
            (_, false) => {
                return Err(
                    "material-referenced world shaders need the bindless main pass, which a \
                     world-authored main shader disables"
                        .to_string(),
                );
            }
            _ => Vec::new(),
        };
        let shader_bucket_count = 1 + world_pipelines.len();

        // Hardware ray-traced reflections: the scene acceleration structure +
        // the inline-`rayQueryEXT` reflection pass. Built only when the world
        // requested it AND the device exposed the ray-query extensions
        // (`rt_wanted`). Reuses the SSR pre-pass G-buffer (forced on above) for
        // the per-pixel surface point + normal, and the bindless pool (when live)
        // for textured hit shading. Graceful-fallback throughout: no resident
        // geometry, an AS build error, or a shader compile failure leaves both
        // `None` and the graph keeps `SsrResolve`. RT takes precedence over the
        // SSR resolve in the shared graph slot, so `ssr_resolve_on` is ANDed with
        // `!rt_active` once the build outcome is known.
        // Layer 2 see-through glass is opt-in per `Material` (the `see_through`
        // arg, which implies `transparent`): see-through only looks right when the
        // space behind the glass is modelled. A material that is `transparent` but
        // NOT `see_through` renders as Layer 1 (opaque, low roughness, scene
        // reflections) = tinted reflective glass that hides the interior. This list
        // drives the transparent-pass producer, the opaque-pass skip and the
        // RT-BLAS exclude together.
        let seethrough_mesh_indices: Vec<usize> = draw_objects
            .iter()
            .enumerate()
            .filter(|(_, o)| o.material.transparent != 0 && o.material.see_through != 0)
            .map(|(i, _)| i)
            .collect();

        // Whether those meshes will be rerouted, decided here because the initial
        // BLAS is built before the transparent pass that owns the mesh producer.
        // It is the same predicate that producer is gated on. The one divergence
        // is a mesh-shader compile failure, which leaves the producer absent (and
        // logs): the meshes then render opaque but stay out of this BLAS until a
        // topology refresh re-reads `seethrough_meshes_enabled` and puts them back.
        let has_seethrough_meshes = !seethrough_mesh_indices.is_empty() && rt_capable;

        let (rt_accel_opt, rt_opt) = if rt_wanted {
            match crate::vulkan::raytrace::build_rt_accel(
                crate::vulkan::raytrace::RtDeviceCtx {
                    alloc: &alloc,
                    instance: &instance,
                    device: &device,
                    pd: physical_device,
                },
                command_pool,
                graphics_queue,
                crate::vulkan::raytrace::RtSceneGeometry {
                    vertex_buffer: vertex_buffer.buffer(),
                    index_buffer: index_buffer.buffer(),
                    draw_objects: &draw_objects,
                    clusters: &instanced_clusters,
                    albedo_count: gpu_textures.len(),
                    total_vertices: vertices.len(),
                    exclude_seethrough: has_seethrough_meshes,
                },
                frames,
                hot_reload,
            ) {
                Ok(Some(accel)) => {
                    let hdr_views: Vec<vk::ImageView> =
                        hdr_resolve_images.iter().map(|i| i.view).collect();
                    // RT reads the unified G-buffer pre-pass's per-frame
                    // normal+depth + roughness (built above whenever any consumer
                    // is on); `gbuffer_opt` is `Some` here because RT forces the
                    // pre-pass on.
                    let gb = gbuffer_opt
                        .as_ref()
                        .expect("RT forces the unified G-buffer pre-pass to exist");
                    let nd_views = gb.normal_depth_views();
                    let rough_views = gb.roughness_views();
                    let (geom_buffer, geom_size) = accel.geom_table();
                    match super::post::rt_reflections::RtReflectionsResources::new(
                        super::post::rt_reflections::RtBuild {
                            alloc: &alloc,
                            device: &device,
                            width: render_extent.width,
                            height: render_extent.height,
                            frames,
                        },
                        rt_settings.expect("rt_wanted implies rt_settings is Some"),
                        super::post::rt_reflections::RtStaticInputs {
                            vertex_buffer: vertex_buffer.buffer(),
                            index_buffer: index_buffer.buffer(),
                            hdr_resolve_views: &hdr_views,
                            gbuffer_views: &nd_views,
                            roughness_views: &rough_views,
                            prefilter_view: env_map.prefilter.view,
                            cube_sampler: cube_sampler.handle(),
                        },
                        super::post::rt_reflections::RtAccelHandles {
                            tlas: accel.tlas(),
                            geom_buffer,
                            geom_size,
                            deformed_verts: accel.deformed_verts(),
                            skinned_indices: accel.skinned_indices(),
                        },
                        super::post::rt_reflections::RtLayoutConfig {
                            bindless_set_layout: bindless_set_layout.as_ref().map(|l| l.handle()),
                            global_set_layout: global_set_layout.handle(),
                            probe_cube_count,
                            pool_size: bindless_pool_size,
                            hot_reload,
                        },
                    ) {
                        Ok(rt) => (Some(accel), Some(rt)),
                        Err(e) => {
                            tracing::warn!(
                                "RT reflections pass build failed (falling back to SSR): {e}"
                            );
                            let mut accel = accel;
                            accel.destroy(&device);
                            (None, None)
                        }
                    }
                }
                Ok(None) => {
                    tracing::info!(
                        "RT reflections requested but no resident triangle geometry to trace; \
                         using SSR"
                    );
                    (None, None)
                }
                Err(e) => {
                    tracing::warn!(
                        "RT acceleration-structure build failed (falling back to SSR): {e}"
                    );
                    (None, None)
                }
            }
        } else {
            (None, None)
        };
        let rt_active = rt_opt.is_some();
        // The SSR *resolve* owns the post-stack scene image only when SSR is
        // authored and RT did not take the slot.
        let ssr_resolve_on = ssr_authored && !rt_active;
        // Reflection composite: built whenever a reflection path owns the post-stack
        // scene image (the SSR resolve is active OR RT reflections are active, which
        // are mutually exclusive). Both resolves write radiance+weight into their
        // output target; this blurs by roughness and composites over the scene into
        // its own output, which then replaces the raw resolve output as the scene
        // image every downstream pass samples.
        let composite_opt = if rt_active || ssr_resolve_on {
            let gb = gbuffer_opt
                .as_ref()
                .expect("a reflection path implies the unified G-buffer pre-pass");
            let hdr_views: Vec<vk::ImageView> =
                hdr_resolve_images.iter().map(|img| img.view).collect();
            Some(
                super::post::reflection_composite::ReflectionCompositeResources::new(
                    &super::texture::GpuUploadContext {
                        alloc: &alloc,
                        device: &device,
                        command_pool,
                        queue: graphics_queue,
                    },
                    render_extent.width,
                    render_extent.height,
                    frames,
                    reflection_blur_scale,
                    &super::post::reflection_composite::CompositeInputViews {
                        hdr_resolve_views: &hdr_views,
                        normal_depth_views: &gb.normal_depth_views(),
                        roughness_views: &gb.roughness_views(),
                    },
                    hot_reload,
                )?,
            )
        } else {
            None
        };

        // Per-object cull-status buffers (one u32 each), built unconditionally
        // on the bindless cull path: phase-1 cull writes them (binding 3 of the
        // cull set), and phase-2 cull (two-pass occlusion) reads them. Always
        // present so the phase-1 kernel always has a valid binding; under
        // single-pass occlusion the values are simply never read. Device-local.
        // Mirrors `directx/cull.rs`.
        let cull_status_buffers = if bindless_active {
            let status_size = n_cull as u64 * std::mem::size_of::<u32>() as u64;
            let mut bufs = Vec::with_capacity(frames);
            for _ in 0..frames {
                bufs.push(alloc.create_buffer(
                    status_size,
                    vk::BufferUsageFlags::STORAGE_BUFFER,
                    vk::MemoryPropertyFlags::DEVICE_LOCAL,
                )?);
            }
            bufs
        } else {
            Vec::new()
        };

        // Compute cull: the cull compute pipeline + per-frame draw-args /
        // indirect-command buffers + descriptor sets. Built under the same
        // condition as the bindless pass: the compute kernel writes one
        // indirect draw command per build-time object, which the bindless main
        // pass issues with a single multiDrawIndexedIndirect.
        type CullPipelineResources = (
            Option<OwnedPipeline>,
            Option<OwnedPipelineLayout>,
            Option<OwnedSetLayout>,
            Vec<vk::DescriptorSet>,
            Vec<super::allocator::PooledBuffer>,
            Vec<super::allocator::PooledBuffer>,
            Option<crate::vulkan::hiz::HiZResources>,
        );
        let (
            cull_pipeline,
            cull_pipeline_layout,
            cull_set_layout,
            cull_sets,
            draw_args_buffers,
            indirect_buffers,
            hiz,
        ): CullPipelineResources = if bindless_active {
            // Set 0: object SSBO + draw-args SSBO + indirect-command SSBO +
            // cull-status SSBO (binding 3: phase-1 writes the per-object cull
            // outcome for two-pass occlusion; the phase-2 kernel reads it).
            let set_bindings: Vec<_> = (0..4u32)
                .map(|b| {
                    vk::DescriptorSetLayoutBinding::default()
                        .binding(b)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .descriptor_count(1)
                        .stage_flags(vk::ShaderStageFlags::COMPUTE)
                })
                .collect();
            let set_layout = device
                .create_descriptor_set_layout(
                    &vk::DescriptorSetLayoutCreateInfo::default().bindings(&set_bindings),
                )
                .map_err(|e| format!("cull set layout: {e}"))?;

            // Hi-Z occlusion resources. Built under the same gating as the cull
            // pipeline; its `read_set_layout` becomes set 1 of the cull
            // pipeline (sampler2D Hi-Z + per-frame CullHizParams UBO).
            let depth_views: Vec<vk::ImageView> = depth_images.iter().map(|img| img.view).collect();
            let hiz = crate::vulkan::hiz::HiZResources::new(
                crate::vulkan::hiz::HiZDeviceCtx {
                    alloc: &alloc,
                    device: &device,
                    command_pool,
                    queue: graphics_queue,
                },
                crate::vulkan::hiz::HiZTarget {
                    width: render_extent.width,
                    height: render_extent.height,
                    depth_views: &depth_views,
                },
                msaa_samples.as_raw(),
                frames,
                occlusion_two_pass,
                hot_reload,
            )?;

            let push_range = vk::PushConstantRange::default()
                .stage_flags(vk::ShaderStageFlags::COMPUTE)
                .offset(0)
                .size(CULL_PUSH_CONSTANT_BYTES);
            let layouts = [set_layout.handle(), hiz.read_set_layout.handle()];
            let pipeline_layout = device
                .create_pipeline_layout(
                    &vk::PipelineLayoutCreateInfo::default()
                        .set_layouts(&layouts)
                        .push_constant_ranges(std::slice::from_ref(&push_range)),
                )
                .map_err(|e| format!("cull pipeline layout: {e}"))?;

            let cs = compile_cull_shader(hot_reload)?;
            let pipeline = create_cull_pipeline(&device, pipeline_layout.handle(), &cs)?;

            // Per-frame GpuDrawArgs (host-visible, rebuilt each frame) and
            // indirect-command buffers (device-local, GPU-written). `n_cull`
            // covers the static objects plus the merged instances.
            let n = n_cull as u64;
            let object_buffer_size =
                n * std::mem::size_of::<crate::gfx::render_types::GpuObjectData>() as u64;
            let draw_args_size =
                n * std::mem::size_of::<crate::gfx::render_types::GpuDrawArgs>() as u64;
            // One `n_cull`-command region per shader bucket: the cull kernel writes
            // every record's slot in each region and the main pass issues one
            // indirect draw per region under that bucket's pipeline.
            let indirect_size = shader_bucket_count as u64
                * n
                * std::mem::size_of::<vk::DrawIndexedIndirectCommand>() as u64;
            let mut da_buffers = Vec::with_capacity(frames);
            let mut ind_buffers = Vec::with_capacity(frames);
            for _ in 0..frames {
                da_buffers.push(alloc.create_buffer(
                    draw_args_size,
                    vk::BufferUsageFlags::STORAGE_BUFFER,
                    vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
                )?);
                ind_buffers.push(alloc.create_buffer(
                    indirect_size,
                    vk::BufferUsageFlags::STORAGE_BUFFER | vk::BufferUsageFlags::INDIRECT_BUFFER,
                    vk::MemoryPropertyFlags::DEVICE_LOCAL,
                )?);
            }

            // One cull set per frame: that frame's object / draw-args /
            // indirect-command buffers at bindings 0 / 1 / 2.
            let set_layouts: Vec<_> = (0..frames).map(|_| set_layout.handle()).collect();
            let sets = alloc_descriptor_sets(&device, descriptor_pool.handle(), &set_layouts)?;
            for (i, &set) in sets.iter().enumerate() {
                let obj_info = vk::DescriptorBufferInfo::default()
                    .buffer(object_buffers[i].buffer())
                    .offset(0)
                    .range(object_buffer_size);
                let arg_info = vk::DescriptorBufferInfo::default()
                    .buffer(da_buffers[i].buffer())
                    .offset(0)
                    .range(draw_args_size);
                let cmd_info = vk::DescriptorBufferInfo::default()
                    .buffer(ind_buffers[i].buffer())
                    .offset(0)
                    .range(indirect_size);
                let status_info = vk::DescriptorBufferInfo::default()
                    .buffer(cull_status_buffers[i].buffer())
                    .offset(0)
                    .range(n * std::mem::size_of::<u32>() as u64);
                let writes = [
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(0)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .buffer_info(std::slice::from_ref(&obj_info)),
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(1)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .buffer_info(std::slice::from_ref(&arg_info)),
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(2)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .buffer_info(std::slice::from_ref(&cmd_info)),
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(3)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .buffer_info(std::slice::from_ref(&status_info)),
                ];
                // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
                // every set and resource it names belongs to this device.
                unsafe { device.update_descriptor_sets(&writes, &[]) };
            }

            (
                Some(pipeline),
                Some(pipeline_layout),
                Some(set_layout),
                sets,
                da_buffers,
                ind_buffers,
                Some(hiz),
            )
        } else {
            (None, None, None, Vec::new(), Vec::new(), Vec::new(), None)
        };

        // GPU-driven instanced merge: write each instance's `GpuObjectData`
        // record (+ `GpuDrawArgs`) once into every frame buffer, after the
        // `n_objects` static records. Instances are placed at world load and
        // never move, so these records are static -- the per-frame static fill
        // (`build_object_buffer` / `build_draw_args_buffer`) writes only
        // `[0, n_objects)`, leaving the instance tail intact. Only runs when the
        // bindless cull buffers exist (the bindless pass is active with build-time
        // geometry) and the world declares instanced props. Mirrors
        // `directx/init/mod.rs`.
        if n_instances > 0 && !object_buffers.is_empty() {
            use crate::gfx::render_types::{
                GpuDrawArgs, GpuObjectData, draw_args_flags, instance_object_records,
            };
            let records = instance_object_records(&instanced_clusters, gpu_textures.len() as u32);
            // Cluster base LOD slice (absolute indices, so `base_vertex = 0`);
            // per-instance LOD is a follow-up. Every instance is visible +
            // resident + cullable, so its finite per-instance world AABB is
            // frustum / distance / Hi-Z tested independently by the cull kernel.
            let mut draw_args: Vec<GpuDrawArgs> = Vec::with_capacity(records.len());
            for cluster in &instanced_clusters {
                for _ in &cluster.instances {
                    draw_args.push(GpuDrawArgs {
                        index_count: cluster.index_count as u32,
                        index_offset: cluster.index_offset as u32,
                        base_vertex: 0,
                        flags: draw_args_flags(true, true, true),
                    });
                }
            }
            let n_objects = draw_objects.len();
            let obj_stride = std::mem::size_of::<GpuObjectData>();
            let da_stride = std::mem::size_of::<GpuDrawArgs>();
            for (obj_buf, da_buf) in object_buffers.iter().zip(draw_args_buffers.iter()) {
                obj_buf.write_slice(n_objects * obj_stride, &records);
                da_buf.write_slice(n_objects * da_stride, &draw_args);
            }
        }

        // GPU-driven shadow pass resources. Built when the bindless cull path is
        // active AND shadows are enabled: a frustum + distance only cull pipeline
        // (`SHADOW_CULL`, lean 3-SSBO set: objects + draw-args + this cascade's
        // indirect buffer), one indirect buffer + cull set per (frame, cascade),
        // and a depth-only bindless graphics pipeline (shadow-global set 0 + the
        // bindless GpuObjectData set 1 + a cascade-index push constant). Each
        // re-rendered cascade then runs one cull dispatch + one
        // `cmd_draw_indexed_indirect` (static + instance prefix) + one for the
        // skinned tail, replacing the CPU per-object shadow loop.
        type ShadowCullResources = (
            Option<OwnedPipeline>,
            Option<OwnedPipelineLayout>,
            Option<OwnedSetLayout>,
            Vec<Vec<vk::DescriptorSet>>,
            Option<OwnedPipeline>,
            Option<OwnedPipelineLayout>,
            Vec<Vec<super::allocator::PooledBuffer>>,
        );
        let (
            shadow_cull_pipeline,
            shadow_cull_pipeline_layout,
            shadow_cull_set_layout,
            shadow_cull_sets,
            shadow_bindless_pipeline,
            shadow_bindless_pipeline_layout,
            shadow_indirect_buffers,
        ): ShadowCullResources = if bindless_active
            && shadow_pipeline_opt.is_some()
            && let Some(bl_set_layout) = bindless_set_layout.as_ref()
        {
            let cascades = crate::gfx::render_types::NUM_SHADOW_CASCADES;
            // Lean shadow cull set layout: objects(0) + draw-args(1) + commands(2).
            let sc_bindings: Vec<_> = (0..3u32)
                .map(|b| {
                    vk::DescriptorSetLayoutBinding::default()
                        .binding(b)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .descriptor_count(1)
                        .stage_flags(vk::ShaderStageFlags::COMPUTE)
                })
                .collect();
            let sc_set_layout = device
                .create_descriptor_set_layout(
                    &vk::DescriptorSetLayoutCreateInfo::default().bindings(&sc_bindings),
                )
                .map_err(|e| format!("shadow cull set layout: {e}"))?;

            let sc_push = vk::PushConstantRange::default()
                .stage_flags(vk::ShaderStageFlags::COMPUTE)
                .offset(0)
                .size(CULL_PUSH_CONSTANT_BYTES);
            let sc_layouts = [sc_set_layout.handle()];
            let sc_pl = device
                .create_pipeline_layout(
                    &vk::PipelineLayoutCreateInfo::default()
                        .set_layouts(&sc_layouts)
                        .push_constant_ranges(std::slice::from_ref(&sc_push)),
                )
                .map_err(|e| format!("shadow cull pipeline layout: {e}"))?;
            let sc_spv = compile_shadow_cull_shader(hot_reload)?;
            let sc_pipeline = create_cull_pipeline(&device, sc_pl.handle(), &sc_spv)?;

            // Depth-only bindless shadow graphics pipeline: shadow-global set 0 +
            // the bindless GpuObjectData set 1 + a cascade-index push constant.
            let sb_push = vk::PushConstantRange::default()
                .stage_flags(vk::ShaderStageFlags::VERTEX)
                .offset(0)
                .size(4);
            let sb_layouts = [shadow_global_set_layout.handle(), bl_set_layout.handle()];
            let sb_pl = device
                .create_pipeline_layout(
                    &vk::PipelineLayoutCreateInfo::default()
                        .set_layouts(&sb_layouts)
                        .push_constant_ranges(std::slice::from_ref(&sb_push)),
                )
                .map_err(|e| format!("shadow bindless pipeline layout: {e}"))?;
            let sb_spv = compile_shadow_bindless_vs(hot_reload)?;
            let sb_pipeline = create_shadow_pipeline(
                &device,
                shadow_render_pass.handle(),
                sb_pl.handle(),
                &sb_spv,
            )?;

            // Per-(frame, cascade) indirect buffers + cull sets. Each cull set
            // binds this frame's object + draw-args SSBOs and this cascade's
            // indirect buffer; the cull dispatch for cascade `c` binds set
            // `[frame][c]`, and the cascade's draws read buffer `[frame][c]`.
            let n = n_cull as u64;
            let object_buffer_size =
                n * std::mem::size_of::<crate::gfx::render_types::GpuObjectData>() as u64;
            let draw_args_size =
                n * std::mem::size_of::<crate::gfx::render_types::GpuDrawArgs>() as u64;
            let indirect_size = n * std::mem::size_of::<vk::DrawIndexedIndirectCommand>() as u64;
            let mut sc_indirect_bufs: Vec<Vec<super::allocator::PooledBuffer>> =
                Vec::with_capacity(frames);
            let mut sc_sets: Vec<Vec<vk::DescriptorSet>> = Vec::with_capacity(frames);
            for f in 0..frames {
                let mut bufs = Vec::with_capacity(cascades);
                for _ in 0..cascades {
                    bufs.push(alloc.create_buffer(
                        indirect_size,
                        vk::BufferUsageFlags::STORAGE_BUFFER
                            | vk::BufferUsageFlags::INDIRECT_BUFFER,
                        vk::MemoryPropertyFlags::DEVICE_LOCAL,
                    )?);
                }
                let set_layouts: Vec<_> = (0..cascades).map(|_| sc_set_layout.handle()).collect();
                let sets = alloc_descriptor_sets(&device, descriptor_pool.handle(), &set_layouts)?;
                for (c, &set) in sets.iter().enumerate() {
                    let obj_info = vk::DescriptorBufferInfo::default()
                        .buffer(object_buffers[f].buffer())
                        .offset(0)
                        .range(object_buffer_size);
                    let arg_info = vk::DescriptorBufferInfo::default()
                        .buffer(draw_args_buffers[f].buffer())
                        .offset(0)
                        .range(draw_args_size);
                    let cmd_info = vk::DescriptorBufferInfo::default()
                        .buffer(bufs[c].buffer())
                        .offset(0)
                        .range(indirect_size);
                    let writes = [
                        vk::WriteDescriptorSet::default()
                            .dst_set(set)
                            .dst_binding(0)
                            .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                            .buffer_info(std::slice::from_ref(&obj_info)),
                        vk::WriteDescriptorSet::default()
                            .dst_set(set)
                            .dst_binding(1)
                            .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                            .buffer_info(std::slice::from_ref(&arg_info)),
                        vk::WriteDescriptorSet::default()
                            .dst_set(set)
                            .dst_binding(2)
                            .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                            .buffer_info(std::slice::from_ref(&cmd_info)),
                    ];
                    // SAFETY: `writes` and the buffer/image infos it borrows are live for the call,
                    // and every set and resource it names belongs to this device.
                    unsafe { device.update_descriptor_sets(&writes, &[]) };
                }
                sc_indirect_bufs.push(bufs);
                sc_sets.push(sets);
            }

            (
                Some(sc_pipeline),
                Some(sc_pl),
                Some(sc_set_layout),
                sc_sets,
                Some(sb_pipeline),
                Some(sb_pl),
                sc_indirect_bufs,
            )
        } else {
            (None, None, None, Vec::new(), None, None, Vec::new())
        };

        // GPU-driven G-buffer pre-pass resources. Built when the bindless cull
        // path is active AND the G-buffer is enabled: a 3-MRT bindless pipeline +
        // per-frame previous-frame model SSBOs, drawn by reusing the main pass's
        // per-frame indirect buffer (camera frustum, NO extra cull dispatch). The
        // prev_model buffers' instance region is init-written inside the helper;
        // the static + skinned regions are rewritten each frame.
        type GbufferBindlessResources = (
            Option<OwnedPipeline>,
            Option<OwnedPipelineLayout>,
            Option<OwnedSetLayout>,
            Vec<vk::DescriptorSet>,
            Vec<super::allocator::PooledBuffer>,
        );
        let (
            gbuffer_bindless_pipeline,
            gbuffer_bindless_pipeline_layout,
            gbuffer_set_layout,
            gbuffer_sets,
            prev_model_buffers,
        ): GbufferBindlessResources = if let (true, Some(gb), Some(bl_set_layout)) = (
            gbuffer_active,
            gbuffer_opt.as_ref(),
            bindless_set_layout.as_ref(),
        ) {
            // Per-instance models in cluster-then-instance order (matches the
            // GpuObjectData instance records); the helper init-writes them into the
            // prev_model buffers' instance region for camera-only velocity.
            let inst_models: Vec<[[f32; 4]; 4]> = instanced_clusters
                .iter()
                .flat_map(|c| c.instances.iter().copied())
                .collect();
            let gbb = super::post::gbuffer::build_gbuffer_bindless(
                super::post::gbuffer::GbufferDeviceCtx {
                    alloc: &alloc,
                    device: &device,
                },
                super::post::gbuffer::GbufferBindlessDescriptors {
                    descriptor_pool: descriptor_pool.handle(),
                    bindless_set_layout: bl_set_layout.handle(),
                },
                gb,
                super::post::gbuffer::GbufferBindlessScene {
                    instance_models: &inst_models,
                    n_objects: draw_objects.len(),
                    n_cull,
                    frames,
                },
                hot_reload,
            )?;
            (
                Some(gbb.pipeline),
                Some(gbb.pipeline_layout),
                Some(gbb.set_layout),
                gbb.sets,
                gbb.prev_model_buffers,
            )
        } else {
            (None, None, None, Vec::new(), Vec::new())
        };

        // The reflection-probe convolution kernels, under the same gate the bake
        // itself needs: a probe capture renders through the bindless GPU cull, so a
        // world without the cull pipeline never bakes one and never needs them.
        let probe_prefilter = match cull_pipeline.is_some() {
            true => Some(super::probe_prefilter::ProbePrefilterPipelines::new(
                &device, hot_reload,
            )?),
            false => None,
        };

        // Two-pass Hi-Z occlusion resources. Built only when the world
        // requested `occlusion_two_pass` AND the bindless cull path is active:
        // the phase-2 cull pipeline (`main_phase2`, same layout as phase 1), a
        // second set of per-frame indirect buffers `Cull2` writes / `Main2`
        // reads, a dedicated descriptor pool + per-frame phase-2 cull sets
        // (bindings 0/1/2/3 = object / draw-args / second-indirect /
        // cull-status), and the phase-1/phase-2 main render passes. The Hi-Z
        // phase-2 cull-read sets live inside `HiZResources` (built above when
        // `occlusion_two_pass`). Mirrors `directx/init/pipelines.rs`.
        type TwoPassCullResources = (
            Option<OwnedPipeline>,
            Vec<vk::DescriptorSet>,
            Option<OwnedDescriptorPool>,
            Vec<super::allocator::PooledBuffer>,
            Option<OwnedRenderPass>,
            Option<OwnedRenderPass>,
        );
        let (
            cull_pipeline_phase2,
            cull_sets2,
            two_pass_pool,
            indirect_buffers2,
            main_render_pass_phase1,
            main_render_pass_phase2,
        ): TwoPassCullResources = if let (Some(set_layout), Some(pipeline_layout)) =
            (cull_set_layout.as_ref(), cull_pipeline_layout.as_ref())
            && occlusion_two_pass
        {
            let n = n_cull as u64;
            let object_buffer_size =
                n * std::mem::size_of::<crate::gfx::render_types::GpuObjectData>() as u64;
            let draw_args_size =
                n * std::mem::size_of::<crate::gfx::render_types::GpuDrawArgs>() as u64;
            // Bucket-expanded exactly like the phase-1 buffers: `Main2` issues the
            // same per-bucket regions over this buffer.
            let indirect_size = shader_bucket_count as u64
                * n
                * std::mem::size_of::<vk::DrawIndexedIndirectCommand>() as u64;
            let status_size = n * std::mem::size_of::<u32>() as u64;

            // Phase-2 cull pipeline (`main_phase2` entry, shared layout).
            let cs2 = compile_cull_shader_phase2(hot_reload)?;
            let pipeline2 = create_cull_pipeline(&device, pipeline_layout.handle(), &cs2)?;

            // Second indirect-command buffers (device-local, GPU-written).
            let mut ind2_buffers = Vec::with_capacity(frames);
            for _ in 0..frames {
                ind2_buffers.push(alloc.create_buffer(
                    indirect_size,
                    vk::BufferUsageFlags::STORAGE_BUFFER | vk::BufferUsageFlags::INDIRECT_BUFFER,
                    vk::MemoryPropertyFlags::DEVICE_LOCAL,
                )?);
            }

            // Dedicated descriptor pool for the per-frame phase-2 cull sets
            // (4 storage buffers each), kept off the shared pool's exact sizing.
            let pool_size = vk::DescriptorPoolSize::default()
                .ty(vk::DescriptorType::STORAGE_BUFFER)
                .descriptor_count(4 * n_frames);
            let pool = device
                .create_descriptor_pool(
                    &vk::DescriptorPoolCreateInfo::default()
                        .pool_sizes(std::slice::from_ref(&pool_size))
                        .max_sets(n_frames),
                )
                .map_err(|e| format!("two-pass cull descriptor pool: {e}"))?;
            let set_layouts2: Vec<_> = (0..frames).map(|_| set_layout.handle()).collect();
            let sets2 = alloc_descriptor_sets(&device, pool.handle(), &set_layouts2)?;
            for (i, &set) in sets2.iter().enumerate() {
                let obj_info = vk::DescriptorBufferInfo::default()
                    .buffer(object_buffers[i].buffer())
                    .offset(0)
                    .range(object_buffer_size);
                let arg_info = vk::DescriptorBufferInfo::default()
                    .buffer(draw_args_buffers[i].buffer())
                    .offset(0)
                    .range(draw_args_size);
                // Binding 2: the *second* indirect buffer (Cull2 writes it).
                let cmd_info = vk::DescriptorBufferInfo::default()
                    .buffer(ind2_buffers[i].buffer())
                    .offset(0)
                    .range(indirect_size);
                // Binding 3: the cull-status buffer (phase 1 wrote it; read here).
                let status_info = vk::DescriptorBufferInfo::default()
                    .buffer(cull_status_buffers[i].buffer())
                    .offset(0)
                    .range(status_size);
                let infos = [obj_info, arg_info, cmd_info, status_info];
                let writes: Vec<_> = infos
                    .iter()
                    .enumerate()
                    .map(|(b, info)| {
                        vk::WriteDescriptorSet::default()
                            .dst_set(set)
                            .dst_binding(b as u32)
                            .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                            .buffer_info(std::slice::from_ref(info))
                    })
                    .collect();
                // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
                // every set and resource it names belongs to this device.
                unsafe { device.update_descriptor_sets(&writes, &[]) };
            }

            // Phase-1 (STORE MSAA colour) + phase-2 (LOAD colour + depth) main
            // render passes, both compatible with the existing framebuffers.
            let rp1 = create_main_render_pass_two_pass(&device, HDR_FORMAT, msaa_samples, false)?;
            let rp2 = create_main_render_pass_two_pass(&device, HDR_FORMAT, msaa_samples, true)?;

            (
                Some(pipeline2),
                sets2,
                Some(pool),
                ind2_buffers,
                Some(rp1),
                Some(rp2),
            )
        } else {
            (None, Vec::new(), None, Vec::new(), None, None)
        };

        // Per-cluster (albedo, normal) sets share the per-object layout.
        let cluster_object_sets: Vec<vk::DescriptorSet> = if instanced_clusters.is_empty() {
            Vec::new()
        } else {
            let cluster_layouts: Vec<_> = instanced_clusters
                .iter()
                .map(|_| object_set_layout.handle())
                .collect();
            let sets = alloc_descriptor_sets(&device, descriptor_pool.handle(), &cluster_layouts)?;
            let last_tex = gpu_textures.len().saturating_sub(1);
            let normal_view = |nms: usize| {
                if nms == NO_NORMAL_MAP_SLOT {
                    gpu_fallbacks[0].view
                } else {
                    gpu_textures[nms.min(last_tex)].view
                }
            };
            let albedo_view = |ts: usize| {
                if ts == NO_ALBEDO_SLOT {
                    gpu_fallbacks[1].view
                } else {
                    gpu_textures[ts.min(last_tex)].view
                }
            };
            for (cluster, &set) in instanced_clusters.iter().zip(sets.iter()) {
                let albedo_info = vk::DescriptorImageInfo::default()
                    .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                    .image_view(albedo_view(cluster.texture_slot))
                    .sampler(linear_sampler.handle());
                let nm_info = vk::DescriptorImageInfo::default()
                    .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                    .image_view(normal_view(cluster.normal_map_slot))
                    .sampler(linear_sampler.handle());
                let writes = [
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(0)
                        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                        .image_info(std::slice::from_ref(&albedo_info)),
                    vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(1)
                        .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                        .image_info(std::slice::from_ref(&nm_info)),
                ];
                // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
                // every set and resource it names belongs to this device.
                unsafe { device.update_descriptor_sets(&writes, &[]) };
            }
            sets
        };

        // Per-frame, per-cluster instance storage buffers (host-mapped).
        let mut instance_buffers: Vec<Vec<super::allocator::PooledBuffer>> =
            Vec::with_capacity(frames);
        let mut instance_sets: Vec<Vec<vk::DescriptorSet>> = Vec::with_capacity(frames);
        if !instanced_clusters.is_empty() {
            let instance_set_layout = instance_set_layout_opt
                .as_ref()
                .expect("instance set layout was created because instanced draws are needed");
            for _ in 0..frames {
                let mut bufs: Vec<super::allocator::PooledBuffer> =
                    Vec::with_capacity(instanced_clusters.len());
                for cluster in &instanced_clusters {
                    let size_bytes = (cluster.instances.len().max(1)
                        * std::mem::size_of::<[[f32; 4]; 4]>())
                        as vk::DeviceSize;
                    let buf = alloc.create_buffer(
                        size_bytes,
                        vk::BufferUsageFlags::STORAGE_BUFFER,
                        vk::MemoryPropertyFlags::HOST_VISIBLE
                            | vk::MemoryPropertyFlags::HOST_COHERENT,
                    )?;
                    bufs.push(buf);
                }
                // Allocate one descriptor set per cluster for this frame.
                let layouts: Vec<_> = instanced_clusters
                    .iter()
                    .map(|_| instance_set_layout.handle())
                    .collect();
                let sets = alloc_descriptor_sets(&device, descriptor_pool.handle(), &layouts)?;
                // Wire each set to its buffer.
                for (i, &set) in sets.iter().enumerate() {
                    let info = vk::DescriptorBufferInfo::default()
                        .buffer(bufs[i].buffer())
                        .offset(0)
                        .range(vk::WHOLE_SIZE);
                    let write = vk::WriteDescriptorSet::default()
                        .dst_set(set)
                        .dst_binding(0)
                        .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
                        .buffer_info(std::slice::from_ref(&info));
                    // SAFETY: `writes` and the buffer/image infos it borrows are live for the call,
                    // and every set and resource it names belongs to this device.
                    unsafe { device.update_descriptor_sets(std::slice::from_ref(&write), &[]) };
                }
                instance_buffers.push(bufs);
                instance_sets.push(sets);
            }
        }

        // Text atlas sets.
        let text_atlas_layouts: Vec<_> = gpu_text_atlases
            .iter()
            .map(|_| text_set_layout.handle())
            .collect();
        let text_atlas_sets = if text_atlas_layouts.is_empty() {
            vec![]
        } else {
            let sets =
                alloc_descriptor_sets(&device, descriptor_pool.handle(), &text_atlas_layouts)?;
            for (&set, atlas) in sets.iter().zip(gpu_text_atlases.iter()) {
                let img_info = vk::DescriptorImageInfo::default()
                    .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
                    .image_view(atlas.view)
                    .sampler(text_sampler.handle());
                let write = vk::WriteDescriptorSet::default()
                    .dst_set(set)
                    .dst_binding(0)
                    .descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
                    .image_info(std::slice::from_ref(&img_info));
                // SAFETY: `writes` and the buffer/image infos it borrows are live for the call, and
                // every set and resource it names belongs to this device.
                unsafe { device.update_descriptor_sets(std::slice::from_ref(&write), &[]) };
            }
            sets
        };

        // Composite sets (one per frame-in-flight slot): binding 0 = the
        // scene image (SSR output when SSR is on, else this slot's HDR
        // resolve), binding 1 = that slot's bloom mip 0, binding 2 = the
        // shared 3D colour LUT. TAA's branch below overrides binding 0 to
        // the TAA output when TAA is on.
        let composite_layouts: Vec<_> =
            (0..frames).map(|_| composite_set_layout.handle()).collect();
        let composite_sets =
            alloc_descriptor_sets(&device, descriptor_pool.handle(), &composite_layouts)?;
        for (i, &set) in composite_sets.iter().enumerate() {
            // Scene image: the reflection composite output (the SSR / RT reflection
            // blended over the scene) when a reflection path is active, else the raw
            // HDR resolve (a SSGI-only build composited its bounce into the latter
            // upstream). TAA / upscale override this below.
            let scene_view = composite_opt
                .as_ref()
                .map(|c| c.output.view)
                .unwrap_or(hdr_resolve_images[i].view);
            write_composite_set(
                &device,
                set,
                scene_view,
                bloom_mips[i][0].view,
                color_lut.view,
                composite_sampler.handle(),
            );
        }

        //  Bloom descriptor pool + input sets
        // A dedicated, resettable pool isolates bloom's variable set count
        // (the octave count can shift on resize) from the main pool. Sized for
        // the worst case (`MAX_BLOOM_MIPS + 1` sets per frame).
        let bloom_pool_capacity = n_frames * (MAX_BLOOM_MIPS + 1);
        let bloom_pool_size = vk::DescriptorPoolSize::default()
            .ty(vk::DescriptorType::COMBINED_IMAGE_SAMPLER)
            .descriptor_count(bloom_pool_capacity);
        let bloom_descriptor_pool = device
            .create_descriptor_pool(
                &vk::DescriptorPoolCreateInfo::default()
                    .pool_sizes(std::slice::from_ref(&bloom_pool_size))
                    .max_sets(bloom_pool_capacity),
            )
            .map_err(|e| format!("bloom descriptor pool: {e}"))?;
        let bloom_input_sets = alloc_bloom_input_sets(
            &device,
            bloom_descriptor_pool.handle(),
            bloom_set_layout.handle(),
            composite_sampler.handle(),
            &hdr_resolve_images,
            &bloom_mips,
        )?;
        // The reflection composite replaces the bloom prefilter's scene input
        // (input 0) with its output, the same scene image the composite pass
        // samples when a reflection path is active and TAA is off (a SSGI-only
        // build leaves the prefilter on the raw HDR resolve). One shared image, so
        // every frame's prefilter input 0 points at it.
        if let Some(view) = composite_opt.as_ref().map(|c| c.output.view) {
            for frame_sets in &bloom_input_sets {
                rebind_bloom_input0(&device, frame_sets[0], view, composite_sampler.handle());
            }
        }

        //  Temporal anti-aliasing
        // When TAA is on the history resolve produces a post-TAA scene image;
        // the bloom prefilter and composite pass must sample that instead of the
        // raw HDR resolve, so their binding-0 descriptor is re-pointed at the
        // per-frame TAA output image.
        let taa = if taa_enabled {
            let taa = TaaResources::new(
                &TaaDeviceContext {
                    alloc: &alloc,
                    device: &device,
                    command_pool,
                    queue: graphics_queue,
                },
                frames,
                render_extent,
                &TaaSceneInputs {
                    hdr_resolve_images: &hdr_resolve_images,
                    sampler: composite_sampler.handle(),
                },
                hot_reload,
            )?;
            // When a reflection path owns the scene image, TAA samples the
            // reflection composite output (the HDR scene with reflections composited
            // in) instead of the raw HDR resolve. A SSGI-only build leaves TAA on the
            // raw HDR resolve.
            if let Some(view) = composite_opt.as_ref().map(|c| c.output.view) {
                taa.rewire_scene(&device, view, composite_sampler.handle());
            }
            for (i, &set) in composite_sets.iter().enumerate() {
                write_composite_set(
                    &device,
                    set,
                    taa.output_view(i),
                    bloom_mips[i][0].view,
                    color_lut.view,
                    composite_sampler.handle(),
                );
            }
            for (i, frame_sets) in bloom_input_sets.iter().enumerate() {
                rebind_bloom_input0(
                    &device,
                    frame_sets[0],
                    taa.output_view(i),
                    composite_sampler.handle(),
                );
            }
            Some(taa)
        } else {
            None
        };

        // Temporal upscaling overrides the scene input: when FSR is active the
        // bloom prefilter + composite sample its reconstructed swapchain-res
        // output (a single shared image), not the per-frame TAA output. TAA
        // resources are forced built under upscaling (for the velocity pre-pass)
        // and the TAA block above pointed the sets at the TAA output, so this
        // override is the final word; the TAA *resolve* is dropped from the
        // graph and never runs.
        if let Some(up) = &upscale {
            let up_output_view = up.output_image().view;
            for (i, &set) in composite_sets.iter().enumerate() {
                write_composite_set(
                    &device,
                    set,
                    up_output_view,
                    bloom_mips[i][0].view,
                    color_lut.view,
                    composite_sampler.handle(),
                );
            }
            for frame_sets in &bloom_input_sets {
                rebind_bloom_input0(
                    &device,
                    frame_sets[0],
                    up_output_view,
                    composite_sampler.handle(),
                );
            }
        }

        //  Unified G-buffer pre-pass reader re-wire
        // Re-point every reader's G-buffer / roughness / velocity descriptor at
        // the merged pre-pass's per-frame views now that the merged buffer + all
        // readers exist. RT was already wired to the unified views at its
        // construction; here we move the SSR resolve, SSGI, SSAO kernel/blur, and
        // the TAA resolve's velocity input. The merged pre-pass produces the
        // byte-identical normal+depth / roughness the separate pre-passes did, so
        // the resolve / kernel maths is unchanged. Mirrors DirectX re-pointing
        // every reader at `self.gbuffer` in init.
        if let Some(gb) = gbuffer_opt.as_ref() {
            let nd_views = gb.normal_depth_views();
            let rough_views = gb.roughness_views();
            let vel_views = gb.velocity_views();
            let hdr_views: Vec<vk::ImageView> =
                hdr_resolve_images.iter().map(|img| img.view).collect();
            if let Some(ssr) = ssr_opt.as_ref() {
                ssr.wire_resolve_sets(
                    &device,
                    &hdr_views,
                    &nd_views,
                    &rough_views,
                    env_map.prefilter.view,
                    cube_sampler.handle(),
                );
            }
            if let Some(ssgi) = ssgi_opt.as_ref() {
                ssgi.wire_sets_gbuffer(&device, &hdr_views, &nd_views);
            }
            if let Some(ssao) = ssao_opt.as_ref() {
                ssao.wire_kernel_and_blur_sets_gbuffer(&device, &nd_views);
            }
            if let Some(taa) = taa.as_ref() {
                taa.rewire_velocity(&device, &vel_views, composite_sampler.handle());
            }
        }

        // Composite G-buffer channel bindings (3/4/5), for the debug view
        // modes. Written after the re-wire above so they point at the merged
        // pre-pass's views; the 1x1 white fallback stands in when a world built
        // no G-buffer / no SSAO.
        for (i, &set) in composite_sets.iter().enumerate() {
            let (nd_view, rough_view) = match gbuffer_opt.as_ref() {
                Some(gb) => (gb.normal_depth_views()[i], gb.roughness_views()[i]),
                None => (ssao_white.view, ssao_white.view),
            };
            write_composite_channel_set(
                &device,
                set,
                nd_view,
                rough_view,
                transient_pool
                    .view_for("ao_output", i)
                    .unwrap_or(ssao_white.view),
                composite_sampler.handle(),
            );
        }

        //  Projected decals
        // Pipeline + per-frame uniforms + per-decal albedo sets are always
        // built so runtime `add_decal` works from a world that started
        // with none. The encoder simply skips when every slot is `None`
        // or every live decal culls.
        let depth_views: Vec<vk::ImageView> = depth_images.iter().map(|img| img.view).collect();
        let hdr_resolve_views: Vec<vk::ImageView> =
            hdr_resolve_images.iter().map(|img| img.view).collect();
        let decals_state = Some(crate::vulkan::decal::DecalResources::new(
            crate::vulkan::decal::DecalDeviceContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            },
            crate::vulkan::decal::DecalPassTargets {
                hdr_format: HDR_FORMAT,
                hdr_resolve_views: &hdr_resolve_views,
                depth_views: &depth_views,
                sampler: linear_sampler.handle(),
                extent: render_extent,
            },
            frames,
            msaa_samples != vk::SampleCountFlags::TYPE_1,
            hot_reload,
        )?);

        // Volumetric fog: pipeline + per-frame uniform ring. Built only
        // when the world declared a `VolumetricFog`; the encoder skips the
        // pass when `fog_settings` is `None`.
        let fog_resources = if fog_settings.is_some() {
            Some(crate::vulkan::fog::FogResources::new(
                crate::vulkan::fog::FogDeviceContext {
                    alloc: &alloc,
                    device: &device,
                    command_pool,
                    queue: graphics_queue,
                },
                crate::vulkan::fog::FogFrameTargets {
                    frames,
                    msaa: msaa_samples != vk::SampleCountFlags::TYPE_1,
                    hdr_format: HDR_FORMAT,
                    hdr_resolve_views: &hdr_resolve_views,
                    depth_views: &depth_views,
                    sampler: linear_sampler.handle(),
                    extent: render_extent,
                },
                crate::vulkan::fog::FogShadowResources {
                    ubos: &shadow_ubos,
                    map_view: shadow_map.view,
                    sampler: shadow_sampler.handle(),
                },
                hot_reload,
            )?)
        } else {
            None
        };

        // Raymarched SDF volumes: per-volume pipelines + the shared view ring,
        // descriptor pool, render passes, and scene snapshot. `None` when no
        // `.glsl` `SdfVolume` survived the backend filter, so the Raymarch pass
        // is omitted from the frame graph.
        let raymarch = crate::vulkan::raymarch::RaymarchResources::try_new(
            crate::vulkan::raymarch::RaymarchDeviceContext {
                alloc: &alloc,
                device: &device,
                command_pool,
                queue: graphics_queue,
            },
            crate::vulkan::raymarch::RaymarchTargetConfig {
                frames,
                msaa_samples,
                width: render_extent.width,
                height: render_extent.height,
            },
            crate::vulkan::raymarch::RaymarchSharedBindings {
                shadow_map_view: shadow_map.view,
                shadow_sampler: shadow_sampler.handle(),
                irradiance_view: env_map.irradiance.view,
                prefilter_view: env_map.prefilter.view,
                cube_sampler: cube_sampler.handle(),
                linear_sampler: linear_sampler.handle(),
                light_ubo: light_ubo.buffer(),
                shadow_ubos: &shadow_ubos,
                shadow_render_pass: shadow_render_pass.handle(),
            },
            &sdf_volumes,
            hot_reload,
        )?;

        // Planar reflections: group each transparent reflector's world-space plane
        // into a bounded set of distinct planes (near-coplanar reflectors share one
        // mirror render; reflectors past the budget fall back to the probe cube),
        // then build one render-resolution mirror target per distinct plane. Built
        // before the transparent pass so each record's planar binding can point at
        // its plane's target. `slots[i]` is reflector `i`'s target slot (or `None`).
        //
        // Water first, then glass, matching the Metal backend, so the two slot
        // ranges are the leading `water_surfaces.len()` entries and the rest.
        let planar_reflectors: Vec<[f32; 4]> = water_surfaces
            .iter()
            // A water surface's rest plane: horizontal at the surface base height.
            .map(|s| [0.0, 1.0, 0.0, -s.centre[1]])
            .chain(
                glass_panels
                    .iter()
                    .map(|p| crate::vulkan::planar::pane_plane(p.normal, p.centre)),
            )
            .collect();
        // Cap at the capacity ceiling the reserved planar targets are sized to, so a
        // stale/over-large preset value can never over-allocate.
        let planar_budget = planar_planes.min(crate::vulkan::planar::MAX_PLANAR_PLANES);
        let planar_assignment =
            crate::gfx::planar_reflection::assign_planar_slots(&planar_reflectors, planar_budget);
        // The reflected-frustum mirror cull is bindless-only (it needs the GPU cull
        // set layout + the per-frame object/draw-args SSBOs); a non-bindless world
        // has no `cull_set_layout`, so planar is skipped and its panes keep the
        // probe / sky reflection. Mirrors `metal::planar`'s bindless gate.
        let planar_reflection = if planar_assignment.representatives.is_empty() {
            None
        } else if let Some(csl) = cull_set_layout.as_ref() {
            let cull_sources = crate::vulkan::planar::PlanarCullSources {
                frame_object_buffers: &object_buffers,
                frame_draw_args_buffers: &draw_args_buffers,
                cull_set_layout: csl.handle(),
                cull_count: n_cull,
                hiz: hiz.as_ref().map(|h| {
                    let (view, sampler) = h.read_set_sources();
                    (h.read_set_layout.handle(), view, sampler)
                }),
            };
            Some(crate::vulkan::planar::PlanarReflectionSet::new(
                crate::vulkan::planar::PlanarDevice {
                    alloc: &alloc,
                    device: &device,
                },
                crate::vulkan::planar::PlanarConfig {
                    frames,
                    sample_count: msaa_samples,
                    width: render_extent.width,
                    height: render_extent.height,
                },
                &planar_assignment.representatives,
                &main_render_pass,
                crate::vulkan::planar::PlanarGlobalSet {
                    update_after_bind: global_update_after_bind,
                    layout: global_set_layout.handle(),
                    probe_cube_count,
                },
                crate::vulkan::planar::PlanarLightingBindings {
                    light_ubo: light_ubo.buffer(),
                    light_size: light_ubo_size,
                    local_light_buffer: local_light_buffer.buffer(),
                    local_light_size: local_light_buffer_size,
                    cluster_params_ubo: light_cull.unclustered_buffer.buffer(),
                    cluster_list_buffer: light_cull.cluster_buffer.buffer(),
                    spot_shadow_map_view: spot_shadow.map.view,
                    spot_shadow_data_buffer: spot_shadow.data_buffer.buffer(),
                    area_light_buffer: area_light_buffer.buffer(),
                    ltc_matrix_view: ltc_matrix_image.view,
                    ltc_magnitude_view: ltc_magnitude_image.view,
                    ltc_sampler: ltc_sampler.handle(),
                    shadow_ubos: &shadow_ubos,
                    shadow_size: shadow_ubo_size,
                    shadow_map_view: shadow_map.view,
                    shadow_sampler: shadow_sampler.handle(),
                    irradiance_view: env_map.irradiance.view,
                    prefilter_view: env_map.prefilter.view,
                    cube_sampler: cube_sampler.handle(),
                    ssao_white_view: ssao_white.view,
                    linear_sampler: linear_sampler.handle(),
                },
                cull_sources,
            )?)
        } else {
            None
        };
        let planar_target_views: Vec<vk::ImageView> = planar_reflection
            .as_ref()
            .map(|s| (0..s.plane_count()).map(|i| s.target_view(i)).collect())
            .unwrap_or_default();

        // The shared transparent pass and its producers: water surfaces,
        // translucent glass panes, and see-through glass meshes. `Some` only when
        // the world declared at least one of the three; the mesh case additionally
        // needs an RT-capable device, since its producer is ray-traced only and a
        // pane-less, water-less world would otherwise build the whole pass for a
        // producer that cannot exist. The pass blends into the post-reflection
        // scene image (the reflection composite output when a reflection path is
        // active, else this slot's HDR resolve), so the scene target per frame slot
        // is resolved here; the main-depth views feed the fragments' manual
        // occlusion test.
        let transparent =
            if glass_panels.is_empty() && water_surfaces.is_empty() && !has_seethrough_meshes {
                None
            } else {
                let (scene_views, scene_images): (Vec<vk::ImageView>, Vec<vk::Image>) = (0..frames)
                    .map(|i| {
                        if let Some(c) = composite_opt.as_ref() {
                            (c.output.view, c.output.image)
                        } else {
                            (hdr_resolve_images[i].view, hdr_resolve_images[i].image)
                        }
                    })
                    .unzip();
                let transparent_depth_views: Vec<vk::ImageView> =
                    depth_images.iter().map(|img| img.view).collect();
                // The initial acceleration-structure handles for the RT path (`None`
                // when RT is off at launch; the per-frame `rt_dynamic_update` fills the
                // ring before the RT path is taken). The RT pipelines themselves are
                // built whenever the device is RT-capable.
                let rt_inputs = rt_accel_opt.as_ref().map(|a| {
                    let (geom_buffer, geom_size) = a.geom_table();
                    crate::vulkan::transparent::TransparentRtInputs {
                        tlas: a.tlas(),
                        geom_buffer,
                        geom_size,
                        deformed_verts: a.deformed_verts(),
                        skinned_indices: a.skinned_indices(),
                    }
                });
                let (water_planar_slots, glass_planar_slots) =
                    planar_assignment.slots.split_at(water_surfaces.len());
                Some(crate::vulkan::transparent::TransparentResources::new(
                    crate::vulkan::transparent::TransparentDeviceCtx {
                        alloc: &alloc,
                        instance: &instance,
                        device: &device,
                        physical_device,
                        command_pool,
                        queue: graphics_queue,
                    },
                    crate::vulkan::transparent::TransparentBuildConfig {
                        frames,
                        msaa_samples,
                        width: render_extent.width,
                        height: render_extent.height,
                        global_set_layout: global_set_layout.handle(),
                        probe_cube_count,
                        hot_reload,
                    },
                    crate::vulkan::transparent::TransparentSceneTargets {
                        scene_views: &scene_views,
                        scene_images: &scene_images,
                        depth_views: &transparent_depth_views,
                        sampler: linear_sampler.handle(),
                    },
                    crate::vulkan::transparent::TransparentContent {
                        glass_panels: &glass_panels,
                        glass_planar_slots,
                        water_surfaces: &water_surfaces,
                        water_planar_slots,
                        planar_target_views: &planar_target_views,
                        seethrough_mesh_indices: &seethrough_mesh_indices,
                    },
                    crate::vulkan::transparent::TransparentRtSetup {
                        rt_capable,
                        vertex_buffer: vertex_buffer.buffer(),
                        index_buffer: index_buffer.buffer(),
                        rt_inputs,
                        bindless_set_layout: bindless_set_layout.as_ref().map(|l| l.handle()),
                        bindless_pool_size,
                    },
                )?)
            };

        // Auto-exposure (EV adaptation): histogram + average compute
        // pipelines, the device-local histogram + output buffers, and the
        // per-frame readback ring. Built only when the world's
        // `PostProcessConfig` opted in. With auto-exposure off every
        // field below is None and the static authored EV continues to
        // drive `post_process.exposure` unchanged.
        let (auto_exposure, auto_exposure_state) =
            if let Some(settings) = auto_exposure_settings.as_ref() {
                let resources = crate::vulkan::auto_exposure::AutoExposureResources::new(
                    &alloc,
                    &device,
                    frames,
                    &hdr_resolve_views,
                    linear_sampler.handle(),
                    hot_reload,
                )?;
                let state = crate::gfx::auto_exposure::AutoExposureState::new(settings);
                (Some(resources), Some(state))
            } else {
                (None, None)
            };

        //  Command buffers
        let alloc_info = vk::CommandBufferAllocateInfo::default()
            .command_pool(command_pool)
            .level(vk::CommandBufferLevel::PRIMARY)
            .command_buffer_count(frames as u32);
        // SAFETY: the create-info and every slice it borrows are live for the call, and each handle
        // it names belongs to this device.
        let command_buffers = unsafe { device.allocate_command_buffers(&alloc_info) }
            .map_err(|e| format!("allocate command buffers: {e}"))?;

        //  Parallel command-buffer recording: a `start` outer buffer per frame
        //  (leading timestamp) plus one command pool + primary buffer per
        //  (frame, pass) slot. Vulkan command pools are externally
        //  synchronized, so every slot gets its own pool - the rayon workers in
        //  `execute_graph` never share a pool. `RESET_COMMAND_BUFFER` so each
        //  buffer can be reset + re-recorded per frame (the per-frame
        //  `in_flight` fence gates reuse). Indexed `frame * PASS_COUNT + pass`.
        let pass_pool_flags = vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER
            | vk::CommandPoolCreateFlags::TRANSIENT;
        let make_pool_with_buffer =
            |device: &VkDevice| -> Result<(vk::CommandPool, vk::CommandBuffer), String> {
                // SAFETY: the create-info and every slice it borrows are live for the call, and
                // each handle it names belongs to this device.
                let pool = unsafe {
                    device.create_command_pool(
                        &vk::CommandPoolCreateInfo::default()
                            .flags(pass_pool_flags)
                            .queue_family_index(graphics_family),
                        None,
                    )
                }
                .map_err(|e| format!("per-pass command pool: {e}"))?;
                // SAFETY: the create-info and every slice it borrows are live for the call, and
                // each handle it names belongs to this device.
                let buf = unsafe {
                    device.allocate_command_buffers(
                        &vk::CommandBufferAllocateInfo::default()
                            .command_pool(pool)
                            .level(vk::CommandBufferLevel::PRIMARY)
                            .command_buffer_count(1),
                    )
                }
                .map_err(|e| format!("per-pass command buffer: {e}"))?[0];
                Ok((pool, buf))
            };
        let mut start_command_pools = Vec::with_capacity(frames);
        let mut start_command_buffers = Vec::with_capacity(frames);
        for _ in 0..frames {
            let (pool, buf) = make_pool_with_buffer(&device)?;
            start_command_pools.push(pool);
            start_command_buffers.push(buf);
        }
        let pass_pool_count = frames * crate::gfx::render_graph::PASS_COUNT;
        let mut pass_command_pools = Vec::with_capacity(pass_pool_count);
        let mut pass_command_buffers = Vec::with_capacity(pass_pool_count);
        for _ in 0..pass_pool_count {
            let (pool, buf) = make_pool_with_buffer(&device)?;
            pass_command_pools.push(pool);
            pass_command_buffers.push(buf);
        }

        //  Sync objects
        // `image_available` + `in_flight` are per-frame-in-flight. The
        // render-finished semaphore is signalled by submit and waited on by
        // present, so it must be one-per-swapchain-image (indexed by the
        // acquired image index): a per-frame semaphore can still be queued
        // for presentation when its frame slot comes round again.
        let sem_info = vk::SemaphoreCreateInfo::default();
        let fence_info = vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED);
        let mut image_available = Vec::with_capacity(frames);
        let mut in_flight = Vec::with_capacity(frames);
        let mut render_finished = Vec::with_capacity(swapchain_images.len());
        for _ in 0..swapchain_images.len() {
            render_finished.push(
                // SAFETY: the create-info and every slice it borrows are live for the call, and
                // each handle it names belongs to this device.
                unsafe { device.create_semaphore(&sem_info, None) }
                    .map_err(|e| format!("semaphore: {e}"))?,
            );
        }
        for _ in 0..frames {
            image_available.push(
                // SAFETY: the create-info and every slice it borrows are live for the call, and
                // each handle it names belongs to this device.
                unsafe { device.create_semaphore(&sem_info, None) }
                    .map_err(|e| format!("semaphore: {e}"))?,
            );
            in_flight.push(
                // SAFETY: the create-info and every slice it borrows are live for the call, and
                // each handle it names belongs to this device.
                unsafe { device.create_fence(&fence_info, None) }
                    .map_err(|e| format!("fence: {e}"))?,
            );
        }

        let (cull_bvh, always_draw) = crate::gfx::bvh::partition_draw_objects(&draw_objects);

        // Membership flags parallel to `draw_objects` so a recycled draw slot is
        // added to `always_draw` at most once. The free-list allocator starts
        // with every build-time slot already in use; runtime spawns and streamed
        // chunks pop a vacated slot before appending past this count.
        let always_draw_member = {
            let mut member = vec![false; draw_objects.len()];
            for &i in &always_draw {
                member[i as usize] = true;
            }
            member
        };

        let shadow_pipeline_layout_field = if shadow_pipeline_opt.is_some() {
            Some(shadow_pipeline_layout)
        } else {
            // SAFETY: every handle here was created from this device and is destroyed exactly once;
            // the caller has already waited for the device to go idle, so no submission still
            // references them.
            None
        };

        // Shader hot-reload: spawn a filesystem watcher over
        // `vulkan/shaders/` only under `cn debug`. The shared atomic flag
        // is also handed to the debug WebSocket server elsewhere so the
        // `reload-shaders` command converges on the same trigger path.
        let (shader_reload_pending, shader_watcher) = if hot_reload {
            let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let watcher = crate::vulkan::hot_reload::spawn(std::sync::Arc::clone(&flag));
            (Some(flag), watcher)
        } else {
            (None, None)
        };

        let mut me = Self {
            instance,
            device,
            physical_device,
            alloc,
            surface,
            surface_loader,
            graphics_queue,
            present_queue,
            graphics_family,
            swapchain: super::context::SwapchainState {
                loader: swapchain_loader,
                handle: swapchain,
                images: swapchain_images,
                image_views: swapchain_image_views,
                format: swapchain_format,
                extent: swapchain_extent,
                last_present_index: None,
            },
            render_extent,
            main_render_pass,
            msaa_samples,
            color_images,
            depth_images,
            hdr_resolve_images,
            framebuffers,
            shadow: VkShadow {
                render_pass: shadow_render_pass,
                map: shadow_map,
                map_size: effective_shadow_size,
                framebuffers: shadow_framebuffers_vec,
                pipeline: shadow_pipeline_opt,
                pipeline_layout: shadow_pipeline_layout_field,
                global_set_layout: Some(shadow_global_set_layout),
                global_sets: shadow_global_sets,
                sampler: shadow_sampler,
                skinned_pipeline: None,
                skinned_pipeline_layout: None,
                ubos: shadow_ubos,
                uniforms: shadow_uniforms,
                light_dir: shadow_light_dir,
                update: shadow_update,
                distance: shadow_distance,
                cascades: shadow_cascades,
                scheduler: Default::default(),
                render_mask: 0,
            },
            spot_shadow,
            area_light: super::context::VkAreaLight {
                buffer: area_light_buffer,
                ltc_matrix: ltc_matrix_image,
                ltc_magnitude: ltc_magnitude_image,
                sampler: ltc_sampler,
            },
            textures: gpu_textures,
            fallback_textures: gpu_fallbacks,
            linear_sampler,
            main_pipeline,
            main_pipeline_layout,
            light_cull,
            cull: VkCull {
                bindless_pipeline,
                bindless_pipeline_layout,
                bindless_set_layout,
                bindless_pool_size,
                bindless_update_after_bind: bindless_uab,
                world_pipelines,
                bucket_stride: n_cull,
                bindless_main_spv,
                bindless_sets,
                object_buffers,
                cull_pipeline,
                cull_pipeline_layout,
                cull_set_layout,
                cull_sets,
                draw_args_buffers,
                indirect_buffers,
                cull_status_buffers,
                occlusion_two_pass,
                cull_pipeline_phase2,
                cull_sets2,
                _two_pass_pool: two_pass_pool,
                indirect_buffers2,
                main_render_pass_phase1,
                main_render_pass_phase2,
                hiz,
                hiz_valid: false,
                hiz_prev_view_proj: IDENTITY,
                shadow_cull_pipeline,
                shadow_cull_pipeline_layout,
                _shadow_cull_set_layout: shadow_cull_set_layout,
                shadow_cull_sets,
                shadow_bindless_pipeline,
                shadow_bindless_pipeline_layout,
                shadow_indirect_buffers,
                gbuffer_bindless_pipeline,
                gbuffer_bindless_pipeline_layout,
                _gbuffer_set_layout: gbuffer_set_layout,
                gbuffer_sets,
                prev_model_buffers,
            },
            text: super::context::TextState {
                atlas_textures: gpu_text_atlases,
                pipeline: text_pipeline_opt,
                pipeline_layout: text_pipeline_layout,
                _sampler: text_sampler,
                upload: crate::vulkan::upload_ring::UploadRing::new(frames),
            },
            instanced: VkInstanced {
                pipeline: instanced_pipeline_opt,
                pipeline_layout: instanced_pipeline_layout_opt,
                set_layout: instance_set_layout_opt,
                object_sets: cluster_object_sets,
                sets: instance_sets,
                buffers: instance_buffers,
                lod_buckets: vec![Vec::new(); instanced_clusters.len()],
                clusters: instanced_clusters,
            },
            composite: super::context::CompositeState {
                render_pass: composite_render_pass,
                framebuffers: composite_framebuffers,
                pipeline: composite_pipeline,
                pipeline_layout: composite_pipeline_layout,
                _set_layout: composite_set_layout,
                sets: composite_sets,
                sampler: composite_sampler,
            },
            color_lut,
            bloom: super::context::BloomState {
                write_pass: bloom_write_pass,
                blend_pass: bloom_blend_pass,
                pipeline_prefilter: bloom_pipeline_prefilter,
                pipeline_downsample: bloom_pipeline_downsample,
                pipeline_upsample: bloom_pipeline_upsample,
                pipeline_layout: bloom_pipeline_layout,
                set_layout: bloom_set_layout,
                descriptor_pool: bloom_descriptor_pool,
                mips: bloom_mips,
                mip_extents: bloom_mip_extents,
                write_framebuffers: bloom_write_framebuffers,
                blend_framebuffers: bloom_blend_framebuffers,
                input_sets: bloom_input_sets,
            },
            post_process,
            taa,
            upscale,
            upscale_requested: upscale_backend,
            ssao: ssao_opt,
            ssao_white,
            transient_pool,
            ssr: ssr_opt,
            ssr_resolve_active: ssr_resolve_on,
            reflection_composite: composite_opt,
            ssgi: ssgi_opt,
            gbuffer: gbuffer_opt,
            rt_reflections: rt_opt,
            rt_accel: rt_accel_opt,
            rt_dynamic_mode,
            rt_skinned_geometry,
            rt_topology_dirty: false,
            rt_capable,
            update_after_bind,
            rt_static_vertex_count: vertices.len(),
            decal: super::context::DecalState {
                resources: decals_state,
                records: Vec::new(),
                free_slots: Vec::new(),
            },
            lines: crate::vulkan::line::LineState::empty(),
            hdr_mode,
            vsync,
            particle: super::context::ParticleState {
                resources: None,
                records: Vec::new(),
                emitter_state: Vec::new(),
                free_slots: Vec::new(),
                last_elapsed: std::cell::Cell::new(0.0),
                frame_index: std::cell::Cell::new(0),
            },
            fog: super::context::FogState {
                resources: fog_resources,
                settings: fog_settings,
                sun_dir: fog_sun_dir,
                sun_color: fog_sun_color,
            },
            raymarch,
            transparent,
            planar_reflection,
            auto_exposure: super::context::AutoExposureState {
                resources: auto_exposure,
                settings: auto_exposure_settings,
                state: auto_exposure_state,
                bias_ev: auto_exposure_bias_ev,
                last_elapsed: 0.0,
            },
            hot_reload: super::context::HotReloadState {
                enabled: hot_reload,
                reload_pending: shader_reload_pending,
                watcher: shader_watcher,
            },
            frame_stats: std::cell::Cell::new(crate::gfx::profile::RenderStats::default()),
            draw_calls_accum: std::sync::atomic::AtomicU32::new(0),
            timestamp_query_pool,
            timestamp_period_ns: timestamp_period,
            device_local_heaps,
            memory_budget_supported,
            descriptors: VkDescriptors {
                global_set_layout,
                global_update_after_bind,
                probe_cube_count,
                object_set_layout,
                _text_set_layout: text_set_layout,
                _descriptor_pool: descriptor_pool,
                global_sets,
                object_sets,
                text_atlas_sets,
            },
            geometry: VkGeometry {
                vertex_buffer,
                index_buffer,
                mesh_vtx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                mesh_idx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                vertex_buffer_bytes,
                index_buffer_bytes,
            },
            chunk_stream: VkChunkStream {
                vtx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                idx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                descriptor_pool: None,
                object_set: None,
                texture_slot: None,
                normal_map_slot: None,
            },
            clone: super::context::CloneState {
                descriptor_pool: None,
                object_sets: Vec::new(),
                free_offsets: Vec::new(),
                slot_by_draw_idx: std::collections::HashMap::new(),
                texture_slots: Vec::new(),
                normal_map_slots: Vec::new(),
            },
            skinned: VkSkinned {
                pipeline: None,
                pipeline_layout: None,
                joint_set_layout: None,
                descriptor_pool: None,
                vertex_buffer: super::allocator::PooledBuffer::null(),
                vertex_buffer_bytes: 0,
                index_buffer: super::allocator::PooledBuffer::null(),
                index_buffer_bytes: 0,
                draw_objects: Vec::new(),
                object_sets: Vec::new(),
                joint_buffers: Vec::new(),
                joint_sets: Vec::new(),
                joint_matrices: Vec::new(),
                skin: None,
                deformed: Vec::new(),
                morph_delta_unique: Vec::new(),
                morph_delta_buffers: Vec::new(),
                morph_target_counts: Vec::new(),
                morph_weights: Vec::new(),
                morph_weight_buffers: Vec::new(),
                deformed_primed: std::sync::atomic::AtomicBool::new(false),
            },
            uniforms: VkUniforms {
                view_ubo_buffers,
                probe_set_ubo_buffers,
                light_ubo,
                local_light_buffer,
                local_light_size: local_light_buffer_size,
                light_uniforms,
            },
            frame_sync: VkFrameSync {
                image_available,
                render_finished,
                in_flight,
            },
            current_frame: 0,
            frames_in_flight: frames,
            commands: VkCommands {
                command_pool,
                command_buffers,
                start_command_pools,
                start_command_buffers,
                pass_command_pools,
                pass_command_buffers,
            },
            draw: super::context::DrawState {
                n_objects: draw_objects.len(),
                objects: draw_objects,
                bvh: cull_bvh,
                always: always_draw,
                always_member: always_draw_member,
                visible_scratch: Vec::new(),
                graph_cache: None,
                n_instances,
                // Streamed-chunk record reserve (fixed at init = the worst-case
                // resident chunk window). The cull buffers reserve `[n_objects +
                // n_instances, +n_chunk)`; resident chunks fold in per frame, the
                // unused tail is disabled. 0 for a non-voxel world.
                n_chunk: n_chunk_max,
                // Set in `upload_skinned` once the skin fold is built; the cull
                // buffers reserve the tail at init via the threaded `n_skinned`
                // capacity, but `cull_count()` reads this runtime count.
                n_skinned: 0,
            },
            view: super::context::ViewState {
                clear_color,
                scene_fade: 0.0,
                mode: Default::default(),
                show: Default::default(),
                far: 1.0,
                matrix: IDENTITY,
            },
            wireframe: Default::default(),
            prefilter_mip_count: env_map.prefilter_mip_count,
            cube_sampler,
            env_map,
            probe: super::context::ProbeState {
                placements: Vec::new(),
                set: concinnity_core::render::uniforms::ProbeSet::EMPTY,
                maps: Vec::new(),
                bake_queue: crate::gfx::reflection_probe::ProbeBakeQueue::new(0),
                rendering: None,
                prefiltering: None,
                prefilter: probe_prefilter,
            },
            stream: super::context::StreamState {
                pool_rewrites: crate::gfx::slot_rewrites::SlotRewriteQueue::new(frames),
                frame: 0,
                retires: Vec::new(),
            },
            window: Some(window),
            _entry: entry,
            // The swap-decision key for a future live reload of this context
            // (see `hot_swap_config` / `reload_world`). Normalised `frames` (>=1)
            // matches how `BackendInit::swapchain_config` clamps it.
            swapchain_config: crate::gfx::backend_init::SwapchainConfig {
                frames_in_flight: frames,
                hdr_display,
                hdr_pq,
            },
            // A freshly built context owns its hardware outright; only
            // `apply_world_reload` flips this on the outgoing context.
            reused_by_successor: false,
            world_content_destroyed: false,
        };
        // Push every world-authored `DecalRecord` through `add_decal` so
        // its albedo descriptor lands in the reserved slot before the
        // first frame runs.
        me.upload_initial_decals(decals)?;
        // Same pattern for particle emitters: each world-authored record
        // routes through `add_particle_emitter` so its pool, counter, and
        // descriptor sets land before the first frame.
        me.upload_initial_particles(particles)?;
        // Every init upload above was synchronous (its one-shot idled the
        // queue), so init's remaining staging debris is retirable now; reclaim
        // it so the stats below report the steady footprint, not init's peak.
        me.alloc.reclaim_idle();
        tracing::info!(
            "device allocator: {} ({} allocations allowed)",
            me.alloc.stats(),
            me.alloc.max_allocations(),
        );
        crate::shader_cache::report_init();
        // Serialize the pipeline cache now that every init-built pipeline has
        // populated it, then write the segment holding it and every shader
        // artifact this init compiled; a crash mid-session then still leaves
        // the next launch warm.
        super::pipeline_cache::serialize(&me.device);
        crate::pipeline_cache::report_init(super::pipeline_cache::disk_state());
        crate::runtime_cache::checkpoint();
        Ok(me)
    }

    // Rebuild this backend's world content in place on its existing hardware for
    // a live editor edit: wait for the GPU to idle, hand the shared instance /
    // device / surface / swapchain / window (+ debug messenger + timestamp pool)
    // to a successor context built from `init`, then replace `self` with it. The
    // outgoing `self` is dropped by the `*self = rebuilt` assignment;
    // `reused_by_successor` (set just before it) makes that Drop free only this
    // world's content and leave the shared hardware to the successor. Only ever
    // called when `hot_swap_config` reported a config matching
    // `init.swapchain_config()`, so the swapchain (format / frames-in-flight /
    // EDR) is guaranteed unchanged. Mirrors `DxContext::apply_world_reload`.
    //
    // The old world's content is freed BEFORE the successor builds, into the
    // allocator the two contexts share, so the rebuild fills the released
    // blocks instead of holding both worlds' memory for the reload's duration.
    //
    // On a content-build failure (essentially impossible for a pre-validated
    // editor edit built from the engine's built-in shaders) the moved window is
    // closed with the dropped reuse bundle and the old world is already gone;
    // `self` keeps the shared hardware (the flag is unset on the failure path)
    // and tears it down in a normal Drop, so the caller can drop this backend
    // and mark the session failed without a leak.
    pub(in crate::vulkan) fn apply_world_reload(
        &mut self,
        init: crate::gfx::backend_init::BackendInit<'_>,
    ) -> Result<(), String> {
        self.wait_idle();
        // The loaders + `ash::{Entry,Instance,Device}` are dispatch-table clones
        // over the same underlying objects; the raw `vk::*` handles are `Copy`;
        // the window + (already-`Option`) debug messenger + timestamp pool are
        // MOVED out so this context's Drop leaves them for the successor.
        let reuse = VkReuse {
            window: self
                .window
                .take()
                .ok_or("apply_world_reload: window already taken")?,
            entry: self._entry.clone(),
            instance: self.instance.clone(),
            device: self.device.clone(),
            physical_device: self.physical_device,
            surface: self.surface,
            surface_loader: self.surface_loader.clone(),
            graphics_queue: self.graphics_queue,
            present_queue: self.present_queue,
            graphics_family: self.graphics_family,
            swapchain_loader: self.swapchain.loader.clone(),
            swapchain: self.swapchain.handle,
            swapchain_images: self.swapchain.images.clone(),
            swapchain_format: self.swapchain.format,
            swapchain_extent: self.swapchain.extent,
            msaa_samples: self.msaa_samples,
            hdr_mode: self.hdr_mode,
            memory_budget_supported: self.memory_budget_supported,
            rt_capable: self.rt_capable,
            update_after_bind: self.update_after_bind,
            device_local_heaps: self.device_local_heaps.clone(),
            timestamp_query_pool: self.timestamp_query_pool.take(),
            timestamp_period: self.timestamp_period_ns,
            alloc: self.alloc.clone(),
        };
        // Free the old world into the shared allocator BEFORE the successor
        // builds, and make the released ranges placeable now (`wait_idle`
        // above gated everything in flight): the rebuild then fills the same
        // blocks instead of doubling the device footprint for the reload's
        // duration. The flag is set first so the content pass keeps the
        // swapchain for the successor; a build failure unsets it and re-runs
        // the swapchain teardown the content pass skipped, so the
        // failed-session `Drop` still tears the shared hardware down.
        self.reused_by_successor = true;
        self.destroy_world_content();
        self.alloc.reclaim_idle();
        // The old world's pipelines, layouts and render passes queued on the
        // device's retire list as their owners dropped; the `wait_idle` above
        // means they can go now rather than after the successor's first frames.
        self.device.reclaim_idle();
        tracing::debug!("reload: old world freed: {}", self.alloc.stats());
        match VkContext::build(init, Some(reuse)) {
            Ok(rebuilt) => {
                *self = rebuilt;
                Ok(())
            }
            Err(e) => {
                self.reused_by_successor = false;
                self.destroy_swapchain_resources();
                Err(e)
            }
        }
    }
}

// The shared hardware `VkContext::build` acquires (fresh launch) or inherits
// (live editor reload) before it builds any per-world resource. Destructured
// right after so the rest of `build` is identical on both paths.
struct SharedHardware {
    window: super::PlatformWindow,
    entry: ash::Entry,
    instance: ash::Instance,
    device: super::owned::VkDevice,
    physical_device: vk::PhysicalDevice,
    surface: vk::SurfaceKHR,
    surface_loader: ash::khr::surface::Instance,
    graphics_queue: vk::Queue,
    present_queue: vk::Queue,
    graphics_family: u32,
    swapchain_loader: ash::khr::swapchain::Device,
    swapchain: vk::SwapchainKHR,
    swapchain_images: Vec<vk::Image>,
    swapchain_format: vk::Format,
    swapchain_extent: vk::Extent2D,
    swapchain_image_views: Vec<vk::ImageView>,
    msaa_samples: vk::SampleCountFlags,
    hdr_mode: crate::gfx::hdr_output::HdrOutputMode,
    memory_budget_supported: bool,
    rt_capable: bool,
    update_after_bind: bool,
    device_local_heaps: Vec<u32>,
    timestamp_query_pool: Option<vk::QueryPool>,
    timestamp_period: f32,
    // Fresh on a launch; the outgoing context's on a reload, so the rebuilt
    // world places into the blocks the old world's leases released.
    alloc: super::allocator::DeviceAllocator,
}

// The shared hardware an outgoing context hands to its successor on a live
// editor `reload_world` (see `VkContext::apply_world_reload`). The loaders and
// `ash::{Entry,Instance,Device}` are cheap dispatch-table clones over the same
// underlying objects; the raw `vk::*` handles are `Copy`; the window and the
// (already-`Option`) debug + timestamp handles are moved out of the outgoing
// context so its `Drop` leaves them alone; the device allocator is a shared
// handle (clones share one pool). Vulkan handles are not refcounted, so the
// outgoing `Drop` also skips destroying the shared instance / device /
// surface / swapchain (gated on `reused_by_successor`).
pub(in crate::vulkan) struct VkReuse {
    window: super::PlatformWindow,
    entry: ash::Entry,
    instance: ash::Instance,
    device: super::owned::VkDevice,
    physical_device: vk::PhysicalDevice,
    surface: vk::SurfaceKHR,
    surface_loader: ash::khr::surface::Instance,
    graphics_queue: vk::Queue,
    present_queue: vk::Queue,
    graphics_family: u32,
    swapchain_loader: ash::khr::swapchain::Device,
    swapchain: vk::SwapchainKHR,
    swapchain_images: Vec<vk::Image>,
    swapchain_format: vk::Format,
    swapchain_extent: vk::Extent2D,
    msaa_samples: vk::SampleCountFlags,
    hdr_mode: crate::gfx::hdr_output::HdrOutputMode,
    memory_budget_supported: bool,
    rt_capable: bool,
    update_after_bind: bool,
    device_local_heaps: Vec<u32>,
    timestamp_query_pool: Option<vk::QueryPool>,
    timestamp_period: f32,
    alloc: super::allocator::DeviceAllocator,
}

impl VkReuse {
    // Turn the inherited hardware into a `SharedHardware`, recreating the only
    // per-context object among it: fresh swapchain image views over the reused
    // swapchain's images (the outgoing context frees its own views in Drop).
    fn into_shared(self) -> Result<SharedHardware, String> {
        let swapchain_image_views = create_swapchain_image_views(
            &self.device,
            &self.swapchain_images,
            self.swapchain_format,
        )?;
        Ok(SharedHardware {
            window: self.window,
            entry: self.entry,
            instance: self.instance,
            device: self.device,
            physical_device: self.physical_device,
            surface: self.surface,
            surface_loader: self.surface_loader,
            graphics_queue: self.graphics_queue,
            present_queue: self.present_queue,
            graphics_family: self.graphics_family,
            swapchain_loader: self.swapchain_loader,
            swapchain: self.swapchain,
            swapchain_images: self.swapchain_images,
            swapchain_format: self.swapchain_format,
            swapchain_extent: self.swapchain_extent,
            swapchain_image_views,
            msaa_samples: self.msaa_samples,
            hdr_mode: self.hdr_mode,
            memory_budget_supported: self.memory_budget_supported,
            rt_capable: self.rt_capable,
            update_after_bind: self.update_after_bind,
            device_local_heaps: self.device_local_heaps,
            timestamp_query_pool: self.timestamp_query_pool,
            timestamp_period: self.timestamp_period,
            alloc: self.alloc,
        })
    }
}

//  Shadow uniforms
//
// Per-frame cascade computation lives in `gfx::csm::compute_shadow_uniforms`
// and is invoked from `draw.rs` each frame using the current view matrix +
// camera position. The init path no longer computes a shadow VP; it just
// stores `empty_shadow_uniforms()` so the descriptor write at startup has a
// valid (fully-lit) buffer.

// Validation layer debug callback: logs validation errors and warnings.
// DLSS's first EvaluateFeature samples two NGX-internal resources it leaves in
// UNDEFINED, tripping VUID-vkCmdDraw-None-09600 exactly twice per feature
// creation. They are internal to nvngx_dlss.dll (not bindable through the NGX
// parameter API, confirmed by supplying our own exposure input, which did not
// displace them) and benign (the upscale output is correct). The debug messenger
// drops this many such messages while DLSS is the active upscaler. D3D12 never
// surfaces them (it has no image-layout validation model).
pub(super) const DLSS_FIRST_FRAME_LAYOUT_SUPPRESS: u32 = 2;

// Decide whether to drop a validation message rather than log it: true only for
// the benign DLSS first-frame layout VUID while `budget` is positive (consuming
// one unit of it). Every other VUID, and an exhausted budget, returns false so
// the message still surfaces. Split out from `debug_callback` so the suppression
// logic is unit testable without a live Vulkan instance.
fn drop_benign_dlss_layout_error(message_id: &[u8], budget: &std::sync::atomic::AtomicU32) -> bool {
    if message_id != b"VUID-vkCmdDraw-None-09600" {
        return false;
    }
    budget
        .fetch_update(
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
            |n| (n > 0).then(|| n - 1),
        )
        .is_ok()
}

// Validation messages route through here (installed only when validation is on).
// `user` is a `*const AtomicU32`: a budget of benign DLSS first-frame layout
// errors to drop, set after `build_upscaler` resolves to DLSS (and reset on
// resize, which re-creates the feature). Null when no budget is wired.
unsafe extern "system" fn debug_callback(
    severity: vk::DebugUtilsMessageSeverityFlagsEXT,
    _msg_type: vk::DebugUtilsMessageTypeFlagsEXT,
    data: *const vk::DebugUtilsMessengerCallbackDataEXT,
    user: *mut std::ffi::c_void,
) -> vk::Bool32 {
    if data.is_null() {
        return vk::FALSE;
    }
    // SAFETY: the null check above passed, and Vulkan guarantees the callback data outlives the
    // callback.
    let data = unsafe { &*data };

    // Drop the benign DLSS first-frame layout errors (see the helper); any other
    // VUID, or an exhausted budget, still logs.
    if !user.is_null() && !data.p_message_id_name.is_null() {
        // SAFETY: Vulkan fills `extension_name` with a NUL-terminated string, and the borrow does
        // not outlive the properties entry it points into.
        let vuid = unsafe { CStr::from_ptr(data.p_message_id_name) };
        // SAFETY: `user` is the `AtomicU32` budget pointer this messenger was registered with; it
        // is non-null per the check above and outlives the messenger.
        let budget = unsafe { &*(user as *const std::sync::atomic::AtomicU32) };
        if drop_benign_dlss_layout_error(vuid.to_bytes(), budget) {
            return vk::FALSE;
        }
    }

    // SAFETY: Vulkan fills `p_message` with a NUL-terminated string that lives for the duration of
    // the callback.
    let msg = unsafe { CStr::from_ptr(data.p_message) }.to_string_lossy();
    if severity.contains(vk::DebugUtilsMessageSeverityFlagsEXT::ERROR) {
        tracing::error!("[Vulkan] {}", msg);
    } else {
        tracing::warn!("[Vulkan] {}", msg);
    }
    vk::FALSE
}

#[cfg(test)]
mod tests {
    use super::{DLSS_FIRST_FRAME_LAYOUT_SUPPRESS, drop_benign_dlss_layout_error};
    use std::sync::atomic::{AtomicU32, Ordering};

    const LAYOUT_VUID: &[u8] = b"VUID-vkCmdDraw-None-09600";

    #[test]
    fn drops_exactly_the_budgeted_layout_errors_then_logs() {
        let budget = AtomicU32::new(DLSS_FIRST_FRAME_LAYOUT_SUPPRESS);
        for _ in 0..DLSS_FIRST_FRAME_LAYOUT_SUPPRESS {
            assert!(drop_benign_dlss_layout_error(LAYOUT_VUID, &budget));
        }
        // Budget spent: a further occurrence logs, so a real bug would surface.
        assert!(!drop_benign_dlss_layout_error(LAYOUT_VUID, &budget));
        assert_eq!(budget.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn never_drops_other_vuids_or_touches_budget() {
        let budget = AtomicU32::new(DLSS_FIRST_FRAME_LAYOUT_SUPPRESS);
        assert!(!drop_benign_dlss_layout_error(
            b"VUID-vkCmdDraw-None-02699",
            &budget
        ));
        assert!(!drop_benign_dlss_layout_error(b"", &budget));
        assert_eq!(
            budget.load(Ordering::Relaxed),
            DLSS_FIRST_FRAME_LAYOUT_SUPPRESS
        );
    }

    #[test]
    fn drops_nothing_when_budget_is_zero() {
        let budget = AtomicU32::new(0);
        assert!(!drop_benign_dlss_layout_error(LAYOUT_VUID, &budget));
    }
}