concinnity-device 0.18.64

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
// src/directx/init/mod.rs
//
// DxContext construction. The constructor is intentionally a flat top-to-
// bottom sequence so the order of dependencies stays obvious; helpers for
// self-contained sub-phases live in sibling modules:
//
//   window.rs    Win32 window + raw input + DXGI factory + adapter +
//                D3D12 device + info-queue + command queue + swapchain
//                + MSAA support query.
//   pipelines.rs Shader compile + main / shadow / instanced / text /
//                composite PSOs + bindless main pass + GPU-cull compute
//                pipeline and its per-frame UAV / upload buffers.
//   effects.rs   Bloom mip targets + pipelines, TAA velocity + history,
//                SSAO pre-pass + kernel + blur, SSAO white fallback.
//                Each gated on per-world settings.
//
// What still lives inline here:
//   * Descriptor heap creation (RTV / DSV / CBV+SRV+UAV / sampler) with
//     the cross-cutting slot layout.
//   * Sampler creation.
//   * Texture pool uploads, per-object + per-cluster SRV pair writes,
//     text atlas uploads, shadow map array, IBL cubes, colour LUT,
//     main-depth + HDR scene targets.
//   * Geometry + per-frame view / light / shadow constant buffers.
//   * Per-frame command infrastructure (allocator/list/fence), per-cluster
//     instance upload buffers, and the final `Self { ... }` literal.

use concinnity_core::gfx::transform::IDENTITY;
use std::cell::RefCell;

use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::System::Threading::CreateEventW;

use crate::directx::allocator::{PooledBuffer, PooledTexture};
use crate::gfx::mesh_payload::Vertex;
use crate::gfx::render_types::*;

use super::com;
use super::context::*;
use super::draw::*;
use super::post::bloom::bloom_mip_count;
use super::texture::*;

mod effects;
mod heap_layout;
pub(in crate::directx) mod pipelines;
mod window;

// Maximum Hi-Z mip count we reserve descriptor slots for. 15 mips covers
// every render target up to 16384 pixels in the larger dimension; an
// 8K display sits at 13. The Hi-Z resource clamps `mip_count` against this
// so the heap layout stays anchored even when the window resizes.
pub(in crate::directx) const HIZ_MAX_MIPS: usize = 15;

impl DxContext {
    // Construct a fresh context (new device + window + swapchain) from the
    // assembled backend inputs (see `crate::gfx::backend_init::BackendInit`).
    pub(crate) fn new(init: crate::gfx::backend_init::BackendInit<'_>) -> Result<Self, String> {
        Self::build(init, None)
    }

    // The shared constructor. `reuse == None` acquires fresh hardware (the
    // normal `new` path); `reuse == Some` rebuilds only the world's content on
    // the retained device + window + swapchain for a live `cn editor` world
    // reload (see `reload_world`). Everything after the device/window
    // acquisition is identical -- the same pipelines, buffers, textures, and
    // targets are built from `init` either way; the DirectX-specific behaviour
    // of each input is documented inline below.
    fn build(
        init: crate::gfx::backend_init::BackendInit<'_>,
        reuse: Option<window::DeviceAndWindow>,
    ) -> Result<Self, String> {
        use crate::gfx::backend_init::{
            BackendInit, MediaPayloads, PostSettings, SceneData, ShaderBytes, ShadowParams, WorldFx,
        };
        let BackendInit {
            window,
            validation,
            // D3D12 always renders FRAMES=3 in flight; this is retained only so
            // `hot_swap_config` can report the world's request for the reload gate.
            frames_in_flight,
            vsync,
            clear_color,
            hot_reload,
            // DirectX retains the presented back-buffer index unconditionally,
            // so capture needs no arming here.
            capture: _,
            scene:
                SceneData {
                    vertices,
                    indices,
                    draw_objects,
                    instanced_clusters,
                    // Skinned draw-object count, threaded purely to size the
                    // shared cull / object / draw-args / indirect buffers for the
                    // merged total at init (`n_objects + n_instances +
                    // n_skinned`); the skinned geometry itself is uploaded later
                    // by `upload_skinned`, which sets the live `self.draw.n_skinned`.
                    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,
            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 D3D12 1..16 range 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_reflection_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,
                    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) = (window.title.as_str(), window.width, window.height);
        // 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();

        // FSR3 needs the velocity buffer + the TAA-velocity pre-pass
        // PSOs, both of which live inside `TaaResources`. When upscale
        // is on we force the TAA resources to be built even if the
        // world's `PostProcessConfig.aa_mode` is off; the TAA *resolve*
        // pass is still skipped (see `record_frame::seed_inputs`),
        // because FSR owns the temporal accumulation.
        let taa_enabled = taa_enabled || temporal_upscaling;
        // Win32 window + DXGI factory + device + info-queue + command queue +
        // MSAA support + swapchain. See init/window.rs. The HDR-display
        // negotiation also happens in there: a capable adapter + a `true`
        // toggle yields a `RGBA16Float` scRGB swapchain; otherwise the
        // returned `hdr_mode` is `Sdr` and the swapchain stays at BGRA8Unorm.
        let window::DeviceAndWindow {
            win_state,
            device,
            info_queue,
            command_queue,
            swapchain,
            swapchain_format,
            allow_tearing,
            msaa_samples,
            adapter,
            hdr_mode,
        } = match reuse {
            // Live editor reload: reuse the retained device + window + swapchain
            // (HDR was already negotiated on the unchanged swapchain, so `setup`
            // is skipped). Only the world content below is rebuilt.
            Some(dw) => dw,
            None => window::setup(
                window::WindowConfig {
                    title,
                    width,
                    height,
                    title_bar: window.title_bar,
                },
                validation,
                vsync,
                hdr_display,
                hdr_pq,
            )?,
        };
        // Persisted pipeline library: seeded from disk when a blob for this
        // adapter exists, consulted by every PSO creation below. No-op on the
        // reload path, where it is already installed.
        super::pso_library::install(&device, adapter.as_ref());
        // Placement pool for every persistent buffer and CPU-uploaded texture.
        // Built before the first resource so nothing has to fall back to a
        // committed allocation.
        let alloc = super::allocator::DeviceAllocator::new(&device, &command_queue, FRAMES);
        // The swapchain config the caller's reload gate compares against.
        let swapchain_config = crate::gfx::backend_init::SwapchainConfig {
            frames_in_flight: frames_in_flight.max(1),
            hdr_display,
            hdr_pq,
        };
        // Presentation pacing derived from the vsync request + tearing support.
        // vsync on -> sync interval 1 (lock to refresh). vsync off + tearing ->
        // sync interval 0 with the tearing present flag (true uncapped). vsync
        // off without tearing -> sync interval 0, no flag (flip-model refresh
        // pacing, the best available fallback).
        let present_sync_interval: u32 = if vsync { 1 } else { 0 };
        // Pair the authored tunables with the resolved mode's output flags. On
        // the SDR path both stay 0.0 and the shader runs the full ACES + gamma
        // + FXAA + LUT chain unchanged. Inside the HDR branch, `pq_output`
        // picks scRGB-linear passthrough (0.0) vs SMPTE ST 2084 in-shader
        // encode (1.0). Mirrors the Metal hop in `metal/init/mod.rs`. `setup`
        // may have already downgraded the encoding when
        // `CheckColorSpaceSupport(HDR10 PQ)` came back negative, so composing
        // after `setup` returns is what makes `hdr_mode` the source of truth.
        let post_process = hdr_mode.post_process_params(post_tunables);

        // Hardware ray-tracing capability. RT reflection resources + the
        // acceleration structure are built only when the world authored
        // `ray_traced_reflections` AND the GPU reports the DXR 1.1 tier inline
        // `RayQuery` needs; otherwise the renderer falls back to SSR.
        let raytracing_supported = super::raytrace::raytracing_supported(&device);
        let rt_enabled = rt_reflection_settings.is_some() && raytracing_supported;
        if rt_reflection_settings.is_some() && !raytracing_supported {
            tracing::warn!(
                "ray_traced_reflections requested but the GPU does not report DXR \
                 tier 1.1; falling back to screen-space reflections"
            );
        }

        // RTV heap
        // Slots: [0..FRAMES) = back-buffer RTVs, [FRAMES] = HDR scene RTV,
        // [FRAMES+1 .. FRAMES+1+bloom_count] = bloom mip RTVs, then (TAA only)
        // the velocity RTV + two ping-pong history RTVs.
        let bloom_count = bloom_mip_count(width, height) as usize;
        // The five live-toggleable Quality features (TAA, SSAO, SSR, SSGI, and
        // the unified G-buffer pre-pass they share) reserve their RTV / DSV / SRV
        // slots UNCONDITIONALLY, independent of the world's init-time gates. The
        // slots are fixed positions the passes bind by absolute index, so a live
        // toggle (`apply_quality_settings`) can build a feature that launched off
        // and write into its pre-reserved slot without shifting any other
        // feature's slots. A reserved-but-unbuilt feature leaves its slots
        // unwritten; that is safe because no always-running pass binds them (each
        // feature's own pass runs only when the feature is on, and the main pass's
        // SSAO occlusion binding falls back to the 1x1 white slot below), matching
        // the existing reserved-but-unwritten SSR slot in a SSGI-only build. The
        // `*_enabled` / `*_present` gates below still drive whether the resources
        // are BUILT at init, just not whether the slots exist.
        //
        // TAA: 2 ping-pong history RTVs after the bloom mip RTVs + 2 history SRVs
        // after the colour LUT SRV. Its motion comes from the G-buffer pre-pass,
        // so TAA reserves no DSV of its own.
        let taa_rtv_extra = 2;
        let taa_srv_extra = 2;
        // SSAO: 2 RTVs (ao_raw + ao) + 2 SRVs (ao_raw + ao); view normal + depth
        // come from the G-buffer pre-pass, so no DSV. A 1x1 white fallback always
        // sits one slot further so the main pass binds a constant 1.0 occlusion
        // when SSAO is off (this is the one feature SRV an always-running pass
        // binds, hence the always-present fallback).
        let ssao_enabled = ssao_settings.is_some();
        let ssao_rtv_extra = 2;
        let ssao_srv_extra = 2;
        // SSR: 1 RTV + 1 SRV (resolve output); view normal + depth + roughness
        // come from the G-buffer pre-pass, so no DSV. SSR / SSGI / RT all reuse
        // the pre-pass; `ssr_prepass_present` still gates whether `SsrResources`
        // is built at init.
        let ssr_prepass_present = ssr_settings.is_some() || ssgi_settings.is_some() || rt_enabled;
        let ssr_rtv_extra = 1;
        let ssr_srv_extra = 1;
        // SSGI gather target: 1 RTV (the gather writes it) + 1 SRV (the composite
        // reads it).
        let ssgi_rtv_extra = 1;
        let ssgi_srv_extra = 1;
        // RT-reflection output: 1 RTV (the trace writes it) at the RTV-heap tail
        // + 1 SRV (the post stack samples it) at the SRV-heap tail. Reserved
        // UNCONDITIONALLY like the other live-toggleable features, so a live
        // `apply_quality_settings` RT enable (on a DXR-capable GPU) builds the
        // output into its fixed slot without shifting any other feature's slots.
        // `rt_enabled` still gates whether RT is BUILT at init, just not the slot.
        let rt_rtv_extra = 1;
        let rt_srv_extra = 1;
        // Reflection composite: 2 RTVs (composited output + reduced-res blur) at the
        // RTV-heap tail + 2 SRVs at the SRV-heap tail. Reserved UNCONDITIONALLY (like
        // SSR / RT) so a live `apply_quality_settings` reflection enable can build it
        // into its fixed slots; the resources themselves build at init only when SSR
        // resolve or RT is authored.
        let refl_composite_rtv_extra = 2;
        let refl_composite_srv_extra = 2;
        // Unified G-buffer pre-pass: 3 RTVs (normal+depth, roughness, velocity),
        // 1 DSV (private depth), 3 SRVs. Slots always reserved; `gbuffer_enabled`
        // still gates whether the pre-pass resources are built at init (any
        // screen-space consumer: SSR / SSGI, SSAO, or TAA / FSR velocity).
        // `taa_enabled` already folds in temporal upscaling, covering velocity.
        let gbuffer_enabled = taa_enabled || ssao_enabled || ssr_prepass_present;
        let gbuffer_rtv_extra = 3;
        let gbuffer_dsv_extra = 1;
        let gbuffer_srv_extra = 3;
        // Projected decals: always-on infrastructure so runtime `add_decal`
        // works from a world that started empty. One extra RTV for
        // `hdr_resolve` (only when MSAA is on; the MSAA-off path writes
        // through the existing `hdr_color` RTV), one SRV for the main depth,
        // and `MAX_DECALS` per-decal albedo SRV slots.
        let decal_rtv_extra = if msaa_samples > 1 { 1 } else { 0 };
        let decal_srv_extra = crate::directx::decal::MAX_DECALS + 1;
        let _ = &decals; // referenced below where the pipeline is built.
        // SAFETY: the create descriptor and every pointer it borrows are live for the call, and the
        // new COM object lands in a binding that owns it.
        let rtv_heap: ID3D12DescriptorHeap = unsafe {
            device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
                Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
                NumDescriptors: FRAMES as u32
                    + 1
                    + bloom_count as u32
                    + taa_rtv_extra as u32
                    + ssao_rtv_extra as u32
                    + ssr_rtv_extra as u32
                    + ssgi_rtv_extra as u32
                    + decal_rtv_extra as u32
                    + gbuffer_rtv_extra as u32
                    + rt_rtv_extra as u32
                    + refl_composite_rtv_extra as u32,
                ..Default::default()
            })
        }
        .map_err(|e| format!("RTV heap: {e}"))?;
        let rtv_descriptor_size =
            // SAFETY: a property query on a live descriptor heap; it only reads.
            unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) }
                as usize;

        // Back-buffer RTVs
        let mut back_buffers = Vec::with_capacity(FRAMES);
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let rtv_base = unsafe { rtv_heap.GetCPUDescriptorHandleForHeapStart() };
        for i in 0..FRAMES {
            // SAFETY: a query on a live COM object; the descriptor it reads and the out-parameters
            // it fills are live locals that outlive the call.
            let buf: ID3D12Resource = unsafe { swapchain.GetBuffer(i as u32) }
                .map_err(|e| format!("GetBuffer[{i}]: {e}"))?;
            let rtv_handle = D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: rtv_base.ptr + i * rtv_descriptor_size,
            };
            // SAFETY: the view descriptor and the resource it names are live for the call, and the
            // destination handle addresses a slot this context reserved for the view in a heap it
            // owns.
            unsafe {
                device.CreateRenderTargetView(&buf, None, rtv_handle);
            }
            back_buffers.push(buf);
        }

        // DSV heap
        // Slots: [0] = main depth, [1..1+NUM_SHADOW_CASCADES] = per-cascade
        // shadow DSVs (one slice each into the shadow map array),
        // [..+MAX_SHADOWED_SPOTS] = per-spot shadow slice DSVs, then the
        // unified G-buffer pre-pass's private depth buffer.
        // SAFETY: the create descriptor and every pointer it borrows are live for the call, and the
        // new COM object lands in a binding that owns it.
        let dsv_heap: ID3D12DescriptorHeap = unsafe {
            device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
                Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
                NumDescriptors: 1
                    + NUM_SHADOW_CASCADES as u32
                    + MAX_SHADOWED_SPOTS as u32
                    + gbuffer_dsv_extra as u32,
                ..Default::default()
            })
        }
        .map_err(|e| format!("DSV heap: {e}"))?;
        let dsv_descriptor_size =
            // SAFETY: a property query on a live descriptor heap; it only reads.
            unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) }
                as usize;
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let dsv_base = unsafe { dsv_heap.GetCPUDescriptorHandleForHeapStart() };
        let main_dsv_cpu = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dsv_base.ptr };
        let shadow_dsv_base_cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: dsv_base.ptr + dsv_descriptor_size,
        };
        let spot_shadow_dsv_base_cpu = D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: dsv_base.ptr + (1 + NUM_SHADOW_CASCADES) * dsv_descriptor_size,
        };

        // CBV/SRV/UAV heap slot layout. The full per-block map + the
        // positional cascade live in `heap_layout.rs`, which a unit test
        // anchors so a stray offset edit fails a test instead of silently
        // misbinding a descriptor at shader time.
        let n_objects = draw_objects.len();
        let n_clusters = instanced_clusters.len();
        let n_atlases = text_atlases.len();
        // Flat bindless pool sizes, derived from the resource pools built below.
        // Albedo and normal maps share ONE handle-indexed pool: the real
        // textures (a 1x1 white fallback stands in when there are none)
        // followed by the reserved fallback pair, flat-normal then white, for
        // draws with no normal map and no albedo.
        let flat_albedo_count = textures.len().max(1);
        let flat_fallback_count = FALLBACK_TEXTURE_COUNT;
        let _ = decal_srv_extra; // folded into the heap_layout decal block.

        // Planar reflections: group each transparent reflector's 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). The
        // distinct count sizes the reserved planar-resolve SRV block; `slots[i]` is
        // reflector `i`'s resolve slot (or `None`). Computed here (pre-heap) so the
        // block is sized before the heap is created; the set itself is built after
        // the render dims are known.
        //
        // Water first, then glass, matching the Metal backend, so the two slot
        // ranges are `[..water_surfaces.len()]` and the rest.
        let planar_panes: 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::directx::planar::pane_plane(p.normal, p.centre)),
            )
            .collect();
        // Cap at the capacity ceiling the reserved planar resolve SRVs are sized to,
        // so a stale/over-large preset value can never over-allocate.
        let planar_budget = planar_planes.min(crate::directx::planar::MAX_PLANAR_PLANES);
        let planar_assignment =
            crate::gfx::planar_reflection::assign_planar_slots(&planar_panes, planar_budget);
        let planar_resolve_srv_extra = planar_assignment.representatives.len();

        let heap_layout::SrvHeapLayout {
            object_base_slot,
            hdr_srv_slot,
            bloom_srv_base_slot,
            lut_srv_slot,
            taa_srv_base_slot,
            ssao_srv_base_slot,
            ssao_white_srv_slot,
            ssr_srv_base_slot,
            decal_depth_srv_slot,
            decal_srv_base_slot,
            chunk_srv_base_slot,
            skinned_srv_base_slot,
            particle_srv_base_slot,
            clone_srv_base_slot,
            fog_froxel_uav_slot,
            fog_froxel_srv_slot,
            upscale_uav_slot,
            upscale_srv_slot,
            raymarch_srv_base_slot,
            hiz_srv_slot,
            hiz_uav_base_slot,
            transparent_scene_copy_srv_slot,
            ssgi_gi_srv_slot,
            gbuffer_srv_base_slot,
            rt_output_srv_slot,
            refl_composite_srv_base_slot,
            planar_resolve_srv_base_slot,
            flat_pool_base_slot,
            probe_cube_base_slot,
            spot_shadow_srv_slot,
            ltc_srv_base_slot,
            srv_slots,
        } = heap_layout::SrvHeapLayout::compute(&heap_layout::SrvHeapParams {
            n_objects,
            n_clusters,
            n_atlases,
            bloom_count,
            taa_srv_extra,
            ssao_srv_extra,
            ssr_srv_extra,
            ssgi_srv_extra,
            gbuffer_srv_extra,
            rt_output_srv_extra: rt_srv_extra,
            refl_composite_srv_extra,
            planar_resolve_srv_extra,
            albedo_count: flat_albedo_count,
            normal_count: flat_fallback_count,
        });
        // SAFETY: the create descriptor and every pointer it borrows are live for the call, and the
        // new COM object lands in a binding that owns it.
        let srv_heap: ID3D12DescriptorHeap = unsafe {
            device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
                Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
                // `srv_slots` is the running total of every block in the
                // heap_layout cascade, so it sizes the heap to exactly cover
                // the highest slot any descriptor write addresses.
                NumDescriptors: srv_slots as u32,
                Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
                ..Default::default()
            })
        }
        .map_err(|e| format!("SRV heap: {e}"))?;
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let srv_descriptor_size = unsafe {
            device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
        } as usize;
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let srv_cpu_base = unsafe { srv_heap.GetCPUDescriptorHandleForHeapStart() };
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let srv_gpu_base = unsafe { srv_heap.GetGPUDescriptorHandleForHeapStart() };

        let slot_cpu = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: srv_cpu_base.ptr + i * srv_descriptor_size,
        };
        let slot_gpu = |i: usize| D3D12_GPU_DESCRIPTOR_HANDLE {
            ptr: srv_gpu_base.ptr + (i * srv_descriptor_size) as u64,
        };

        // Temporal upscaler (FSR3 via the FidelityFX SDK). Built here,
        // ahead of the HDR / depth / post-effect targets, because its
        // resolved render dimensions decide the size of every scene target.
        // When the world's `PostProcessConfig.temporal_upscaling` is on AND
        // the FFX DLL loads + the context creates successfully, this returns
        // `Some` and the scene renders at `output * upscale_scale`; FSR
        // reconstructs the drawable resolution into the upscaler's output
        // texture, which bloom + composite sample. Falls back silently (logs
        // a warning, leaves render == output) when the SDK isn't on `PATH`
        // or the GPU rejects the context build, so a missing SDK degrades
        // to native-resolution TAA rather than a low-res bilinear stretch.
        let upscaler = if temporal_upscaling {
            crate::directx::post::upscale::build_upscaler(
                &device,
                &command_queue,
                width,
                height,
                upscale_scale,
                crate::directx::post::upscale::UpscalerDescriptors {
                    uav_cpu: slot_cpu(upscale_uav_slot),
                    srv_cpu: slot_cpu(upscale_srv_slot),
                    srv_gpu: slot_gpu(upscale_srv_slot),
                },
                upscale_backend,
            )?
            .0
        } else {
            None
        };
        // Off-screen scene render resolution. The active backend reports the
        // resolved render dims (clamped to the backend's supported ratio
        // range); a missing / failed upscaler leaves the scene at full output.
        let (render_w, render_h) = match &upscaler {
            Some(u) => u.render_dims(),
            None => (width, height),
        };
        if upscaler.is_some() {
            tracing::info!(
                "DirectX: temporal upscaling active: scene render {}x{}, drawable {}x{}",
                render_w,
                render_h,
                width,
                height
            );
        }

        // Sampler heap
        // Slots: [0]=shadow comparison, [1]=linear repeat, [2]=cube linear-clamp+mip,
        //        [3]=linear clamp (text). linear+cube are placed contiguously so the
        //        main pass binds them via a single 2-descriptor table range.
        // Slots [4..7] are the raymarch pass's contiguous descriptor table:
        // shadow comparison, cube linear-clamp, and a linear-clamp scene
        // sampler. These duplicate samplers at slots 0 / 2 so the raymarch
        // root sig can bind a single 3-slot range; the cost is three extra
        // descriptors (a few bytes). Reserved unconditionally so the heap
        // layout stays anchored.
        let raymarch_sampler_base_slot = 4usize;
        // SAFETY: the create descriptor and every pointer it borrows are live for the call, and the
        // new COM object lands in a binding that owns it.
        let sampler_heap: ID3D12DescriptorHeap = unsafe {
            device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
                Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
                NumDescriptors: 7,
                Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
                ..Default::default()
            })
        }
        .map_err(|e| format!("sampler heap: {e}"))?;
        let sampler_descriptor_size =
            // SAFETY: a property query on a live descriptor heap; it only reads.
            unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) }
                as usize;
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let samp_cpu_base = unsafe { sampler_heap.GetCPUDescriptorHandleForHeapStart() };
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let samp_gpu_base = unsafe { sampler_heap.GetGPUDescriptorHandleForHeapStart() };

        create_samplers(&device, samp_cpu_base, sampler_descriptor_size, anisotropy);

        let shadow_sampler_gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
            ptr: samp_gpu_base.ptr,
        };
        let linear_sampler_gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
            ptr: samp_gpu_base.ptr + sampler_descriptor_size as u64,
        };
        let text_sampler_gpu = D3D12_GPU_DESCRIPTOR_HANDLE {
            ptr: samp_gpu_base.ptr + (3 * sampler_descriptor_size) as u64,
        };

        // Shadow map array
        // Real path: NUM_SHADOW_CASCADES-slice Texture2DArray with per-slice DSVs.
        // Fallback: 1×1 single-slice R32_FLOAT array with value 0.0 (LESS_EQUAL
        // always passes → fully lit), declared as Texture2DArray so the shader's
        // binding type stays identical between disabled and enabled cases.
        // CSM is gated on `shadow_map_size` (from GraphicsConfig; 0 disables
        // shadows). The shadow vertex shader is engine-internal (the baked
        // `builtins::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_resource_opt, shadow_dsvs, shadow_srv_gpu) = if effective_shadow_size > 0 {
            let (sm, dsvs) = create_shadow_map_array(
                &device,
                effective_shadow_size,
                NUM_SHADOW_CASCADES as u32,
                shadow_dsv_base_cpu,
                dsv_descriptor_size,
                slot_cpu(0),
                slot_gpu(0),
            )?;
            (Some(sm), dsvs, slot_gpu(0))
        } else {
            let fb = create_fallback_shadow_array(&alloc, slot_cpu(0), slot_gpu(0))?;
            (Some(fb), Vec::new(), slot_gpu(0))
        };

        // Spot shadow map array: one slice per shadow-casting spot light, at a
        // quarter the cascade resolution (a spot slice covers a single cone, not
        // a view-frustum slab). Local lights are static, so the slice count and
        // every light-space matrix are fixed here; only the depth refreshes.
        // A world with no shadowed spot still binds a 1x1 fallback so the main
        // pass's SRV is never unwritten.
        let spot_shadow_slice_size =
            crate::gfx::render_types::spot_shadow_slice_size(effective_shadow_size);
        let (spot_shadow_resource, spot_shadow_dsvs) = if spot_shadows.is_empty() {
            let fb = create_fallback_shadow_array(
                &alloc,
                slot_cpu(spot_shadow_srv_slot),
                slot_gpu(spot_shadow_srv_slot),
            )?;
            (Some(fb), Vec::new())
        } else {
            let (sm, dsvs) = create_shadow_map_array(
                &device,
                spot_shadow_slice_size,
                spot_shadows.len() as u32,
                spot_shadow_dsv_base_cpu,
                dsv_descriptor_size,
                slot_cpu(spot_shadow_srv_slot),
                slot_gpu(spot_shadow_srv_slot),
            )?;
            (Some(sm), dsvs)
        };
        // The per-slice projections, uploaded once. A scene with no shadowed
        // spot gets a one-element identity buffer: the shader never indexes it
        // (every `shadow_index` is -1) but the root SRV must still be valid.
        let spot_shadow_data = if spot_shadows.is_empty() {
            vec![crate::gfx::render_types::SpotShadowData::ZERO]
        } else {
            spot_shadows.clone()
        };
        let spot_shadow_buffer = {
            use crate::gfx::render_types::SpotShadowData;
            let size = align256((spot_shadow_data.len() * size_of::<SpotShadowData>()) as u64);
            let buf = create_buffer(
                &alloc,
                size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            upload_static_records(&buf, &spot_shadow_data, "spot-shadow")?;
            buf
        };
        // One `ShadowUniforms` per slice, each carrying that spot's matrix in
        // `light_vps[0]`, so the shared shadow vertex shader renders a spot
        // slice by pushing cascade_idx = 0. Written once: the projections never
        // change, so unlike the cascade UBO this needs no per-frame ring.
        let spot_shadow_ubo_stride = align256(size_of::<ShadowUniforms>() as u64);
        let spot_shadow_ubo = {
            let slots = spot_shadows.len().max(1) as u64;
            let buf = create_buffer(
                &alloc,
                spot_shadow_ubo_stride * slots,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            let mut ptr = std::ptr::null_mut::<std::ffi::c_void>();
            // SAFETY: the resource is a live CPU-visible buffer, and the out-parameter is a live
            // local that receives the mapping.
            unsafe { buf.Map(0, None, Some(&mut ptr)) }
                .map_err(|e| format!("map spot-shadow UBO: {e}"))?;
            for (i, sd) in spot_shadows.iter().enumerate() {
                let mut u = crate::gfx::csm::empty_shadow_uniforms();
                u.light_vps[0] = sd.light_vp;
                u.active_cascades = 1;
                // SAFETY: the mapping covers an UPLOAD-heap buffer created to hold this payload,
                // and the source is a separate allocation, so the ranges cannot overlap.
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        &u as *const ShadowUniforms as *const u8,
                        (ptr as *mut u8).add(i * spot_shadow_ubo_stride as usize),
                        size_of::<ShadowUniforms>(),
                    );
                }
            }
            // SAFETY: the resource is live and this code mapped it, and nothing keeps the mapping
            // past this call.
            unsafe { buf.Unmap(0, None) };
            buf
        };

        // Per-scene rectangular area lights: the edge vectors that do not fit in
        // `GpuLight`, indexed by its `data_index`. A world with no area light
        // still gets a one-element buffer, since the shader never reads it
        // (`data_index` stays -1) but the root SRV must be valid.
        let area_light_data = if area_lights.is_empty() {
            vec![crate::gfx::render_types::AreaLightData::ZERO]
        } else {
            area_lights.clone()
        };
        let area_light_buffer = {
            use crate::gfx::render_types::AreaLightData;
            let size = align256((area_light_data.len() * size_of::<AreaLightData>()) as u64);
            let buf = create_buffer(
                &alloc,
                size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            upload_static_records(&buf, &area_light_data, "area-light")?;
            buf
        };

        // Area-light LTC tables. Scene-independent (they depend only on the
        // build-time fit), so they are created unconditionally and the shader
        // simply never samples them when no area light is declared.
        let ltc_size = crate::gfx::ltc::LTC_LUT_SIZE as u32;
        let ltc_matrix_texture = upload_float_lut(
            &alloc,
            ltc_size,
            4,
            crate::gfx::ltc::matrix_texels(),
            slot_cpu(ltc_srv_base_slot),
            slot_gpu(ltc_srv_base_slot),
        )?;
        let ltc_magnitude_texture = upload_float_lut(
            &alloc,
            ltc_size,
            2,
            crate::gfx::ltc::magnitude_texels(),
            slot_cpu(ltc_srv_base_slot + 1),
            slot_gpu(ltc_srv_base_slot + 1),
        )?;

        // IBL cubemaps (irradiance + prefilter)
        // When env_map_bytes is Some, deserialise the EnvironmentMap payload and
        // upload both cubes. Otherwise bind a 1×1 grey fallback for each; the
        // shader keys off prefilter_mip_count == 0 to skip IBL math.
        let env_map = if let Some(bytes) = env_map_bytes {
            let view = crate::build::environment_map::deserialise(bytes)
                .map_err(|e| format!("EnvironmentMap payload malformed: {e}"))?;
            upload_environment_map(
                &alloc,
                crate::directx::texture::EnvironmentMapPayload {
                    irradiance_face: view.irradiance_face,
                    irradiance_bytes: view.irradiance_bytes,
                    prefilter_face: view.prefilter_face,
                    mip_bytes: &view.prefilter_mip_bytes,
                },
                crate::directx::texture::EnvironmentMapDescriptors {
                    irr_srv_cpu: slot_cpu(1),
                    irr_srv_gpu: slot_gpu(1),
                    pre_srv_cpu: slot_cpu(2),
                    pre_srv_gpu: slot_gpu(2),
                },
            )?
        } else {
            let irradiance =
                create_fallback_cubemap(&alloc, [0.05, 0.05, 0.05, 1.0], slot_cpu(1), slot_gpu(1))?;
            let prefilter =
                create_fallback_cubemap(&alloc, [0.05, 0.05, 0.05, 1.0], slot_cpu(2), slot_gpu(2))?;
            EnvironmentMapTextures {
                irradiance,
                prefilter,
                prefilter_mip_count: 0,
            }
        };

        // Reflection-probe cube array: point every slot at the sky prefilter cube so
        // the bindless main shader's `probe_cubes` table is valid before any probe
        // bakes (unbaked slots stay the sky; a baked probe overwrites its slot in
        // `probe_install`). The forward shader only samples a slot when
        // `ProbeSet.count` covers it, but the descriptor table must still be valid.
        let probe_sky_mips = env_map.prefilter_mip_count.max(1);
        for k in 0..concinnity_render::uniforms::MAX_PROBES {
            crate::directx::texture::write_cube_srv_mips(
                &device,
                &env_map.prefilter.resource,
                probe_sky_mips,
                slot_cpu(probe_cube_base_slot + k),
            );
        }

        // ProbeSet constant buffers: a `FRAMES` ring the main pass binds at root
        // param [11] (written per frame from `probe_set`), plus a static count-0 CBV
        // the asynchronous capture binds so a probe face samples the sky, not other
        // probes (and never reads the live ring while `record_frame` rewrites it).
        let probe_set_size =
            align256(std::mem::size_of::<concinnity_render::uniforms::ProbeSet>() as u64);
        let mut probe_set_cbvs: Vec<PooledBuffer> = Vec::with_capacity(FRAMES);
        let mut probe_set_cbv_ptrs: Vec<*mut u8> = Vec::with_capacity(FRAMES);
        for _ in 0..FRAMES {
            let buf = create_buffer(
                &alloc,
                probe_set_size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            let mut ptr = std::ptr::null_mut::<std::ffi::c_void>();
            // SAFETY: the resource is a live CPU-visible buffer, and the out-parameter is a live
            // local that receives the mapping.
            unsafe { buf.Map(0, None, Some(&mut ptr)) }
                .map_err(|e| format!("map probe set cbv: {e}"))?;
            // Initialise to the empty set (count 0) until the first frame writes it.
            let empty = concinnity_render::uniforms::ProbeSet::EMPTY;
            // SAFETY: the mapping covers an UPLOAD-heap buffer created to hold this payload, and
            // the source is a separate allocation, so the ranges cannot overlap.
            unsafe {
                std::ptr::copy_nonoverlapping(
                    &empty as *const concinnity_render::uniforms::ProbeSet as *const u8,
                    ptr as *mut u8,
                    std::mem::size_of::<concinnity_render::uniforms::ProbeSet>(),
                );
            }
            probe_set_cbv_ptrs.push(ptr as *mut u8);
            probe_set_cbvs.push(buf);
        }
        let probe_set_empty_cbv = {
            let buf = create_buffer(
                &alloc,
                probe_set_size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            let mut ptr = std::ptr::null_mut::<std::ffi::c_void>();
            // SAFETY: the resource is a live CPU-visible buffer, and the out-parameter is a live
            // local that receives the mapping.
            unsafe { buf.Map(0, None, Some(&mut ptr)) }
                .map_err(|e| format!("map probe empty cbv: {e}"))?;
            let empty = concinnity_render::uniforms::ProbeSet::EMPTY;
            // SAFETY: the mapping covers an UPLOAD-heap buffer created to hold this payload, and
            // the source is a separate allocation, so the ranges cannot overlap.
            unsafe {
                std::ptr::copy_nonoverlapping(
                    &empty as *const concinnity_render::uniforms::ProbeSet as *const u8,
                    ptr as *mut u8,
                    std::mem::size_of::<concinnity_render::uniforms::ProbeSet>(),
                );
                buf.Unmap(0, None);
            }
            buf
        };

        // Cache the first directional light's direction for per-frame CSM updates.
        let shadow_light_dir = crate::gfx::lights::sun_direction(&light_uniforms);

        // Cache the first directional light's colour * intensity for the
        // volumetric-fog encoder, since `LightUniforms` 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);

        // Albedo texture pool
        // One ID3D12Resource per input texture; SRVs are written below at
        // per-object pair slots so a single texture can be referenced by many
        // objects. When no textures were declared, a single 1x1 white fallback
        // stands in so every object's albedo slot resolves to opaque white.
        let gpu_textures: Vec<PooledTexture> = if textures.is_empty() {
            vec![create_fallback_white_resource(&alloc)?]
        } else {
            textures
                .iter()
                .enumerate()
                .map(|(i, image)| {
                    upload_texture_image(&alloc, image).map_err(|e| format!("texture[{i}]: {e}"))
                })
                .collect::<Result<Vec<_>, _>>()?
        };

        // Reserved fallbacks, in the order `FALLBACK_TEXTURE_COUNT` documents:
        // the flat-normal resource a draw with no normal map samples, then the
        // white resource a draw with no albedo samples. Real normal maps and
        // albedos are textures in `gpu_textures` (the shared pool), addressed by
        // their own handle; only these two live in `fallback_textures`.
        let gpu_fallbacks: Vec<PooledTexture> = vec![
            create_fallback_flat_normal_resource(&alloc)?,
            create_fallback_white_resource(&alloc)?,
        ];

        // Flat deduplicated bindless pool: one SRV per distinct texture, then the
        // fallback pair at `flat_albedo_count`. The bindless main pass and
        // the RT hit shader bind this region's base and index it by a flat slot
        // (`albedo = texture_slot` or the white slot when the draw has none,
        // `normal = normal's own handle` or the flat-normal slot), mirroring
        // Vulkan/Metal. A shared texture resolves to ONE descriptor here, unlike
        // the per-object pairs below which bake a copy per draw.
        debug_assert_eq!(gpu_textures.len(), flat_albedo_count);
        debug_assert_eq!(gpu_fallbacks.len(), flat_fallback_count);
        let last_tex = gpu_textures.len() - 1;
        let flat_pool_len = flat_albedo_count + flat_fallback_count;
        for f in 0..FRAMES {
            let copy_base = flat_pool_base_slot + f * flat_pool_len;
            for (k, tex) in gpu_textures.iter().enumerate() {
                write_texture_srv(&device, tex, slot_cpu(copy_base + k));
            }
            for (k, tex) in gpu_fallbacks.iter().enumerate() {
                write_texture_srv(&device, tex, slot_cpu(copy_base + flat_albedo_count + k));
            }
        }

        // Resolve the pool resource a `normal_map_slot` samples for the legacy
        // per-object / per-cluster SRV pairs: a real normal map is a texture in
        // the shared pool at its own slot; `NO_NORMAL_MAP_SLOT` selects the
        // flat-normal fallback.
        let normal_resource = |slot: usize| -> &ID3D12Resource {
            if slot == NO_NORMAL_MAP_SLOT {
                &gpu_fallbacks[0]
            } else {
                &gpu_textures[slot.min(last_tex)]
            }
        };

        // The same for an albedo `texture_slot`: a real albedo is a texture at
        // its own slot; `NO_ALBEDO_SLOT` selects the white fallback, so an
        // untextured material shows its tint rather than texture 0.
        let albedo_resource = |slot: usize| -> &ID3D12Resource {
            if slot == NO_ALBEDO_SLOT {
                &gpu_fallbacks[1]
            } else {
                &gpu_textures[slot.min(last_tex)]
            }
        };

        // Per-object albedo + normal SRV pairs
        // Layout: slot object_base_slot+obj_idx*2 = albedo, +1 = normal.
        // Each object's SRVs are CreateShaderResourceView'd from the pool
        // resource selected by texture_slot / normal_map_slot, clamped to the
        // pool length so out-of-range slots fall back to the last valid entry.
        if n_objects > 0 {
            for (obj_idx, obj) in draw_objects.iter().enumerate() {
                let albedo_slot_idx = object_base_slot + obj_idx * 2;
                let normal_slot_idx = albedo_slot_idx + 1;
                write_texture_srv(
                    &device,
                    albedo_resource(obj.texture_slot),
                    slot_cpu(albedo_slot_idx),
                );
                write_texture_srv(
                    &device,
                    normal_resource(obj.normal_map_slot),
                    slot_cpu(normal_slot_idx),
                );
            }
        }

        // Per-cluster albedo + normal SRV pairs
        // Layout: slot (object_base_slot + n_objects*2 + cluster_idx*2) = albedo, +1 = normal.
        if n_clusters > 0 {
            let cluster_base_slot = object_base_slot + n_objects * 2;
            for (cluster_idx, cluster) in instanced_clusters.iter().enumerate() {
                let albedo_slot_idx = cluster_base_slot + cluster_idx * 2;
                let normal_slot_idx = albedo_slot_idx + 1;
                write_texture_srv(
                    &device,
                    albedo_resource(cluster.texture_slot),
                    slot_cpu(albedo_slot_idx),
                );
                write_texture_srv(
                    &device,
                    normal_resource(cluster.normal_map_slot),
                    slot_cpu(normal_slot_idx),
                );
            }
        }

        // Text atlas textures
        let atlas_base_slot = object_base_slot + n_objects * 2 + n_clusters * 2;
        let mut gpu_text_atlases: Vec<GpuResource> = Vec::new();
        let mut text_atlas_srv_gpus: Vec<D3D12_GPU_DESCRIPTOR_HANDLE> = Vec::new();
        for (i, (w, h, px)) in text_atlases.iter().enumerate() {
            let s = atlas_base_slot + i;
            let res = upload_texture(&alloc, *w, *h, px, slot_cpu(s), slot_gpu(s))
                .map_err(|e| format!("text_atlas[{i}]: {e}"))?;
            text_atlas_srv_gpus.push(slot_gpu(s));
            gpu_text_atlases.push(res);
        }

        // Main depth buffer. Allowed as SRV so the projected-decal pass can
        // sample it to reconstruct world positions; runtime `add_decal`
        // needs this even when no decals were declared at init.
        let depth_resource = create_main_depth_texture(
            &device,
            render_w,
            render_h,
            main_dsv_cpu,
            msaa_samples,
            true,
        )?;

        // Off-screen HDR scene target
        // The main + instanced passes render linear-light HDR into this; the
        // composite pass tonemaps it onto the swapchain. RTV heap slot [FRAMES]
        // (after the back-buffer RTVs) holds its render-target view.
        let hdr_color_rtv = D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr + FRAMES * rtv_descriptor_size,
        };
        let hdr_color = create_hdr_color_target(
            &device,
            render_w,
            render_h,
            msaa_samples,
            hdr_color_rtv,
            clear_color,
        )?;
        // The sample count is a hardware query with no authored knob, and it
        // decides which of two shapes the frame has: with MSAA the main pass
        // resolves `hdr_color` into a separate single-sample spine (and the
        // render graph carries both as resources), without it `hdr_color` is the
        // spine and there is no resolve step at all. Log it so a verification
        // run can say which shape it exercised.
        tracing::info!("d3d12 HDR target: {msaa_samples}x MSAA");
        let hdr_resolve = if msaa_samples > 1 {
            Some(create_hdr_resolve_target(&device, render_w, render_h)?)
        } else {
            None
        };
        // RTV for `hdr_resolve`: the projected-decal pass renders into the
        // resolved scene target, so it needs a render-target view. Sits in
        // the RTV heap right after the SSR RTVs. Only created when MSAA is
        // on (MSAA off uses the existing `hdr_color_rtv`).
        let hdr_resolve_rtv = if let Some(resolve) = &hdr_resolve {
            let rtv_handle = D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: rtv_base.ptr
                    + (FRAMES
                        + 1
                        + bloom_count
                        + taa_rtv_extra
                        + ssao_rtv_extra
                        + ssr_rtv_extra
                        + ssgi_rtv_extra)
                        * rtv_descriptor_size,
            };
            // SAFETY: the view descriptor and the resource it names are live for the call, and the
            // destination handle addresses a slot this context reserved for the view in a heap it
            // owns.
            unsafe {
                let rtv_desc = D3D12_RENDER_TARGET_VIEW_DESC {
                    Format: crate::directx::texture::HDR_FORMAT,
                    ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D,
                    ..Default::default()
                };
                device.CreateRenderTargetView(resolve, Some(&rtv_desc), rtv_handle);
            }
            Some(rtv_handle)
        } else {
            None
        };
        // The composite pass samples the resolved target (MSAA on) or the
        // directly-rendered HDR target (MSAA off).
        write_hdr_srv(
            &device,
            hdr_resolve.as_ref().unwrap_or(&hdr_color),
            slot_cpu(hdr_srv_slot),
        );
        let hdr_srv_gpu = slot_gpu(hdr_srv_slot);

        // Main-depth SRV, shared by every depth-sampling decoration pass (decal,
        // glass, lines) at their own t0. The DSV-only flag was dropped above so
        // this is valid.
        crate::directx::decal::write_main_depth_srv(
            &device,
            &depth_resource,
            slot_cpu(decal_depth_srv_slot),
            msaa_samples,
        );
        let decal_depth_srv_gpu = slot_gpu(decal_depth_srv_slot);

        // Colour-grading LUT
        // Upload the declared `ColorLut` payload, or build a 2×2×2 identity LUT
        // so the composite pass always binds a valid Texture3D. With the
        // identity LUT the grade is a no-op at any `lut_strength`.
        let color_lut = if let Some(bytes) = color_lut_bytes {
            let (size, data) = crate::build::color_lut::deserialise(bytes)
                .map_err(|e| format!("ColorLut payload malformed: {e}"))?;
            upload_color_lut(
                &alloc,
                size,
                data,
                slot_cpu(lut_srv_slot),
                slot_gpu(lut_srv_slot),
            )?
        } else {
            create_fallback_color_lut(&alloc, slot_cpu(lut_srv_slot), slot_gpu(lut_srv_slot))?
        };

        // Geometry buffers
        let vert_bytes_raw = bytemuck::cast_slice(vertices);
        let idx_bytes_raw = bytemuck::cast_slice(indices);
        let vertex_buffer = upload_buffer(
            &alloc,
            vert_bytes_raw,
            D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,
        )?;
        let index_buffer = upload_buffer(&alloc, idx_bytes_raw, D3D12_RESOURCE_STATE_INDEX_BUFFER)?;

        let vertex_buffer_view = D3D12_VERTEX_BUFFER_VIEW {
            BufferLocation: com::gpu_va(&vertex_buffer),
            SizeInBytes: vert_bytes_raw.len().max(4) as u32,
            StrideInBytes: std::mem::size_of::<Vertex>() as u32,
        };
        let index_buffer_view = D3D12_INDEX_BUFFER_VIEW {
            BufferLocation: com::gpu_va(&index_buffer),
            SizeInBytes: idx_bytes_raw.len().max(4) as u32,
            // Static IB is u32: the `indices: &[u32]` signature is honoured
            // end-to-end. A previous half-completed migration left this as
            // R16_UINT while the byte count was already widened: the GPU then
            // read each u32 index as a pair of u16s, indexing into garbage
            // vertices and shearing every static prop's geometry.
            Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT,
        };

        // Constant buffers
        let view_ubo_size = align256(std::mem::size_of::<ViewUniforms>() as u64);
        let light_ubo_size = align256(std::mem::size_of::<LightUniforms>() as u64);
        let shadow_ubo_size = align256(std::mem::size_of::<ShadowUniforms>() as u64);

        let mut view_ubo_resources = Vec::with_capacity(FRAMES);
        let mut view_ubo_ptrs: Vec<*mut u8> = Vec::with_capacity(FRAMES);
        for _ in 0..FRAMES {
            let buf = create_buffer(
                &alloc,
                view_ubo_size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            let mut ptr = std::ptr::null_mut::<std::ffi::c_void>();
            // SAFETY: the resource is a live CPU-visible buffer, and the out-parameter is a live
            // local that receives the mapping.
            unsafe { buf.Map(0, None, Some(&mut ptr)) }
                .map_err(|e| format!("map view ubo: {e}"))?;
            view_ubo_ptrs.push(ptr as *mut u8);
            view_ubo_resources.push(buf);
        }

        let light_ubo = create_buffer(
            &alloc,
            light_ubo_size,
            D3D12_HEAP_TYPE_UPLOAD,
            D3D12_RESOURCE_STATE_GENERIC_READ,
        )?;

        // Triple-buffer the shadow UBO since cascade VPs are recomputed each
        // frame from the camera. Persistently mapped.
        let mut shadow_ubo_resources = Vec::with_capacity(FRAMES);
        let mut shadow_ubo_ptrs: Vec<*mut u8> = Vec::with_capacity(FRAMES);
        for _ in 0..FRAMES {
            let buf = create_buffer(
                &alloc,
                shadow_ubo_size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            let mut ptr = std::ptr::null_mut::<std::ffi::c_void>();
            // SAFETY: the resource is a live CPU-visible buffer, and the out-parameter is a live
            // local that receives the mapping.
            unsafe { buf.Map(0, None, Some(&mut ptr)) }
                .map_err(|e| format!("map shadow ubo: {e}"))?;
            shadow_ubo_ptrs.push(ptr as *mut u8);
            shadow_ubo_resources.push(buf);
        }

        let shadow_uniforms = crate::gfx::csm::empty_shadow_uniforms();
        // Seed every frame's shadow UBO with the empty uniforms; per-frame
        // compute_shadow_uniforms in record_frame overwrites them.
        for ptr in &shadow_ubo_ptrs {
            // SAFETY: the mapping covers an UPLOAD-heap buffer created to hold this payload, and
            // the source is a separate allocation, so the ranges cannot overlap.
            unsafe {
                std::ptr::copy_nonoverlapping(
                    &shadow_uniforms as *const ShadowUniforms as *const u8,
                    *ptr,
                    std::mem::size_of::<ShadowUniforms>(),
                );
            }
        }
        upload_light_uniforms(&light_ubo, &light_uniforms)?;

        // Per-scene local-light storage buffer: a single UPLOAD resource filled
        // once from `local_lights` and never rewritten per frame (mirrors the
        // `light_ubo` single-upload path, not the per-frame object buffer). An
        // empty scene still allocates a one-element placeholder; the shader's
        // `num_local_lights == 0` guard keeps it from being read.
        let local_light_buffer = {
            use crate::gfx::render_types::GpuLight;
            let size =
                align256((local_lights.len().max(1) * std::mem::size_of::<GpuLight>()) as u64);
            let buf = create_buffer(
                &alloc,
                size,
                D3D12_HEAP_TYPE_UPLOAD,
                D3D12_RESOURCE_STATE_GENERIC_READ,
            )?;
            if !local_lights.is_empty() {
                upload_static_records(&buf, &local_lights, "local-light")?;
            }
            buf
        };

        // Clustered light binning. The per-cluster list + `ClusterParams` buffers
        // are always allocated (the forward shaders reference them
        // 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 = {
            use super::light_cull as lc;
            let cluster_buffer = lc::build_cluster_light_buffer(&device)?;
            let (params_resources, params_ptrs) = lc::build_cluster_params_buffers(&alloc, FRAMES)?;
            let (root_sig, pso) = if local_lights.is_empty() {
                (None, None)
            } else {
                let cs = lc::compile_light_cull_shader(hot_reload)?;
                let rs = dump_on_err(
                    info_queue.as_ref(),
                    lc::create_light_cull_root_signature(&device),
                )?;
                let pso = dump_on_err(
                    info_queue.as_ref(),
                    lc::create_light_cull_pso(&device, &rs, &cs),
                )?;
                (Some(rs), Some(pso))
            };
            lc::LightCullState {
                root_sig,
                pso,
                cluster_buffer,
                params_resources,
                params_ptrs,
            }
        };

        // Shaders + root sigs + PSOs (main / shadow / instanced / text /
        // composite + bindless static main + GPU-cull compute). See
        // init/pipelines.rs.
        let need_instanced = !instanced_clusters.is_empty();
        // Total instances across all clusters, folded into the GPU-driven bindless
        // pass as `GpuObjectData` records after the `n_objects` static objects.
        let n_instances: usize = instanced_clusters.iter().map(|c| c.instances.len()).sum();
        let shaders = pipelines::compile_all_shaders(
            vert_bytes,
            frag_bytes,
            shadow_bytes,
            vert_instanced_bytes,
            need_instanced,
            hot_reload,
        )?;

        let main_pipelines = pipelines::build_main_pipelines(
            &alloc,
            info_queue.as_ref(),
            pipelines::MainPipelineShaders {
                shaders: &shaders,
                vert_bytes,
                frag_bytes,
                bucket_shaders: world_shaders.get(1..).unwrap_or(&[]),
            },
            pipelines::MainPipelineConfig {
                n_objects,
                n_instances,
                n_skinned,
                n_chunk_max,
                msaa_samples,
            },
            pipelines::MainPipelineFeatures {
                occlusion_two_pass,
                shadow_enabled: effective_shadow_size > 0,
                gbuffer_enabled,
                hot_reload,
            },
        )?;
        let pipelines::MainPipelines {
            main_root_sig,
            main_pso,
            main_bindless_root_sig,
            main_bindless_pso,
            world_pipelines,
            bucket_stride,
            bindless_main_shaders,
            object_buffer_resources,
            object_buffer_ptrs,
            cull_root_sig,
            cull_pso,
            cull_pso_phase2,
            cull_command_signature,
            draw_args_buffer_resources,
            draw_args_buffer_ptrs,
            indirect_cmd_buffers,
            cull_status_buffers,
            indirect_cmd_buffers_2,
            shadow_bindless_root_sig,
            shadow_bindless_pso,
            shadow_bindless_cmd_sig,
            cull_pso_shadow,
            shadow_indirect_buffers,
            shadow_cull_status_buffers,
            gbuffer_bindless_root_sig,
            gbuffer_bindless_pso,
            gbuffer_bindless_cmd_sig,
            prev_model_buffer_resources,
            prev_model_buffer_ptrs,
        } = main_pipelines;

        // 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.
        if n_instances > 0 && !object_buffer_ptrs.is_empty() {
            use crate::gfx::render_types::{
                GpuDrawArgs, GpuObjectData, draw_args_flags, instance_object_records,
            };
            let records = instance_object_records(&instanced_clusters, flat_albedo_count as u32);
            // Cluster base index range (cluster indices are absolute, 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 obj_stride = std::mem::size_of::<GpuObjectData>();
            let da_stride = std::mem::size_of::<GpuDrawArgs>();
            for (obj_ptr, da_ptr) in object_buffer_ptrs.iter().zip(draw_args_buffer_ptrs.iter()) {
                // SAFETY: the buffers were sized for `n_objects + n_instances`
                // records, so writing `records.len()` past the `n_objects` offset
                // stays in bounds.
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        records.as_ptr() as *const u8,
                        obj_ptr.add(n_objects * obj_stride),
                        records.len() * obj_stride,
                    );
                    std::ptr::copy_nonoverlapping(
                        draw_args.as_ptr() as *const u8,
                        da_ptr.add(n_objects * da_stride),
                        draw_args.len() * da_stride,
                    );
                }
            }

            // GPU-driven G-buffer velocity: the instance region of the parallel
            // `prev_model` buffer is the instances' current models (immutable, so
            // motion is camera-only). Written once into every frame buffer after
            // the static prefix, exactly like the instance object records; the
            // per-frame `build_gbuffer_prev_models` fill writes only the static +
            // skinned regions, leaving this intact. A no-op when the G-buffer path
            // is inactive (the buffers were not allocated).
            if !prev_model_buffer_ptrs.is_empty() {
                let models: Vec<[[f32; 4]; 4]> = records.iter().map(|r| r.model).collect();
                let m_stride = std::mem::size_of::<[[f32; 4]; 4]>();
                for pm_ptr in prev_model_buffer_ptrs.iter() {
                    // SAFETY: the prev_model buffer was sized for
                    // `n_objects + n_instances + n_skinned` records, so writing
                    // `models.len()` past the `n_objects` offset stays in bounds.
                    unsafe {
                        std::ptr::copy_nonoverlapping(
                            models.as_ptr() as *const u8,
                            pm_ptr.add(n_objects * m_stride),
                            models.len() * m_stride,
                        );
                    }
                }
            }
        }

        // The bindless texture pool's base, one table handle per frame-in-flight
        // copy; pool index `texture_slot` lands on the albedo SRV and
        // `albedo_count + normal_slot` on the normal SRV. The bindless main pass
        // and the RT hit shader bind the recording frame's copy.
        let bindless_pool_gpu: Vec<D3D12_GPU_DESCRIPTOR_HANDLE> = (0..FRAMES)
            .map(|f| slot_gpu(flat_pool_base_slot + f * flat_pool_len))
            .collect();

        // Only build the shadow PSO when shadows are enabled; the shadow pass
        // keys off `shadow_pso.is_some()`, so passing `None` when
        // `effective_shadow_size == 0` keeps a shadow-disabled world from
        // rendering into nonexistent cascade DSVs.
        let shadow_vs_for_pso = if effective_shadow_size > 0 {
            shaders.shadow_vs.as_deref()
        } else {
            None
        };
        let (shadow_root_sig, shadow_pso) =
            pipelines::build_shadow_pipeline(&device, info_queue.as_ref(), shadow_vs_for_pso)?;

        let (main_instanced_root_sig, main_instanced_pso) =
            pipelines::build_main_instanced_pipeline(
                &device,
                info_queue.as_ref(),
                shaders.main_vs_instanced.as_deref(),
                &shaders.main_ps,
                msaa_samples,
            )?;

        let (text_root_sig, text_pso) = pipelines::build_text_pipeline(
            &device,
            info_queue.as_ref(),
            &shaders.text_vs,
            &shaders.text_ps,
            swapchain_format,
            !text_atlases.is_empty(),
        )?;

        let (composite_root_sig, composite_pso) = pipelines::build_composite_pipeline(
            &device,
            info_queue.as_ref(),
            swapchain_format,
            hot_reload,
        )?;

        // Bloom mips + bloom PSOs + TAA + SSAO. See init/effects.rs.
        let bloom_rtv_for = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr + (FRAMES + 1 + i) * rtv_descriptor_size,
        };
        let bloom_srv_cpu_for = |i: usize| slot_cpu(bloom_srv_base_slot + i);
        let bloom_srv_gpu_for = |i: usize| slot_gpu(bloom_srv_base_slot + i);

        let taa_rtv_for = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr + (FRAMES + 1 + bloom_count + i) * rtv_descriptor_size,
        };
        let taa_slots = effects::TaaSlots {
            history_rtv: [taa_rtv_for(0), taa_rtv_for(1)],
            history_srv: [
                (slot_cpu(taa_srv_base_slot), slot_gpu(taa_srv_base_slot)),
                (
                    slot_cpu(taa_srv_base_slot + 1),
                    slot_gpu(taa_srv_base_slot + 1),
                ),
            ],
        };

        let ssr_rtv_for = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr
                + (FRAMES + 1 + bloom_count + taa_rtv_extra + ssao_rtv_extra + i)
                    * rtv_descriptor_size,
        };
        let ssr_slots = effects::SsrSlots {
            output_rtv: ssr_rtv_for(0),
            output_srv: (slot_cpu(ssr_srv_base_slot), slot_gpu(ssr_srv_base_slot)),
        };

        // SSGI gather target: RTV right after the SSR RTVs, SRV at the heap tail.
        let ssgi_gi_rtv = D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr
                + (FRAMES + 1 + bloom_count + taa_rtv_extra + ssao_rtv_extra + ssr_rtv_extra)
                    * rtv_descriptor_size,
        };
        let ssgi_slots = effects::SsgiSlots {
            gi_rtv: ssgi_gi_rtv,
            gi_srv: (slot_cpu(ssgi_gi_srv_slot), slot_gpu(ssgi_gi_srv_slot)),
        };

        let ssao_rtv_for = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr
                + (FRAMES + 1 + bloom_count + taa_rtv_extra + i) * rtv_descriptor_size,
        };
        let ssao_slots = effects::SsaoSlots {
            ao_raw_rtv: ssao_rtv_for(0),
            ao_raw_srv: (slot_cpu(ssao_srv_base_slot), slot_gpu(ssao_srv_base_slot)),
            ao_rtv: ssao_rtv_for(1),
            ao_srv: (
                slot_cpu(ssao_srv_base_slot + 1),
                slot_gpu(ssao_srv_base_slot + 1),
            ),
            white_srv: (slot_cpu(ssao_white_srv_slot), slot_gpu(ssao_white_srv_slot)),
        };

        // RT-reflection output target: RTV right after the gbuffer RTVs (the
        // last RTV block), SRV at the SRV-heap tail.
        let rt_output_rtv = D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr
                + (FRAMES
                    + 1
                    + bloom_count
                    + taa_rtv_extra
                    + ssao_rtv_extra
                    + ssr_rtv_extra
                    + ssgi_rtv_extra
                    + decal_rtv_extra
                    + gbuffer_rtv_extra)
                    * rtv_descriptor_size,
        };
        let rt_slots = effects::RtReflectionsSlots {
            output_rtv: rt_output_rtv,
            output_srv: (slot_cpu(rt_output_srv_slot), slot_gpu(rt_output_srv_slot)),
        };

        // Reflection composite: 2 RTVs at the very tail (after the RT RTV) + 2 SRVs
        // at the SRV-heap tail. `output` is the scene-with-reflections the post stack
        // consumes; `blur` is the reduced-res roughness blur. Built when SSR resolve
        // or RT is authored (both feed the same composite); the slots stay reserved
        // either way for a live reflection enable.
        let refl_composite_rtv_base = FRAMES
            + 1
            + bloom_count
            + taa_rtv_extra
            + ssao_rtv_extra
            + ssr_rtv_extra
            + ssgi_rtv_extra
            + decal_rtv_extra
            + gbuffer_rtv_extra
            + rt_rtv_extra;
        let refl_composite_rtv = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr + (refl_composite_rtv_base + i) * rtv_descriptor_size,
        };
        let refl_composite_slots =
            crate::directx::post::reflection_composite::ReflectionCompositeSlots {
                output_rtv: refl_composite_rtv(0),
                output_srv: (
                    slot_cpu(refl_composite_srv_base_slot),
                    slot_gpu(refl_composite_srv_base_slot),
                ),
                blur_rtv: refl_composite_rtv(1),
                blur_srv: (
                    slot_cpu(refl_composite_srv_base_slot + 1),
                    slot_gpu(refl_composite_srv_base_slot + 1),
                ),
            };
        let reflection_composite = if ssr_settings.is_some() || rt_reflection_settings.is_some() {
            Some(
                crate::directx::post::reflection_composite::ReflectionCompositeResources::new(
                    &device,
                    render_w,
                    render_h,
                    reflection_blur_scale,
                    refl_composite_slots,
                    info_queue.as_ref(),
                    hot_reload,
                )?,
            )
        } else {
            None
        };

        // Unified G-buffer pre-pass descriptor slots (always reserved). Minted
        // here so both the conditional init build below and the runtime
        // `apply_quality_settings` rebuild use the same fixed slots.
        let gb_rtv_base = FRAMES
            + 1
            + bloom_count
            + taa_rtv_extra
            + ssao_rtv_extra
            + ssr_rtv_extra
            + ssgi_rtv_extra
            + decal_rtv_extra;
        let gb_rtv = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr + (gb_rtv_base + i) * rtv_descriptor_size,
        };
        let gbuffer_slots = crate::directx::post::gbuffer::GbufferSlots {
            normal_depth_rtv: gb_rtv(0),
            normal_depth_srv: (
                slot_cpu(gbuffer_srv_base_slot),
                slot_gpu(gbuffer_srv_base_slot),
            ),
            roughness_rtv: gb_rtv(1),
            roughness_srv: (
                slot_cpu(gbuffer_srv_base_slot + 1),
                slot_gpu(gbuffer_srv_base_slot + 1),
            ),
            velocity_rtv: gb_rtv(2),
            velocity_srv: (
                slot_cpu(gbuffer_srv_base_slot + 2),
                slot_gpu(gbuffer_srv_base_slot + 2),
            ),
            depth_dsv: D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: dsv_base.ptr
                    + (1 + NUM_SHADOW_CASCADES + MAX_SHADOWED_SPOTS) * dsv_descriptor_size,
            },
        };

        // Stash the live-toggleable effects' fixed slots so the runtime
        // `apply_quality_settings` can build a launched-off feature into its slot
        // without re-deriving the heap layout. Copied from the per-effect slot
        // structs before they move into `build_effects` below.
        let quality_slots = super::quality::QualitySlotHandles {
            taa_history_rtv: taa_slots.history_rtv,
            taa_history_srv: taa_slots.history_srv,
            ssao_ao_raw_rtv: ssao_slots.ao_raw_rtv,
            ssao_ao_raw_srv: ssao_slots.ao_raw_srv,
            ssao_ao_rtv: ssao_slots.ao_rtv,
            ssao_ao_srv: ssao_slots.ao_srv,
            ssr_output_rtv: ssr_slots.output_rtv,
            ssr_output_srv: ssr_slots.output_srv,
            ssgi_gi_rtv: ssgi_slots.gi_rtv,
            ssgi_gi_srv: ssgi_slots.gi_srv,
            rt_output_rtv: rt_slots.output_rtv,
            rt_output_srv: rt_slots.output_srv,
            refl_composite: refl_composite_slots,
            gbuffer: gbuffer_slots,
        };

        let effects_bundle = effects::build_effects(
            &alloc,
            info_queue.as_ref(),
            effects::EffectDimensions {
                width,
                height,
                render_width: render_w,
                render_height: render_h,
            },
            effects::EffectSettings {
                ssao_settings,
                ssr_settings,
                ssgi_settings,
                rt_reflection_settings,
                rt_supported: raytracing_supported,
            },
            effects::EffectFlags {
                taa_enabled,
                gbuffer_enabled,
                hot_reload,
            },
            effects::EffectDescriptorSlots {
                bloom: effects::BloomSlots {
                    rtv_for: &bloom_rtv_for,
                    srv_cpu_for: &bloom_srv_cpu_for,
                    srv_gpu_for: &bloom_srv_gpu_for,
                },
                taa: taa_slots,
                ssao: ssao_slots,
                ssr: ssr_slots,
                ssgi: ssgi_slots,
                rt: rt_slots,
            },
        )?;
        let effects::EffectsBundle {
            transient_pool,
            bloom_mips,
            bloom_mip_rtvs,
            bloom_mip_srv_gpus,
            bloom_mip_extents,
            bloom_root_sig,
            bloom_pso_prefilter,
            bloom_pso_downsample,
            bloom_pso_upsample,
            taa,
            ssao,
            ssao_white,
            ssao_white_srv_gpu,
            ssr,
            ssgi,
            rt_reflections,
        } = effects_bundle;

        // Unified G-buffer pre-pass resources. Built whenever any screen-space
        // consumer drives it (see `gbuffer_enabled`). Its three MRT RTVs sit at
        // the tail of the RTV heap (after the decal RTV), its private depth DSV
        // right after the shadow DSVs, and its three SRVs in the reserved
        // `gbuffer_srv_base_slot` block. The skinned PSO builds lazily in
        // `upload_skinned` once the joint-bound vertex layout exists.
        let gbuffer = if gbuffer_enabled {
            // The three colour targets are pooled, so the pool (built in
            // `build_effects`, before this) is what owns them.
            let pooled = transient_pool
                .gbuffer_pooled()
                .ok_or("transient pool missing the gbuffer colour targets")?;
            Some(crate::directx::post::gbuffer::GbufferResources::new(
                crate::directx::post::gbuffer::GbufferDeviceCtx {
                    alloc: &alloc,
                    info_queue: info_queue.as_ref(),
                },
                crate::directx::post::gbuffer::GbufferExtent {
                    width: render_w,
                    height: render_h,
                    need_instanced,
                    need_skinned: false,
                    hot_reload,
                },
                gbuffer_slots,
                &pooled,
            )?)
        } else {
            None
        };

        // Projected decals: pipeline + unit-cube buffers + per-frame
        // uniform rings. Always built so runtime `add_decal` works from a
        // world that started with none; pre-authored decals get their albedo
        // SRV written below.
        let decals_state = Some(crate::directx::decal::DecalResources::new(
            &alloc,
            msaa_samples,
            decal_srv_base_slot,
            decal_depth_srv_gpu,
            info_queue.as_ref(),
            hot_reload,
        )?);
        // Pre-authored decals: write each one's albedo SRV into its reserved
        // heap slot. Runtime adds via `DxContext::add_decal` follow the same
        // pattern.
        if decals.len() > crate::directx::decal::MAX_DECALS {
            return Err(format!(
                "decals: {} authored decals exceed MAX_DECALS ({})",
                decals.len(),
                crate::directx::decal::MAX_DECALS
            ));
        }
        let last_tex = gpu_textures.len().saturating_sub(1);
        for (i, rec) in decals.iter().enumerate() {
            let tex_idx = rec.texture_slot.min(last_tex);
            write_texture_srv(
                &device,
                &gpu_textures[tex_idx],
                slot_cpu(decal_srv_base_slot + i),
            );
        }
        let decals_init: Vec<Option<crate::gfx::decal::DecalRecord>> =
            decals.into_iter().map(Some).collect();

        // Volumetric fog: pipeline + per-frame uniform ring. Built only when
        // the world declared a `VolumetricFog`; the encoder simply skips the
        // pass when `fog_settings` is `None`. The fog pass shares the main-
        // depth SRV that the decal-init path already wrote into the heap.
        let fog_resources = if fog_settings.is_some() {
            Some(crate::directx::fog::FogResources::new(
                &alloc,
                crate::directx::fog::FogVolumeDescriptors {
                    uav_cpu: slot_cpu(fog_froxel_uav_slot),
                    uav_gpu: slot_gpu(fog_froxel_uav_slot),
                    srv_cpu: slot_cpu(fog_froxel_srv_slot),
                    srv_gpu: slot_gpu(fog_froxel_srv_slot),
                },
                crate::directx::fog::FogShaderResourceHandles {
                    depth_srv_gpu: decal_depth_srv_gpu,
                    shadow_srv_gpu,
                },
                crate::directx::fog::FogDeviceParams {
                    msaa_samples,
                    hot_reload,
                },
                info_queue.as_ref(),
            )?)
        } else {
            None
        };

        // (The FSR3 temporal upscaler is built earlier; its resolved render
        // dimensions decide the scene-target sizes used above.)

        // Particles: compute + render pipelines + per-frame uniform rings,
        // plus one persistent GPU pool per emitter. Built only when the world
        // declared ≥1 emitter; the encoder skips the passes when
        // `particle_resources` is `None`, and runtime `add_emitter` builds the
        // pipelines lazily the same way. The emitter cap matches the SRV-heap
        // reservation made above.
        if particles.len() > crate::directx::particle::MAX_EMITTERS {
            return Err(format!(
                "particles: {} authored emitters exceed MAX_EMITTERS ({})",
                particles.len(),
                crate::directx::particle::MAX_EMITTERS
            ));
        }
        let (particle_resources, particle_records, particle_emitter_states) =
            if !particles.is_empty() {
                let resources = crate::directx::particle::ParticleResources::new(
                    &alloc,
                    particle_srv_base_slot,
                    info_queue.as_ref(),
                    hot_reload,
                )?;
                let mut states: Vec<Option<crate::directx::particle::ParticleEmitterGpuState>> =
                    Vec::with_capacity(particles.len());
                let last_tex = gpu_textures.len().saturating_sub(1);
                for (i, rec) in particles.iter().enumerate() {
                    let state = crate::directx::particle::build_emitter_gpu_state(&alloc, rec)?;
                    states.push(Some(state));
                    // Write the per-emitter albedo SRV into its reserved heap slot.
                    let tex_idx = rec.texture_slot.min(last_tex);
                    write_texture_srv(
                        &device,
                        &gpu_textures[tex_idx],
                        slot_cpu(particle_srv_base_slot + i),
                    );
                }
                let recs: Vec<Option<crate::gfx::particles::ParticleEmitterRecord>> =
                    particles.into_iter().map(Some).collect();
                (Some(resources), recs, states)
            } else {
                (None, Vec::new(), Vec::new())
            };

        // Per-frame command infrastructure
        let mut command_allocators = Vec::with_capacity(FRAMES);
        let mut command_lists: Vec<ID3D12GraphicsCommandList> = Vec::with_capacity(FRAMES);
        for _ in 0..FRAMES {
            let alloc: ID3D12CommandAllocator =
                // SAFETY: the create descriptor and every pointer it borrows are live for the call,
                // and the new COM object lands in a binding that owns it.
                unsafe { device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) }
                    .map_err(|e| format!("command allocator: {e}"))?;
            // SAFETY: the create descriptor and every pointer it borrows are live for the call, and
            // the new COM object lands in a binding that owns it.
            let list: ID3D12GraphicsCommandList = unsafe {
                device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)
            }
            .map_err(|e| format!("command list: {e}"))?;
            // Close immediately; we re-open each frame.
            // SAFETY: the command list is live and in the recording state, which is what `Close`
            // requires.
            unsafe { list.Close() }.map_err(|e| format!("close cmd list: {e}"))?;
            command_allocators.push(alloc);
            command_lists.push(list);
        }

        // Per-pass command allocator + cmd list pool for the parallel-
        // encoding path. Sized FRAMES * PASS_COUNT so each pass owns its
        // own allocator + cmd list per in-flight slot; workers reset
        // their own allocator + cmd list before recording, so multiple
        // workers can encode in parallel without contending. Allocators
        // are very lightweight (a few KB of CPU-side bookkeeping each);
        // a 21-pass × 3-frame pool is ~63 entries.
        let pass_pool_size = FRAMES * crate::gfx::render_graph::PASS_COUNT;
        let mut pass_allocators: Vec<ID3D12CommandAllocator> = Vec::with_capacity(pass_pool_size);
        let mut pass_cmd_lists: Vec<ID3D12GraphicsCommandList> = Vec::with_capacity(pass_pool_size);
        for _ in 0..pass_pool_size {
            let alloc: ID3D12CommandAllocator =
                // SAFETY: the create descriptor and every pointer it borrows are live for the call,
                // and the new COM object lands in a binding that owns it.
                unsafe { device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) }
                    .map_err(|e| format!("per-pass command allocator: {e}"))?;
            // SAFETY: the create descriptor and every pointer it borrows are live for the call, and
            // the new COM object lands in a binding that owns it.
            let list: ID3D12GraphicsCommandList = unsafe {
                device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)
            }
            .map_err(|e| format!("per-pass command list: {e}"))?;
            // Close immediately; we re-open per-pass each frame as needed.
            // SAFETY: the command list is live and in the recording state, which is what `Close`
            // requires.
            unsafe { list.Close() }.map_err(|e| format!("close per-pass cmd list: {e}"))?;
            pass_allocators.push(alloc);
            pass_cmd_lists.push(list);
        }

        // End-of-frame outer cmd list pair (composite + final timestamp +
        // resolve). Submitted last so its `ResolveQueryData` reads every
        // per-pass `EndQuery` write.
        let mut end_command_allocators: Vec<ID3D12CommandAllocator> = Vec::with_capacity(FRAMES);
        let mut end_command_lists: Vec<ID3D12GraphicsCommandList> = Vec::with_capacity(FRAMES);
        for _ in 0..FRAMES {
            let alloc: ID3D12CommandAllocator =
                // SAFETY: the create descriptor and every pointer it borrows are live for the call,
                // and the new COM object lands in a binding that owns it.
                unsafe { device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) }
                    .map_err(|e| format!("end command allocator: {e}"))?;
            // SAFETY: the create descriptor and every pointer it borrows are live for the call, and
            // the new COM object lands in a binding that owns it.
            let list: ID3D12GraphicsCommandList = unsafe {
                device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)
            }
            .map_err(|e| format!("end command list: {e}"))?;
            // SAFETY: the command list is live and in the recording state, which is what `Close`
            // requires.
            unsafe { list.Close() }.map_err(|e| format!("close end cmd list: {e}"))?;
            end_command_allocators.push(alloc);
            end_command_lists.push(list);
        }

        // SAFETY: the create descriptor and every pointer it borrows are live for the call, and the
        // new COM object lands in a binding that owns it.
        let fence: ID3D12Fence = unsafe { device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }
            .map_err(|e| format!("create fence: {e}"))?;
        // SAFETY: an auto-reset, initially unsignalled event with no name and no security
        // attributes; the call borrows nothing.
        let fence_event = unsafe { CreateEventW(None, false, false, None) }
            .map_err(|e| format!("create fence event: {e}"))?;
        let fence_values = vec![0u64; FRAMES];

        // Timestamp infrastructure for the per-frame GPU time chip. Falls back
        // to `None`s with frequency 0 when the queue does not support
        // timestamps (every WDDM 2.0+ direct queue does, but the fallback keeps
        // the rest of the overlay working on adapters that don't).
        let (timestamp_query_heap, timestamp_readback, timestamp_readback_ptr, timestamp_frequency) =
            crate::directx::context::build_timestamp_resources(&alloc);

        // Shader hot-reload wiring. The atomic flag is shared between the
        // notify watcher thread and `draw_frame`, plus the debug WS
        // `reload-shaders` command path via `GraphicsSystem`. Watcher
        // creation is best-effort: a missing source dir or a notify error
        // logs a warning and disables only the watcher half -- the debug
        // command still works on the same flag.
        let (shader_reload_pending, shader_watcher) = if hot_reload {
            let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let watcher = crate::directx::hot_reload::spawn(std::sync::Arc::clone(&flag));
            (Some(flag), watcher)
        } else {
            (None, None)
        };

        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
        };

        // Per-frame instance upload buffers. One persistently-mapped buffer
        // per (frame, cluster). Sized to hold cluster.instances.len() float4x4
        // matrices, which is fixed at init time.
        let mut instance_upload_buffers: Vec<Vec<PooledBuffer>> = Vec::with_capacity(FRAMES);
        let mut instance_upload_ptrs: Vec<Vec<*mut u8>> = Vec::with_capacity(FRAMES);
        for _ in 0..FRAMES {
            let mut frame_bufs: Vec<PooledBuffer> = Vec::with_capacity(instanced_clusters.len());
            let mut frame_ptrs: Vec<*mut u8> = Vec::with_capacity(instanced_clusters.len());
            for cluster in &instanced_clusters {
                let bytes =
                    (cluster.instances.len().max(1) * std::mem::size_of::<[[f32; 4]; 4]>()) as u64;
                let buf = create_buffer(
                    &alloc,
                    bytes,
                    D3D12_HEAP_TYPE_UPLOAD,
                    D3D12_RESOURCE_STATE_GENERIC_READ,
                )
                .map_err(|e| format!("instance upload buf: {e}"))?;
                let mut ptr = std::ptr::null_mut::<std::ffi::c_void>();
                // SAFETY: the resource is a live CPU-visible buffer, and the out-parameter is a
                // live local that receives the mapping.
                unsafe {
                    buf.Map(0, None, Some(&mut ptr))
                        .map_err(|e| format!("map instance buf: {e}"))?;
                }
                frame_bufs.push(buf);
                frame_ptrs.push(ptr as *mut u8);
            }
            instance_upload_buffers.push(frame_bufs);
            instance_upload_ptrs.push(frame_ptrs);
        }

        // Auto-exposure: build the histogram + average compute pipelines plus
        // the GPU buffers (histogram UAV, output UAV, per-frame readback)
        // only when the world's PostProcessConfig opted in. With auto-exposure
        // off every path 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 = dump_on_err(
                    info_queue.as_ref(),
                    crate::directx::auto_exposure::AutoExposureResources::new(&alloc, hot_reload),
                )?;
                let state = crate::gfx::auto_exposure::AutoExposureState::new(settings);
                (Some(resources), Some(state))
            } else {
                (None, None)
            };

        // Raymarched SDF volumes. Builds per-volume PSOs from `.hlsl`
        // payloads and writes the raymarch SRV + sampler tables into
        // their reserved blocks. `.metal` payloads are filtered out
        // inside `try_new` with a logged warning; if every volume is
        // Metal-first (the current showcase shape), this returns `None`
        // and the render graph never adds `PassId::Raymarch`. The
        // shadow + IBL handles passed here mirror the matching slot-0/1/2
        // bindings the main pass uses, so raymarched surfaces sample the
        // same CSM cascades + IBL cubes as rasterised geometry.
        let raymarch = crate::directx::raymarch::RaymarchResources::try_new(
            crate::directx::raymarch::RaymarchDeviceContext {
                alloc: &alloc,
                info_queue: info_queue.as_ref(),
            },
            crate::directx::raymarch::RaymarchTargetConfig {
                width: render_w,
                height: render_h,
                msaa_samples,
            },
            crate::directx::raymarch::RaymarchSharedBindings {
                shadow_resource: shadow_resource_opt.as_ref().map(|r| &r.resource),
                shadow_layers: NUM_SHADOW_CASCADES as u32,
                irradiance_resource: &env_map.irradiance.resource,
                prefilter_resource: &env_map.prefilter.resource,
            },
            crate::directx::raymarch::RaymarchDescriptorHandles {
                srv_base_cpu: slot_cpu(raymarch_srv_base_slot),
                srv_base_gpu: slot_gpu(raymarch_srv_base_slot),
                srv_descriptor_size,
                sampler_base_cpu: D3D12_CPU_DESCRIPTOR_HANDLE {
                    ptr: samp_cpu_base.ptr + raymarch_sampler_base_slot * sampler_descriptor_size,
                },
                sampler_base_gpu: D3D12_GPU_DESCRIPTOR_HANDLE {
                    ptr: samp_gpu_base.ptr
                        + (raymarch_sampler_base_slot * sampler_descriptor_size) as u64,
                },
                sampler_descriptor_size,
            },
            &sdf_volumes,
            hot_reload,
        )?;

        // Hi-Z pyramid. Built under the same condition as the cull pipeline
        // (bindless main pass active + build-time static geometry). The
        // resource owns its descriptors at the reserved Hi-Z heap slots;
        // when the gating condition fails the slots stay empty and the
        // cull kernel's `hiz_enabled` flag stays zero so it never samples
        // them. The init kernel reads the main-depth SRV that the decal +
        // fog passes already wrote; `decal_depth_srv_gpu` carries the
        // matching GPU handle.
        let hiz = if cull_pso.is_some() {
            let mut mip_uav_cpus: Vec<D3D12_CPU_DESCRIPTOR_HANDLE> =
                Vec::with_capacity(HIZ_MAX_MIPS);
            let mut mip_uav_gpus: Vec<D3D12_GPU_DESCRIPTOR_HANDLE> =
                Vec::with_capacity(HIZ_MAX_MIPS);
            for i in 0..HIZ_MAX_MIPS {
                mip_uav_cpus.push(slot_cpu(hiz_uav_base_slot + i));
                mip_uav_gpus.push(slot_gpu(hiz_uav_base_slot + i));
            }
            Some(crate::directx::hiz::HiZResources::new(
                crate::directx::hiz::HiZDeviceCtx {
                    device: &device,
                    info_queue: info_queue.as_ref(),
                    hot_reload,
                },
                crate::directx::hiz::HiZTarget {
                    width: render_w,
                    height: render_h,
                    srv_cpu: slot_cpu(hiz_srv_slot),
                    srv_gpu: slot_gpu(hiz_srv_slot),
                    depth_srv_gpu: decal_depth_srv_gpu,
                    mip_uav_cpus,
                    mip_uav_gpus,
                },
            )?)
        } else {
            None
        };

        // Planar reflections: one mirror-render resolve per distinct reflector
        // plane (the `assign_planar_slots` representatives), each SRV in a reserved
        // heap slot the transparent pass binds per record. `None` when no reflector
        // was assigned a planar slot (no transparent content, or every plane
        // degenerate / over budget).
        let planar_reflection = if planar_assignment.representatives.is_empty() {
            None
        } else {
            // Build-time draw-record count (matches `DxContext::cull_count`): sizes
            // each plane's region of the mirror-cull indirect buffer.
            let planar_n_cull = n_objects + n_instances + n_chunk_max + n_skinned;
            let resolve_srv_cpu: Vec<_> = (0..planar_assignment.representatives.len())
                .map(|i| slot_cpu(planar_resolve_srv_base_slot + i))
                .collect();
            let resolve_srv_gpu: Vec<_> = (0..planar_assignment.representatives.len())
                .map(|i| slot_gpu(planar_resolve_srv_base_slot + i))
                .collect();
            Some(crate::directx::planar::PlanarReflectionSet::new(
                &alloc,
                crate::directx::planar::PlanarConfig {
                    sample_count: msaa_samples,
                    width: render_w,
                    height: render_h,
                    n_cull: planar_n_cull,
                },
                &planar_assignment.representatives,
                crate::directx::planar::PlanarTargets {
                    resolve_srv_cpu: &resolve_srv_cpu,
                    resolve_srv_gpu: &resolve_srv_gpu,
                    clear_color,
                },
            )?)
        };

        // 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();

        // 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 a DXR-capable GPU, 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. Shares the main-depth SRV with the decal
        // pass; the scene-copy snapshot uses its own reserved heap slot.
        // `planar_assignment.slots` gives each reflector its planar resolve slot
        // (or `None` -> probe-cube fallback), numbered water first to match the
        // plane list above.
        let has_seethrough_meshes =
            !seethrough_mesh_indices.is_empty() && super::raytrace::raytracing_supported(&device);
        let transparent =
            if glass_panels.is_empty() && water_surfaces.is_empty() && !has_seethrough_meshes {
                None
            } else {
                let (water_planar_slots, glass_planar_slots) =
                    planar_assignment.slots.split_at(water_surfaces.len());
                Some(crate::directx::transparent::TransparentResources::new(
                    crate::directx::transparent::TransparentDeviceCtx { alloc: &alloc },
                    crate::directx::transparent::TransparentBuildConfig {
                        msaa_samples,
                        width: render_w,
                        height: render_h,
                        hot_reload,
                    },
                    crate::directx::transparent::TransparentSceneTargets {
                        scene_copy_srv_cpu: slot_cpu(transparent_scene_copy_srv_slot),
                        scene_copy_srv_gpu: slot_gpu(transparent_scene_copy_srv_slot),
                        depth_srv_gpu: decal_depth_srv_gpu,
                    },
                    crate::directx::transparent::TransparentContent {
                        glass_panels: &glass_panels,
                        glass_planar_slots,
                        water_surfaces: &water_surfaces,
                        water_planar_slots,
                        seethrough_mesh_indices: &seethrough_mesh_indices,
                    },
                    info_queue.as_ref(),
                )?)
            };

        // Hardware-RT acceleration structure. Built once over the shared static
        // vertex/index buffers + the draw-object / cluster lists, only when the
        // RT reflection resources came up (DXR-capable GPU + DXC compile OK).
        // `Ok(None)` means an empty scene; an `Err` is non-fatal (logged, falls
        // back to SSR). `rt_reflections_active` gates the RT pass on both this
        // and the resources being `Some`. The init build is static-only; skinned
        // meshes are seeded into the BVH on the first dynamic frame
        // (`rebuild_skinned`), so the compute-skinning pipeline is built here and
        // attached. A skin-pipeline build failure is non-fatal: the
        // RT pass still runs for static geometry, just without skinned hits.
        let rt_accel = if rt_reflections.is_some() {
            match super::raytrace::build_rt_accel(super::raytrace::RtInitGeometry {
                alloc: &alloc,
                vertex_buffer: &vertex_buffer,
                index_buffer: &index_buffer,
                draw_objects: &draw_objects,
                clusters: &instanced_clusters,
                total_vertices: vertices.len(),
                albedo_count: flat_albedo_count as u32,
                // Exclude the meshes the transparent pass will reroute. Decided
                // here rather than through `seethrough_meshes_enabled` because
                // the context does not exist yet; the two agree because both read
                // "a material opted in AND the mesh pipelines built".
                exclude_seethrough: transparent
                    .as_ref()
                    .is_some_and(|t| t.mesh_pipelines_ready()),
            }) {
                Ok(Some(mut accel)) => {
                    match super::raytrace::build_rt_skin_pipeline(&device, hot_reload) {
                        Ok(skin) => accel.set_skin_pipeline(skin),
                        Err(e) => tracing::warn!(
                            "RT skin pipeline build failed (skinned meshes absent from reflections): {e}"
                        ),
                    }
                    Some(accel)
                }
                Ok(None) => None,
                Err(e) => {
                    tracing::warn!(
                        "RT acceleration-structure build failed, falling back to SSR: {e}"
                    );
                    None
                }
            }
        } else {
            None
        };

        crate::shader_cache::report_init_and_prune();
        // Persist the pipeline library now that every init-built PSO has
        // populated it; a crash mid-session then still leaves the next launch
        // warm.
        super::pso_library::serialize();
        crate::pipeline_cache::report_init(super::pso_library::disk_state());

        let pooled = alloc.stats();
        tracing::info!(
            "device allocator: {} heap(s), {} KiB reserved for {} KiB of resources",
            pooled.block_count,
            pooled.reserved_bytes / 1024,
            pooled.in_use_bytes / 1024,
        );

        Ok(Self {
            win_state: Some(win_state),
            fullscreen_display: crate::win32::display_mode::FullscreenDisplayMode::new(),
            device,
            command_queue,
            alloc,
            swapchain_config,
            hdr_mode,
            swapchain: super::context::SwapchainState {
                handle: swapchain,
                back_buffers,
                rtv_heap,
                rtv_descriptor_size,
                format: swapchain_format,
                present_sync_interval,
                allow_tearing,
                last_present_index: None,
            },
            hdr: super::context::HdrState {
                color: hdr_color,
                color_rtv: hdr_color_rtv,
                resolve: hdr_resolve,
                resolve_rtv: hdr_resolve_rtv,
                srv_gpu: hdr_srv_gpu,
                msaa_samples,
            },
            extent: super::context::Extents {
                render_width: render_w,
                render_height: render_h,
                output_width: width,
                output_height: height,
            },
            upscale: super::context::UpscaleState {
                backend: upscaler,
                requested: upscale_backend,
                jitter: std::cell::Cell::new([0.0, 0.0]),
                prev_elapsed: std::cell::Cell::new(0.0),
            },
            depth: super::context::DepthState {
                dsv: main_dsv_cpu,
                resource: depth_resource,
                heap: dsv_heap,
            },
            shadow: super::context::ShadowState {
                resource: shadow_resource_opt,
                dsvs: shadow_dsvs,
                map_size: effective_shadow_size,
                srv_gpu: shadow_srv_gpu,
                light_dir: shadow_light_dir,
                update: shadow_update,
                distance: shadow_distance,
                cascades: shadow_cascades,
                scheduler: Default::default(),
                render_mask: 0,
                uniforms: crate::gfx::csm::empty_shadow_uniforms(),
            },
            spot_shadow: super::context::SpotShadowState {
                resource: spot_shadow_resource,
                dsvs: spot_shadow_dsvs,
                srv_gpu: slot_gpu(spot_shadow_srv_slot),
                buffer: spot_shadow_buffer,
                ubo: spot_shadow_ubo,
                ubo_stride: spot_shadow_ubo_stride,
                slice_size: spot_shadow_slice_size,
                scheduler: Default::default(),
                render_mask: 0,
            },
            area_light: super::context::AreaLightState {
                buffer: area_light_buffer,
                ltc_matrix: ltc_matrix_texture,
                ltc_magnitude: ltc_magnitude_texture,
                ltc_table_gpu: slot_gpu(ltc_srv_base_slot),
            },
            env_map,
            color_lut,
            descriptors: DxDescriptors {
                srv_heap,
                srv_descriptor_size,
                flat_pool_base_slot,
                flat_pool_len,
                probe_cube_base_slot,
                sampler_heap,
                shadow_sampler_gpu,
                linear_sampler_gpu,
                text_sampler_gpu,
                textures: gpu_textures,
                fallback_textures: gpu_fallbacks,
                text_atlas_textures: gpu_text_atlases,
                text_atlas_srv_gpus,
            },
            geometry: DxGeometry {
                vertex_buffer,
                index_buffer,
                vertex_buffer_view,
                index_buffer_view,
            },
            mesh_stream: super::context::MeshStreamState {
                vtx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                idx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
            },
            chunk_stream: super::context::ChunkStreamState {
                vtx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                idx_alloc: crate::suballoc::range_alloc::RangeAllocator::new(),
                srv_base_slot: chunk_srv_base_slot,
            },
            skinned: SkinnedState {
                pso: None,
                root_sig: None,
                shadow_pso: None,
                shadow_root_sig: None,
                vertex_buffer: None,
                index_buffer: None,
                vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW::default(),
                index_buffer_view: D3D12_INDEX_BUFFER_VIEW::default(),
                draw_objects: Vec::new(),
                joint_buffers: Vec::new(),
                joint_ptrs: Vec::new(),
                joint_matrices: Vec::new(),
                srv_base_slot: skinned_srv_base_slot,
                skin_pipeline: None,
                deformed_primed: std::sync::atomic::AtomicBool::new(false),
                deformed_buffers: Vec::new(),
                deformed_vbvs: Vec::new(),
                morph_delta_buffers: Vec::new(),
                morph_target_counts: Vec::new(),
                morph_weights: Vec::new(),
                morph_weight_buffers: Vec::new(),
                morph_weight_ptrs: Vec::new(),
            },
            uniforms: DxUniforms {
                view_ubo_resources,
                view_ubo_ptrs,
                light_ubo,
                local_light_buffer,
                light_uniforms,
                shadow_ubo_resources,
                shadow_ubo_ptrs,
            },
            main_root_sig,
            main_pso,
            light_cull,
            cull: CullState {
                main_bindless_root_sig,
                main_bindless_pso,
                world_pipelines,
                bucket_stride,
                object_buffer_resources,
                object_buffer_ptrs,
                bindless_pool_gpu,
                cull_root_sig,
                cull_pso,
                cull_pso_phase2,
                cull_command_signature,
                draw_args_buffer_resources,
                draw_args_buffer_ptrs,
                indirect_cmd_buffers,
                cull_status_buffers,
                indirect_cmd_buffers_2,
                shadow_bindless_root_sig,
                shadow_bindless_pso,
                shadow_bindless_cmd_sig,
                cull_pso_shadow,
                shadow_indirect_buffers,
                shadow_cull_status_buffers,
                gbuffer_bindless_root_sig,
                gbuffer_bindless_pso,
                gbuffer_bindless_cmd_sig,
                prev_model_buffers: prev_model_buffer_resources,
                prev_model_buffer_ptrs,
                occlusion_two_pass,
                hiz,
                prev_view_proj: std::cell::Cell::new(IDENTITY),
                hiz_valid: std::cell::Cell::new(false),
            },
            shadow_root_sig,
            shadow_pso,
            text: super::context::TextState {
                root_sig: text_root_sig,
                pso: text_pso,
                upload: super::upload_ring::UploadRing::new(FRAMES),
            },
            composite: super::context::CompositeState {
                root_sig: composite_root_sig,
                pso: composite_pso,
            },
            bloom: BloomState {
                mips: bloom_mips,
                mip_rtvs: bloom_mip_rtvs,
                mip_srv_gpus: bloom_mip_srv_gpus,
                mip_extents: bloom_mip_extents,
                root_sig: bloom_root_sig,
                pso_prefilter: bloom_pso_prefilter,
                pso_downsample: bloom_pso_downsample,
                pso_upsample: bloom_pso_upsample,
            },
            post_process,
            gbuffer,
            taa,
            ssao: super::context::SsaoState {
                resources: ssao,
                white: ssao_white,
                white_srv_gpu: ssao_white_srv_gpu,
            },
            transient_pool,
            ssr,
            ssgi,
            reflection_composite,
            rt_reflections,
            rt_accel,
            rt_dynamic_mode,
            rt_skinned_geometry,
            rt_topology_dirty: false,
            decal: super::context::DecalState {
                state: decals_state,
                records: decals_init,
                free_slots: Vec::new(),
            },
            lines: super::line::LineState::empty(),
            main_depth_srv_gpu: decal_depth_srv_gpu,
            raymarch,
            transparent,
            planar_reflection,
            fog: super::context::FogState {
                resources: fog_resources,
                settings: fog_settings,
                sun_dir: fog_sun_dir,
                sun_color: fog_sun_color,
            },
            particle: super::context::ParticleState {
                resources: particle_resources,
                records: particle_records,
                emitter_state: particle_emitter_states,
                free_slots: Vec::new(),
                srv_base_slot: particle_srv_base_slot,
                last_elapsed: std::cell::Cell::new(0.0),
                frame_index: std::cell::Cell::new(0),
            },
            clone: super::context::CloneState {
                srv_base_slot: clone_srv_base_slot,
                count: 0,
                slot_by_draw_idx: std::collections::HashMap::new(),
                free_offsets: Vec::new(),
            },
            commands: DxCommands {
                command_allocators,
                command_lists,
                pass_allocators,
                pass_cmd_lists,
                end_command_allocators,
                end_command_lists,
            },
            frame_sync: DxFrameSync {
                fence,
                fence_values,
                next_fence_value: std::cell::Cell::new(1),
                fence_event,
            },
            current_frame: 0,
            stream: super::context::StreamState {
                pool_rewrites: crate::gfx::slot_rewrites::SlotRewriteQueue::new(FRAMES),
                frame: 0,
                retires: Vec::new(),
            },
            draw: super::context::DrawState {
                n_objects,
                objects: draw_objects,
                bvh: cull_bvh,
                always: always_draw,
                always_member: always_draw_member,
                visible_scratch: RefCell::new(Vec::new()),
                graph_cache: RefCell::new(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 are
                // folded in per frame and the unused tail is disabled. 0 for a
                // non-voxel world.
                n_chunk: n_chunk_max,
                // Set in `upload_skinned` once skinned geometry is resident; the
                // cull buffers reserve the tail at init via the threaded
                // `n_skinned` capacity, but `cull_count()` reads this runtime
                // count.
                n_skinned: 0,
                n_clusters,
            },
            instanced: DxInstanced {
                root_sig: main_instanced_root_sig,
                pso: main_instanced_pso,
                clusters: instanced_clusters,
                upload_buffers: instance_upload_buffers,
                upload_ptrs: instance_upload_ptrs,
                // One outer Vec entry per cluster; populated each frame by
                // `build_instance_upload` from `lod_buckets(cam_pos)`. The
                // inner Vec is the bucket order (LOD0 → LODN) for that
                // cluster. Empty rows for clusters that never have visible
                // instances stay empty.
                bucket_layouts: std::sync::RwLock::new(vec![Vec::new(); n_clusters]),
            },
            view: super::context::ViewState {
                clear_color,
                scene_fade: 0.0,
                mode: Default::default(),
                show: Default::default(),
                far: 1.0,
                matrix: IDENTITY,
            },
            wireframe: Default::default(),
            diagnostics: super::context::Diagnostics {
                frame_stats: std::cell::Cell::new(crate::gfx::profile::RenderStats::default()),
                draw_calls_accum: std::sync::atomic::AtomicU32::new(0),
                info_queue,
            },
            bindless_main_shaders,
            adapter,
            timestamps: TimestampState {
                query_heap: timestamp_query_heap,
                readback: timestamp_readback,
                readback_ptr: timestamp_readback_ptr,
                frequency: timestamp_frequency,
            },
            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,
            },
            max_edr: match hdr_mode {
                crate::gfx::hdr_output::HdrOutputMode::Hdr { max_edr, .. } => Some(max_edr),
                crate::gfx::hdr_output::HdrOutputMode::Sdr => None,
            },
            hdr_encoding: match hdr_mode {
                crate::gfx::hdr_output::HdrOutputMode::Hdr { encoding, .. } => Some(encoding),
                crate::gfx::hdr_output::HdrOutputMode::Sdr => None,
            },
            hot_reload: super::context::HotReloadState {
                enabled: hot_reload,
                reload_pending: shader_reload_pending,
                watcher: shader_watcher,
            },
            quality_slots,
            rt_capable: raytracing_supported,
            rt_static_vertex_count: vertices.len(),
            // Reflection probes: empty until `set_reflection_probes` supplies
            // placements (declared or auto-seeded). See [`super::context`].
            probe: super::context::ProbeState {
                placements: Vec::new(),
                bake_queue: crate::gfx::reflection_probe::ProbeBakeQueue::new(0),
                set: concinnity_render::uniforms::ProbeSet::EMPTY,
                rendering: None,
                converting: None,
                maps: Vec::new(),
                set_cbvs: probe_set_cbvs,
                set_cbv_ptrs: probe_set_cbv_ptrs,
                set_empty_cbv: probe_set_empty_cbv,
            },
        })
    }
}

impl DxContext {
    // Rebuild the world's GPU content in place for a live `cn editor` reload,
    // reusing the retained device + command queue + window + swapchain so the
    // save applies without recreating the OS window or re-initialising the GPU.
    //
    // The GPU is idled, then a fresh context is `build`t on the reused hardware
    // (the D3D12 / DXGI objects are COM ref-counted, so cloning them keeps the
    // same device + swapchain alive; the window `Box` is moved, carrying its live
    // cursor / menu / keymap state) and moved into `*self`. Assigning `*self`
    // drops the old content resources; the device + swapchain survive because the
    // rebuilt context holds a clone, and the window because it was moved out
    // first. Only ever called when the swapchain config is unchanged (the
    // caller's `hot_swap_config` gate).
    //
    // On a content-build failure (essentially impossible for a pre-validated
    // editor edit built from the engine's built-in shaders) `self.win_state`
    // is left `None`; the caller drops this backend and marks the session failed.
    pub(in crate::directx) fn apply_world_reload(
        &mut self,
        init: crate::gfx::backend_init::BackendInit<'_>,
    ) -> Result<(), String> {
        self.wait_idle();
        let reuse = window::DeviceAndWindow {
            win_state: self
                .win_state
                .take()
                .ok_or("apply_world_reload: window already taken")?,
            device: self.device.clone(),
            info_queue: self.diagnostics.info_queue.clone(),
            command_queue: self.command_queue.clone(),
            swapchain: self.swapchain.handle.clone(),
            swapchain_format: self.swapchain.format,
            allow_tearing: self.swapchain.allow_tearing,
            msaa_samples: self.hdr.msaa_samples,
            adapter: self.adapter.clone(),
            hdr_mode: self.hdr_mode,
        };
        // The fresh build resets the fullscreen display-mode bookkeeping (its
        // mode-restore state), which GraphicsSystem does not re-push after a
        // reload; carry it over so a fullscreen editor keeps its restore state.
        // (The keymap rides along inside the moved `win_state`.)
        let fullscreen_display = std::mem::replace(
            &mut self.fullscreen_display,
            crate::win32::display_mode::FullscreenDisplayMode::new(),
        );
        let mut rebuilt = DxContext::build(init, Some(reuse))?;
        rebuilt.fullscreen_display = fullscreen_display;
        *self = rebuilt;
        Ok(())
    }
}

fn create_samplers(
    device: &ID3D12Device,
    base_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
    stride: usize,
    // Scene-sampler max anisotropy from GraphicsConfig.anisotropy, clamped to the
    // D3D12 1..16 range below.
    anisotropy: u32,
) {
    // [0] Shadow comparison sampler (LESS_EQUAL).
    let shadow_samp = D3D12_SAMPLER_DESC {
        Filter: D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT,
        AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        ComparisonFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
        MinLOD: 0.0,
        MaxLOD: f32::MAX,
        ..Default::default()
    };
    // SAFETY: the view descriptor and the resource it names are live for the call, and the
    // destination handle addresses a slot this context reserved for the view in a heap it owns.
    unsafe {
        device.CreateSampler(
            &shadow_samp,
            D3D12_CPU_DESCRIPTOR_HANDLE { ptr: base_cpu.ptr },
        )
    };

    // [1] Anisotropic repeat (albedo + normal map). Anisotropic filtering plus
    // the unclamped MaxLOD lets minified scene textures trilinear-select down
    // their mip chain instead of aliasing from mip 0. The degree comes from
    // GraphicsConfig.anisotropy (default 8), clamped to the D3D12 feature-level-11
    // guaranteed 1..16 range.
    let linear_samp = D3D12_SAMPLER_DESC {
        Filter: D3D12_FILTER_ANISOTROPIC,
        AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
        AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
        AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
        MaxAnisotropy: anisotropy.clamp(1, 16),
        MinLOD: 0.0,
        MaxLOD: f32::MAX,
        ..Default::default()
    };
    // SAFETY: the view descriptor and the resource it names are live for the call, and the
    // destination handle addresses a slot this context reserved for the view in a heap it owns.
    unsafe {
        device.CreateSampler(
            &linear_samp,
            D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: base_cpu.ptr + stride,
            },
        )
    };

    // [2] Cube linear-clamp + mip linear (IBL irradiance / prefilter).
    let cube_samp = D3D12_SAMPLER_DESC {
        Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
        AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        MinLOD: 0.0,
        MaxLOD: f32::MAX,
        ..Default::default()
    };
    // SAFETY: the view descriptor and the resource it names are live for the call, and the
    // destination handle addresses a slot this context reserved for the view in a heap it owns.
    unsafe {
        device.CreateSampler(
            &cube_samp,
            D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: base_cpu.ptr + stride * 2,
            },
        )
    };

    // [3] Linear clamp, mip 0 only (text atlas). The text atlas is a tightly
    // packed glyph SDF: its coarse mips bleed adjacent glyphs together, so
    // trilinear minification samples that garbage and the text reads choppy.
    // Clamp MaxLOD to 0 so only the full-resolution (supersampled) mip 0 is
    // sampled; the SDF stays crisp under bilinear minification on its own.
    // Mirrors the Vulkan text sampler (`create_sampler_linear_clamp`, whose
    // max_lod defaults to 0).
    let clamp_samp = D3D12_SAMPLER_DESC {
        Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
        AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        MinLOD: 0.0,
        MaxLOD: 0.0,
        ..Default::default()
    };
    // SAFETY: the view descriptor and the resource it names are live for the call, and the
    // destination handle addresses a slot this context reserved for the view in a heap it owns.
    unsafe {
        device.CreateSampler(
            &clamp_samp,
            D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: base_cpu.ptr + stride * 3,
            },
        )
    };
}