concinnity-device 0.19.119

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
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
// D3D12 rendering context. Owns all GPU resources, the Win32 window, and input
// state. Mirrors the public API of VkContext / MtlContext so GraphicsSystem can
// drive all three backends identically.

use concinnity_core::components;
use concinnity_core::gfx::render_types;
use concinnity_core::gfx::render_types::*;
use concinnity_core::input::keymap::KeyMap;
use concinnity_core::input::snapshot::InputSnapshot;
use concinnity_core::profile;
use concinnity_core::render::backend;
use concinnity_core::render::backend::FrameParams;
use concinnity_core::render::backend_init;
use concinnity_core::render::error;
use concinnity_core::render::error::{RenderError, RenderResult};
use concinnity_core::render::hdr_output;
use concinnity_core::render::lights;
use concinnity_core::render::pass_timing;
use concinnity_core::render::planar_reflection;
use concinnity_core::render::post::reflection_path::ReflectionPath;
use concinnity_core::render::probe_book::ProbeBook;
use concinnity_core::render::render_graph;
use concinnity_core::render::retire_pool::RetirePool;
use concinnity_core::render::scene_flow;
use concinnity_core::render::scene_state::SceneState;
use concinnity_core::render::slot_rewrites;
use concinnity_core::window::display_mode;
use std::cell::RefCell;
use std::sync::OnceLock;
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::System::Threading::{GetCurrentThreadId, WaitForSingleObject};

use super::allocator::{DeviceAllocator, PooledBuffer, PooledTexture};
use super::auto_exposure::AutoExposureState;
use super::cull::CullState;
use super::decal::*;
use super::draw::shadow::ShadowState;
use super::draw::spot_shadow::SpotShadowState;
use super::fog::*;
use super::geometry_upload::{GeometryDest, GeometryUploads};
use super::hot_reload::HotReloadState;
use super::particle::ParticleState;
use super::post::bloom::BloomResources;
use super::post::gbuffer::GbufferResources;
use super::post::ssao::*;
use super::post::ssr::*;
use super::post::taa::*;
use super::post::upscale::UpscaleState;
use super::resources::skinning::SkinnedState;
use super::texture::*;
use crate::directx::descriptor_slot::{SamplerSlot, SrvSlot};
use crate::win32::window;
use crate::win32::window::{WindowState, frame_tick, take_input_snapshot};

// Constants
pub(super) const FRAMES: usize = 3; // triple-buffered
// Constant buffer alignment required by D3D12.
pub(super) const CB_ALIGN: u64 = 256;

// Upper bound on the number of `SkinnedMesh` draws. The SRV heap is sized once
// at init, so a fixed block of `MAX_SKINNED_OBJECTS * 2` descriptors is
// reserved for skinned (albedo, normal) pairs even when no skinned mesh is
// declared (the reservation costs only descriptor-heap slots, mirroring the
// chunk-streaming SRV reservation). `upload_skinned` rejects worlds exceeding
// this count.
pub(super) const MAX_SKINNED_OBJECTS: usize = 64;

pub(super) fn align256(n: u64) -> u64 {
    (n + CB_ALIGN - 1) & !(CB_ALIGN - 1)
}

// Build the timestamp-query heap + readback buffer for the per-frame GPU
// time chip. Returns `(None, None, null, 0)` when the queue does not
// support timestamps or any resource allocation fails; `draw_frame` then
// leaves `gpu_frame_us` at zero. The readback buffer is persistently
// mapped (READBACK-heap pointers stay valid for the resource's lifetime,
// matching the auto-exposure readback pattern).
pub(super) fn build_timestamp_resources(
    alloc: &DeviceAllocator,
) -> (
    Option<ID3D12QueryHeap>,
    Option<PooledBuffer>,
    *const u64,
    u64,
) {
    let device = alloc.device();
    // SAFETY: a property query on a live command queue; it only reads.
    let frequency = unsafe { alloc.queue().GetTimestampFrequency() }.unwrap_or(0);
    if frequency == 0 {
        return (None, None, std::ptr::null(), 0);
    }
    // Heap holds one block of [whole_frame_start, whole_frame_end, then
    // PASS_COUNT (start, end) pairs] per in-flight frame. See
    // `concinnity_core::render::pass_timing` for the slot layout.
    //
    // Timing: `execute_graph` issues an EndQuery before and after each pass's
    // encode, and the resolve at the end of the command list copies the whole block
    // into the persistently-mapped readback buffer. The CPU reads the previous
    // frame's block at the top of `draw_frame`, after the matching fence wait gates
    // the GPU writes. SsaoDepth and SsaoKernel are bundled inside their parent
    // encoder, and the FogFroxel / Upscale / Transparent / Raymarch arms are no-ops
    // here, so those slots stay zero and drop out of the on-screen chip.
    let heap_desc = D3D12_QUERY_HEAP_DESC {
        Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
        Count: (pass_timing::SLOTS_PER_FRAME * FRAMES) as u32,
        NodeMask: 0,
    };
    let mut heap: Option<ID3D12QueryHeap> = None;
    // 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.
    if let Err(e) = unsafe { device.CreateQueryHeap(&heap_desc, &mut heap) } {
        tracing::warn!("timestamp query heap create failed: {e}");
        return (None, None, std::ptr::null(), 0);
    }
    let readback = match alloc.alloc_buffer(
        pass_timing::FRAME_BLOCK_BYTES * FRAMES as u64,
        D3D12_HEAP_TYPE_READBACK,
        D3D12_RESOURCE_STATE_COPY_DEST,
    ) {
        Ok(r) => r,
        Err(e) => {
            tracing::warn!("timestamp readback buffer create failed: {e}");
            return (None, None, std::ptr::null(), 0);
        }
    };
    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.
    if let Err(e) = unsafe { readback.Map(0, None, Some(&mut ptr)) } {
        tracing::warn!("timestamp readback map failed: {e}");
        return (None, None, std::ptr::null(), 0);
    }
    (heap, Some(readback), ptr as *const u64, frequency)
}

// Per-pass GPU timestamp query state. `query_heap` + `readback` are `None`
// when the command queue does not expose a non-zero timestamp frequency; the
// per-pass chip then reports 0 us. See [`pass_timing`] for the slot
// helpers and [`build_timestamp_resources`] for construction.
pub(super) struct TimestampState {
    // Timestamp query heap with `SLOTS_PER_FRAME * FRAMES` slots: one block
    // per in-flight frame, each laid out as a whole-frame start/end pair
    // followed by one (start, end) pair per `PassId`.
    pub query_heap: Option<ID3D12QueryHeap>,
    // Persistently-mapped READBACK buffer paired with `query_heap`, holding
    // `FRAMES` blocks of `SLOTS_PER_FRAME` `u64` ticks each.
    pub readback: Option<PooledBuffer>,
    pub readback_ptr: *const u64,
    // Ticks per second from `ID3D12CommandQueue::GetTimestampFrequency`; zero
    // when timestamps are unsupported.
    pub frequency: u64,
}

// Off-screen HDR scene target. The main + instanced passes render linear-light
// HDR into `color`; the composite pass tonemaps it down onto the swapchain
// backbuffer. With MSAA on (`msaa_samples > 1`), `color` is the multisampled
// target and the per-frame loop resolves it into the single-sample `resolve`;
// with MSAA off `color` is single-sample and `resolve` is `None`.
// `resolve_rtv` is `Some` only when MSAA is on (the projected-decal pass renders
// into the resolved scene target; the MSAA-off path uses `color_rtv`).
// `srv_gpu` points at whichever target the composite pass samples.
pub(super) struct HdrState {
    pub color: ID3D12Resource,
    pub color_rtv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub resolve: Option<ID3D12Resource>,
    pub resolve_rtv: Option<D3D12_CPU_DESCRIPTOR_HANDLE>,
    pub srv_gpu: SrvSlot,
    pub msaa_samples: u32,
}

// Rectangular area lights: the per-scene `AreaLightData` table indexed by
// `GpuLight.data_index`, plus the two LTC lookup tables the shading path
// samples. All three are static for the world's lifetime. The tables are
// scene-independent (fitted at build time), so they are uploaded even with no
// area light declared -- the shader simply never samples them.
pub(super) struct AreaLightState {
    pub buffer: PooledBuffer,
    #[expect(
        dead_code,
        reason = "owns the resource the LTC table descriptors point at"
    )]
    pub ltc_matrix: GpuResource,
    #[expect(
        dead_code,
        reason = "owns the resource the LTC table descriptors point at"
    )]
    pub ltc_magnitude: GpuResource,
    // Base of the 2-descriptor LTC table (matrix, then magnitude).
    pub ltc_table_gpu: SrvSlot,
}

// The main-pass constant buffers, grouped off the flat `DxContext`. Mirrors
// Vulkan's `VkUniforms`. The view, light and shadow buffers are all per-frame
// and persistently mapped. The COM resources auto-release on drop; only the
// persistent mappings need an explicit `unmap`.
pub(super) struct DxUniforms {
    pub view_ubo_resources: Vec<PooledBuffer>,
    pub view_ubo_ptrs: Vec<*mut u8>,
    // Per-frame-in-flight `LightUniforms` CBV ring. Every pass that binds the
    // light block (main, transparent, raymarch, planar) takes the frame's own
    // GPU address, so a live light change never has to drain the queue.
    pub light_ubo_resources: Vec<PooledBuffer>,
    pub light_ubo_ptrs: Vec<*mut u8>,
    // Which slots of the light ring still need this frame's values.
    pub light_dirty: std::cell::Cell<concinnity_core::render::frame_dirty::FrameDirty>,
    // Per-scene local-light storage buffer bound as a root SRV by the main
    // pass. Static: filled once at init from `BackendInit.local_lights` and
    // never rewritten (not persistently mapped, so it stays out of `unmap`).
    pub local_light_buffer: PooledBuffer,
    // The local lights' reach, which places the far end of the cluster grid.
    pub cluster_reach: concinnity_core::render::cluster_range::ClusterReach,
    // The values the light ring carries. A live Ambient-slider or
    // directional-light change mutates this and re-arms `light_dirty`;
    // `record_frame` writes the frame's own slot, so no in-flight read is raced.
    pub light_uniforms: render_types::LightUniforms,
    pub shadow_ubo_resources: Vec<PooledBuffer>,
    pub shadow_ubo_ptrs: Vec<*mut u8>,
    // Per-frame CBVs holding the live probe count, bound at root param [11] by
    // the main pass. A `FRAMES` ring so a frame writes its
    // own slot without racing a prior frame's in-flight GPU read.
    pub probe_set_cbvs: Vec<PooledBuffer>,
    pub probe_set_cbv_ptrs: Vec<*mut u8>,
    // A static count-0 ProbeSet CBV the asynchronous capture binds at [11], so a
    // probe face render samples the sky (no probe feedback) and never reads the
    // live ring while `record_frame` rewrites it.
    pub probe_set_empty_cbv: PooledBuffer,
}

impl DxUniforms {
    // Re-arm every light-ring slot after a change to `light_uniforms`.
    pub(super) fn mark_lights_dirty(&self) {
        let mut dirty = self.light_dirty.get();
        dirty.mark_all();
        self.light_dirty.set(dirty);
    }

    // Whether `frame`'s light CBV still needs this frame's values, clearing it.
    pub(super) fn take_light_dirty(&self, frame: usize) -> bool {
        let mut dirty = self.light_dirty.get();
        let pending = dirty.take(frame);
        self.light_dirty.set(dirty);
        pending
    }

    // Unmap the persistent view + light + shadow CBV mappings. Called from
    // `DxContext::drop`; the COM resources themselves auto-release.
    pub(super) fn unmap(&self) {
        for res in self
            .view_ubo_resources
            .iter()
            .chain(self.light_ubo_resources.iter())
            .chain(self.shadow_ubo_resources.iter())
        {
            // SAFETY: the resource is live and this code mapped it, and nothing keeps the mapping
            // past this call.
            unsafe { res.Unmap(0, None) };
        }
    }
}

// Per-frame command infrastructure (allocators + lists), grouped off the flat
// `DxContext`. Mirrors Vulkan's `VkCommands`. The frame is split across two
// outer cmd lists + a per-pass pool so non-composite passes can record in
// parallel:
//
//   * `command_allocators` / `command_lists`: "start" outer cmd list. Holds the
//     timestamp pre-init at the top of every frame (D3D12 debug layer flags an
//     unwritten slot in the `ResolveQueryData` range, so every pass's pair is
//     pre-initialized here). FRAMES-sized.
//
//   * `pass_allocators` / `pass_cmd_lists`: per-pass pool. 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.
//     Indexed as `frame_idx * PASS_COUNT + (PassId as usize)`. Passes the graph
//     never activates simply leave their slot untouched; it never enters the
//     submission list.
//
//   * `end_command_allocators` / `end_command_lists`: "end" outer cmd list.
//     Holds the composite pass + the final timestamp `EndQuery` +
//     `ResolveQueryData`. Submitted after every per-pass cmd list so the resolve
//     sees every prior pass's `EndQuery` writes. FRAMES-sized.
pub(super) struct DxCommands {
    pub command_allocators: Vec<ID3D12CommandAllocator>,
    pub command_lists: Vec<ID3D12GraphicsCommandList>,
    pub pass_allocators: Vec<ID3D12CommandAllocator>,
    pub pass_cmd_lists: Vec<ID3D12GraphicsCommandList>,
    pub end_command_allocators: Vec<ID3D12CommandAllocator>,
    pub end_command_lists: Vec<ID3D12GraphicsCommandList>,
}

// CPU/GPU frame synchronization, grouped off the flat `DxContext`. Mirrors
// Vulkan's `VkFrameSync` (D3D12 uses one monotonic fence + per-slot signaled
// values instead of per-frame semaphores). The ring cursor (`current_frame`)
// and the per-frame draw-call accumulator stay flat on `DxContext`. All COM /
// plain fields auto-release on drop; only `fence_event` needs an explicit
// `CloseHandle` (done in `DxContext::drop`).
pub(super) struct DxFrameSync {
    pub fence: ID3D12Fence,
    // Per-slot fence value last signaled for that slot's submission. Compared
    // against `fence.GetCompletedValue()` to gate the slot's allocator reset.
    pub fence_values: Vec<u64>,
    // Global monotonic counter feeding every Signal. Must be unique per
    // submission across all slots, otherwise the wait-before-reuse check can
    // be satisfied by another slot's signal of the same value. `Cell` because
    // `wait_idle` advances it through `&self` (trait-imposed signature).
    pub next_fence_value: std::cell::Cell<u64>,
    pub fence_event: windows::Win32::Foundation::HANDLE,
}

// Shared static-mesh geometry buffers + their views, grouped off the flat
// `DxContext`. Mirrors Vulkan's `VkGeometry`.
pub(super) struct DxGeometry {
    pub vertex_buffer: PooledBuffer,
    pub index_buffer: PooledBuffer,
    pub vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW,
    pub index_buffer_view: D3D12_INDEX_BUFFER_VIEW,
}

// Instanced-prop clusters, grouped off the flat `DxContext`. Mirrors Vulkan's
// `VkInstanced`. Every instance folds into the GPU-driven cull records, so no
// pass walks the instances on the CPU.
pub(super) struct DxInstanced {
    pub clusters: Vec<InstancedCluster>,
    // Whether any cluster declares LOD alternates. False skips the per-frame
    // per-instance LOD patch: without alternates the base slice written into
    // every frame's draw-args buffer at init is right for the world's life.
    pub any_lod: bool,
}

impl DxInstanced {
    pub(super) fn new(clusters: Vec<InstancedCluster>) -> Self {
        Self {
            any_lod: concinnity_core::gfx::lod::any_cluster_has_lod(&clusters),
            clusters,
        }
    }
}

// The shader-visible descriptor heaps and the static sampler handles, grouped
// off the flat `DxContext`. The SRV heap's slot map is `layout`, which every
// pass addresses its descriptors through.
pub(super) struct DxDescriptors {
    // CBV/SRV/UAV descriptor heap (shader-visible). The slot map is
    // `init/heap_layout.rs`.
    pub srv_heap: ID3D12DescriptorHeap,
    pub srv_descriptor_size: usize,
    // The resolved slot of every block in `srv_heap`. The flat deduplicated
    // bindless pool at `layout.flat_pool_base_slot` (`[albedo SRVs..] ++
    // [normal SRVs..]`) repeats once per frame in flight, `flat_pool_len` slots
    // per copy: the bindless main pass and the RT hit shader address the current
    // frame's copy by a flat index, and the streaming-residency rewrite
    // re-points the one SRV per swapped pool slot in each copy as its frame
    // fence-waits. The reflection-probe cube block and the per-bake convolution
    // descriptors live here too. See [`super::probe`] and
    // [`super::probe_prefilter`].
    pub layout: super::init::heap_layout::SrvHeapLayout,
    pub flat_pool_len: usize,
    // Sampler heap (shader-visible). Slots:
    //   [0] shadow comparison (s0)   [1] linear repeat (s1)
    //   [2] cube linear-clamp + mip linear (s2)   [3] text linear-clamp
    pub sampler_heap: ID3D12DescriptorHeap,
    pub shadow_sampler_gpu: SamplerSlot,
    pub linear_sampler_gpu: SamplerSlot,
    pub text_sampler_gpu: SamplerSlot,
}

// Scene-captured reflection probes and the staggered bake that fills them.
// See [`super::probe`].
pub(super) struct ProbeState {
    // Placements (declared `ReflectionProbe` assets or an auto-seeded grid), the
    // record of every installed probe (the live count the forward / SSR / RT /
    // transparent shaders read) and the staggered bake's queue: a not-yet-baked
    // probe falls back to the sky until its turn.
    pub book: ProbeBook,
    // The cube array the bake writes a cube of per placement, and the per-frame
    // record buffers. Distinct from `env_map` so the background + diffuse
    // irradiance keep the sky.
    pub gpu: super::probe_set::ProbeSetGpu,
    // At most one probe whose six cube faces are rendering on the GPU (one face
    // per frame, into the reserved-ring-slot capture resources) and one prior
    // probe whose capture is convolving into its cube, one destination mip per
    // frame.
    pub bake: super::probe::DxProbeBake,
    // The three convolution kernels and their root signatures, built at init under
    // the same gate the bake needs. `None` disables baking.
    pub prefilter: Option<super::probe_prefilter::ProbePrefilterPipelines>,
}

impl ProbeState {
    // Empty until `set_reflection_probes` supplies placements (declared or
    // auto-seeded).
    pub(super) fn new(
        prefilter: Option<super::probe_prefilter::ProbePrefilterPipelines>,
        gpu: super::probe_set::ProbeSetGpu,
    ) -> Self {
        Self {
            book: ProbeBook::new(),
            gpu,
            bake: super::probe::DxProbeBake::default(),
            prefilter,
        }
    }
}

// Stall-free texture streaming. A streamed slot swap replaces the pool resource
// immediately but cannot rewrite the per-frame flat-pool SRV copies while their
// frames' lists are pending; `stream.pool_rewrites` carries the slot to each frame's
// copy right after its fence wait (`apply_streamed_texture_rewrites`). The
// replaced resource and the upload's transients are parked on `retires` against
// the monotonic `frame` tick and released `RETIRE_DEPTH` ticks later: by then
// every copy has been re-pointed, every list recorded against the old resource
// has retired, and the tick's fence wait covers the upload submission itself.
pub(super) struct StreamState {
    pub pool_rewrites: slot_rewrites::SlotRewriteQueue,
    pub frame: u64,
    pub retires: RetirePool<super::texture::StreamedUploadRetire>,
}

impl StreamState {
    // `FRAMES + 1`: a swap lands between frames, after the previous frame's
    // submit, so the first frame fence that covers the upload submission is the
    // one signaled by the NEXT draw, waited FRAMES ticks after that draw's tick.
    pub(super) const RETIRE_DEPTH: u64 = FRAMES as u64 + 1;

    pub(super) fn new() -> Self {
        Self {
            pool_rewrites: slot_rewrites::SlotRewriteQueue::new(FRAMES),
            frame: 0,
            retires: RetirePool::new(),
        }
    }
}

// The swapchain, its back buffers + RTV heap, and the presentation pacing.
pub(super) struct SwapchainState {
    pub handle: IDXGISwapChain3,
    pub back_buffers: Vec<ID3D12Resource>,
    pub rtv_heap: ID3D12DescriptorHeap,
    pub rtv_descriptor_size: usize,
    // Swapchain RTV format captured at init. Stored so the composite + text PSO
    // rebuilds during shader hot-reload can target the same format the PSOs were
    // originally created against.
    pub format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
    // 1 (vsync, lock to refresh) or 0 (uncapped).
    pub present_sync_interval: u32,
    // True when the swapchain was created with
    // DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING (vsync off + tearing supported); it
    // selects the tearing present flag and must be mirrored in ResizeBuffers.
    pub allow_tearing: bool,
    // Back-buffer index of the most recently presented frame. `None` until the
    // first `draw_frame` presents. The headless `screenshot` path copies this
    // buffer (the one currently on screen); `GetCurrentBackBufferIndex` after a
    // present already points at the next buffer to render into, so the captured
    // index must be recorded at present time. Mirrors
    // `VkContext::swapchain.last_present_index`.
    pub last_present_index: Option<usize>,
}

// The two resolutions the pipeline runs at. `render_*` is what the scene is
// rendered at: the G-buffer + SSAO + SSR + Hi-Z + raymarch targets are sized to
// it. When temporal upscaling is active it is `output_* * upscale_quality.scale()`,
// strictly smaller than the drawable; FSR reconstructs the drawable resolution
// into the upscaler's output texture, which bloom + composite then sample.
// `output_*` is the drawable (swapchain) resolution: the back buffers, the bloom
// mip chain, the upscaler's output texture, and the composite/text pass run at
// this size. They are equal whenever temporal upscaling is off, and the renderer
// then behaves as a single-resolution pipeline.
pub(super) struct Extents {
    pub render_width: u32,
    pub render_height: u32,
    pub output_width: u32,
    pub output_height: u32,
}

// The main depth buffer and the DSV heap that also holds the cascade, spot and
// G-buffer depth views. `dsv` indexes into the heap; the depth resource itself
// is never read back.
pub(super) struct DepthState {
    pub dsv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub resource: ID3D12Resource,
    pub heap: ID3D12DescriptorHeap,
}

// HUD text pass: its root signature, its PSO (`None` until the first frame that
// publishes text), and the per-frame-slot persistent upload buffers for
// transient text geometry. Each upload slot's cursor resets and its buffer
// (re)maps inside the ring's `reserve`, which the composite pass calls once the
// frame fence confirms the GPU is done with slot i.
pub(super) struct TextState {
    pub root_sig: ID3D12RootSignature,
    pub pso: Option<ID3D12PipelineState>,
    pub upload: super::upload_ring::UploadRing,
    // Held only to keep the text-atlas textures resident; the SRV handles
    // below are what the text pass actually binds.
    #[expect(
        dead_code,
        reason = "held to keep the text atlases resident; the pass binds the SRV handles"
    )]
    pub atlas_textures: Vec<GpuResource>,
    pub atlas_srv_gpus: Vec<SrvSlot>,
}

// Composite (post-process) pass: fullscreen-triangle tonemap of the HDR scene
// target onto the swapchain backbuffer.
pub(super) struct CompositeState {
    pub root_sig: ID3D12RootSignature,
    pub pso: ID3D12PipelineState,
}

// Per-frame counters and the D3D12 validation sink.
#[derive(Default)]
pub(super) struct Diagnostics {
    // Render statistics for the most recent frame: draw-call and object counts
    // (filled by `draw_frame`) plus VRAM bytes pulled from the adapter. Lives in
    // a `Cell` because the per-pass increments happen through the `&self`
    // `record_frame` path. Surfaced to the profiler overlay via `render_stats`.
    pub frame_stats: std::cell::Cell<profile::RenderStats>,
    // CPU-side accumulator for this frame's draw calls. The Metal + Vulkan
    // executors use the same pattern: encoders (which may run in parallel) bump
    // this atomic via `inc_draw_calls`; the main thread drains it into
    // `diagnostics.frame_stats.draw_calls` at the end of every frame. `AtomicU32` because
    // `Cell<RenderStats>` is single-threaded and would race when workers encode
    // in parallel.
    pub draw_calls_accum: std::sync::atomic::AtomicU32,
}

// The render-resolution scene targets: the HDR color target, the main depth
// buffer and its sampling SRV, the two pipeline resolutions, and the render
// graph's transient pool. The resize path rebuilds all of it.
pub(super) struct DxTargets {
    pub hdr: HdrState,
    pub depth: DepthState,
    // GPU handle of the main-depth SRV. Written at init (and rewritten on
    // resize) into a single reserved heap slot every depth-sampling decoration
    // pass binds; the lazily-built line pass needs it past init.
    pub main_depth_srv_gpu: SrvSlot,
    pub extent: Extents,
    // Backing store for the render graph's transient render targets (the
    // resources the aliasing planner manages). Owns each managed transient as a
    // placed resource on an `ID3D12Heap`; features read them back by label and
    // the executor's barrier registry resolves them the same way.
    pub transient_pool: super::transient_pool::TransientResourcePool,
    // The reactive mask the particle and transparent passes write.
    pub reactive_mask: super::reactive_mask::ReactiveMask,
}

// The world's scene assets: the IBL cubes and color-grading LUT, the area-light
// tables, and the shared static-mesh geometry. None of it depends on the
// swapchain.
pub(super) struct DxSceneAssets {
    // IBL resources. The fragment shader always samples these; when no
    // EnvironmentMap was supplied, both are 1x1 gray fallback cubes and
    // ViewUniforms::prefilter_mip_count is 0, so the shader uses the flat albedo
    // ambient term instead of IBL.
    pub env_map: EnvironmentMapTextures,
    // 3D color-grading LUT sampled in the composite pass. Holds the declared
    // `ColorLut` payload baked into a Texture3D, or a 2x2x2 identity LUT when
    // the world declares none. Resolution-independent, so it is never rebuilt.
    pub color_lut: GpuResource,
    pub area_light: AreaLightState,
    pub geometry: DxGeometry,
    // Shared texture pool (kept alive). Every texture -- albedo, normal map,
    // emissive/ORM, terrain secondary -- lives here once at its handle, matching
    // Metal/Vulkan, so `DrawObject::texture_slot` and a real `normal_map_slot`
    // index directly into it. `_fallback_textures` holds only the reserved
    // pair past the last real texture -- flat-normal for a normal-less draw,
    // then white for an albedo-less one; real normal maps and albedos are
    // entries in `textures`. Held so the flat pool's fallback SRVs stay
    // resident; nothing reads the resources back.
    pub textures: Vec<PooledTexture>,
    pub _fallback_textures: Vec<PooledTexture>,
}

// The hardware ray-tracing scene: the acceleration structures and the policy
// that keeps them current as the draw set changes.
pub(super) struct DxRayTracing {
    // BLAS/TLAS + geometry table. `Some` only when RT reflections are on, the
    // GPU reports the DXR tier, and the build succeeded.
    pub accel: Option<super::raytrace::RtAccelData>,
    // How the acceleration structure is kept current as props move (the
    // launch's `--rt-dynamic` request; `Auto` by default).
    pub dynamic_mode: concinnity_core::render::rt_geom::RtDynamicMode,
    // Whether the per-frame BVH update is failing, so a failure is logged once
    // per streak rather than every frame.
    pub update_streak: concinnity_core::render::rt_accel::FailureStreak,
    // BVHs dropped mid-run (a refresh removed the last geometry), held until no
    // frame still in flight can trace them, timed against `retire_tick`, which
    // advances once per frame.
    pub retired: RetirePool<super::raytrace::RtAccelData>,
    pub retire_tick: u64,
    // Whether skinned meshes join the BVH (the launch's `--rt-skinned-geometry`
    // request; in by default). Clear it and the BVH covers static + instanced
    // geometry only, isolating the skinned trace path.
    pub skinned_geometry: bool,
    // The compute-skinning pipeline (`rt_skin`) skinned geometry joins the BVH
    // through, built with the RT pass. `None` when the kernel failed to compile.
    pub skin: Option<super::raytrace::SkinPipeline>,
}

// The device layer every per-world resource is built on: device, queue,
// allocator, adapter and window, plus the capabilities and display settings
// negotiated with them. The window is declared last so every COM object that
// presents to it releases first.
pub(super) struct DxHardware {
    pub device: ID3D12Device,
    pub command_queue: ID3D12CommandQueue,
    // Placement pool every persistent buffer and CPU-uploaded texture is
    // suballocated from, rather than one committed resource each. See
    // `directx/allocator.rs`.
    pub alloc: DeviceAllocator,
    // IDXGIAdapter3 for `QueryVideoMemoryInfo`, the VRAM chip's source. `None`
    // when the adapter does not expose the v3 interface; the chip then reads
    // `0 MB`.
    pub adapter: Option<IDXGIAdapter3>,
    // D3D12 validation message sink (`Some` only when validation=true).
    pub info_queue: Option<ID3D12InfoQueue>,
    // Whether the GPU reports the DXR 1.1 tier. Gates the live RT-reflections
    // toggle: an enable on a non-DXR GPU no-ops with a warning, mirroring the
    // init fallback to SSR.
    pub rt_capable: bool,
    // The resolved HDR-output mode. (The DXGI format is in `swapchain.format`.)
    pub hdr_mode: hdr_output::HdrOutputMode,
    // The swapchain config (ring depth + HDR request) this context was built
    // with, reported by `hot_swap_config` so a live editor reload reuses this
    // hardware only when the new world's config still matches.
    pub swapchain_config: backend_init::SwapchainConfig,
    // The user's chosen fullscreen display mode, held on the monitor while the
    // window is in (borderless) fullscreen and restored on exit / drop.
    // Reconciled once per frame in `window_closed`.
    pub fullscreen_display: crate::win32::display_mode::FullscreenDisplayMode,
    // Win32 window. `Option` so a live `cn editor` world reload can MOVE the
    // window (and its live cursor / menu / keymap state) into the rebuilt
    // context; a normal context always holds `Some`. Access via `win`/`win_mut`.
    pub win_state: Option<Box<WindowState>>,
}

impl DxHardware {
    // The hardware an outgoing context hands its successor on a live editor
    // `reload_world`: COM clones of the device, queue, adapter and info queue,
    // with the window and fullscreen restore state moved out. The successor
    // places into a fresh allocator; the outgoing world releases into its own.
    pub(super) fn hand_over(&mut self) -> RenderResult<Self> {
        Ok(Self {
            win_state: Some(self.win_state.take().ok_or_else(|| {
                RenderError::Other("apply_world_reload: window already taken".into())
            })?),
            fullscreen_display: std::mem::replace(
                &mut self.fullscreen_display,
                crate::win32::display_mode::FullscreenDisplayMode::new(),
            ),
            alloc: DeviceAllocator::new(&self.device, &self.command_queue, FRAMES),
            device: self.device.clone(),
            command_queue: self.command_queue.clone(),
            adapter: self.adapter.clone(),
            info_queue: self.info_queue.clone(),
            rt_capable: self.rt_capable,
            hdr_mode: self.hdr_mode,
            swapchain_config: self.swapchain_config,
        })
    }

    // Maximum extended-range multiplier on the HDR path, `None` on SDR.
    pub(super) fn max_edr(&self) -> Option<f32> {
        match self.hdr_mode {
            hdr_output::HdrOutputMode::Hdr { max_edr, .. } => Some(max_edr),
            hdr_output::HdrOutputMode::Sdr => None,
        }
    }

    // HDR encoding (scRGB-linear vs PQ) on the HDR path, `None` on SDR.
    pub(super) fn hdr_encoding(&self) -> Option<hdr_output::HdrEncoding> {
        match self.hdr_mode {
            hdr_output::HdrOutputMode::Hdr { encoding, .. } => Some(encoding),
            hdr_output::HdrOutputMode::Sdr => None,
        }
    }
}

pub(crate) struct DxContext {
    pub(super) swapchain: SwapchainState,

    // Render-resolution scene targets. See [`DxTargets`].
    pub(super) targets: DxTargets,

    // Temporal upscaling (AMD FidelityFX FSR3). See [`UpscaleState`].
    pub(super) upscale: UpscaleState,

    // Shadow map resources. See [`ShadowState`].
    pub(super) shadow: ShadowState,

    // Spot shadow map resources. See [`SpotShadowState`].
    pub(super) spot_shadow: SpotShadowState,

    // Scene assets. See [`DxSceneAssets`].
    pub(super) scene: DxSceneAssets,

    // Shader-visible descriptor heaps + samplers + scene texture pools. See
    // `DxDescriptors`.
    pub(super) descriptors: DxDescriptors,
    // The CPU-side scene: draw list, view, skinned slots, model history and
    // streamed-geometry placement. See [`SceneState`].
    pub(super) state: SceneState,
    // The last compiled frame graph, keyed by the `FrameGraphInputs` it was built
    // from. `build_frame_graph` is a pure function of those inputs (which change
    // only when a feature toggles or a target resizes), so a frame whose inputs
    // match the cached key reuses the compiled graph instead of rebuilding it.
    // `RefCell` because `record_frame` is &self; taken out before
    // `execute_graph` and put back after so a steady scene compiles the graph
    // once and reuses it thereafter.
    pub(super) graph_cache:
        RefCell<Option<(render_graph::FrameGraphInputs, render_graph::CompiledGraph)>>,

    // Geometry writes staged for the next copy submit. See [`GeometryUploads`].
    pub(super) geometry_uploads: RefCell<GeometryUploads>,

    // Skinned (skeletally animated) mesh rendering. All `None` / empty until
    // `upload_skinned` runs.
    pub(super) skinned: SkinnedState,

    // Constant buffers (view + shadow per-frame persistent-mapped, light once).
    // See `DxUniforms`.
    pub(super) uniforms: DxUniforms,

    // Root signatures + PSOs
    // GPU-driven cull + main pass. All `Some`/non-empty only when the world has
    // anything to drive. See [`CullState`].
    pub(super) cull: CullState,
    // Clustered light binning: the compute pipeline (built only when the world
    // has local lights), the per-cluster light-index buffer, and the per-frame
    // `ClusterParams` constant buffers. See [`LightCullState`].
    pub(super) light_cull: super::light_cull::LightCullState,
    pub(super) text: TextState,
    pub(super) composite: CompositeState,

    // The shared bloom chain and the view of the pool's `bloom_top` it writes.
    // The octaves are shared across frame slots; the command queue runs frames
    // serially, so a frame's bloom writes never race a prior frame's composite
    // read. `None` only while a resize rebuilds it.
    pub(super) bloom: Option<BloomResources>,
    // Post-process tunables (bloom / exposure / vignette). Drives whether the
    // bloom chain runs and feeds the bloom-prefilter + composite root constants.
    pub(super) post_process: render_types::PostProcessParams,

    // Unified geometry G-buffer pre-pass. `Some` whenever any screen-space
    // consumer (SSR, SSGI, SSAO, TAA, or temporal upscaling) is enabled: one
    // jittered traversal writes view normal+depth, roughness, and motion into
    // one MRT that all those consumers read, replacing the separate SSR / SSAO
    // / velocity geometry pre-passes. See [`GbufferResources`].
    pub(super) gbuffer: Option<GbufferResources>,

    // Temporal anti-aliasing. `Some` only when `PostProcessConfig.aa_mode` is set;
    // when `None` the history resolve and the projection jitter are skipped and
    // the composite samples the HDR scene target directly.
    pub(super) taa: Option<TaaResources>,

    // The descriptor slots every shared fullscreen post pass allocates its
    // targets from. Held once for the backend rather than reserved per effect in
    // `init/heap_layout.rs`.
    pub(super) post: super::post::descriptors::PostDescriptors,

    // SSAO (GTAO). See [`SsaoState`].
    pub(super) ssao: SsaoState,

    // SSR. `Some` when `PostProcessConfig.ssr` is set, or when SSGI is on
    // (SSGI reuses the depth + normal pre-pass G-buffer). The resolve half
    // (`ssr.resolve`) is `Some` only when SSR itself is authored on; with it
    // off the TAA / bloom / composite passes sample `hdr_srv_gpu` directly as
    // the scene color. When the resolve is on it writes into
    // `ssr.resolve.output`, whose SRV becomes the scene the post stack consumes
    // (see `scene_srv_for_post`).
    pub(super) ssr: Option<SsrResources>,

    // SSGI. `Some` only when `PostProcessConfig.indirect_lighting` is `ssgi`.
    // A hemisphere-gather + depth-aware-blur composite that bleeds nearby lit
    // surfaces' color onto one another, additively on top of the IBL ambient.
    // Reuses the SSR pre-pass G-buffer (so `ssr` is also `Some` whenever this
    // is); the render-graph `PassId::Ssgi` node is gated on `ssgi.is_some()`.
    pub(super) ssgi: Option<super::post::ssgi::SsgiResources>,

    // Roughness-aware reflection composite: the SSR / RT resolve writes reflected
    // radiance + weight, then this blurs it by surface roughness (a reduced-res blur
    // pass) and composites it over the scene into its own output -- the scene the
    // post stack consumes via `scene_srv_for_post`. `Some` when SSR resolve or RT is
    // authored (both feed it).
    pub(super) reflection_composite:
        Option<super::post::reflection_composite::DxReflectionCompositePass>,

    // Hardware ray-traced reflections (DXR). `rt_reflections` (output target +
    // RtParams UBO + root sig + flat/textured PSOs) and `rt.accel` (BLAS/TLAS +
    // geometry table) are both `Some` only when the world enables
    // `ray_traced_reflections`, the GPU supports the DXR tier, and the DXC
    // compile + acceleration-structure build succeeded; otherwise the graph
    // falls back to `SsrResolve`. RT occupies the `SsrResolve` slot, reuses the
    // SSR pre-pass G-buffer (forced on), and its output becomes the scene the
    // post stack consumes via `scene_srv_for_post`. `FrameGraphInputs::
    // rt_reflections_enabled` is gated on both being `Some`.
    pub(super) rt_reflections: Option<super::post::rt_reflections::RtReflectionsResources>,
    // The ray-tracing scene. See [`DxRayTracing`].
    pub(super) rt: DxRayTracing,

    // Projected decals. See [`DecalState`].
    pub(super) decal: DecalState,

    // World-space line pass state: the resources, built on the first frame
    // that publishes lines. See [`super::line::LineState`].
    pub(super) lines: super::line::LineState,

    // Raymarched SDF volumes. `Some` when the world declares at least one
    // `SdfVolume`. Render-graph `PassId::Raymarch` is gated on
    // `Self::raymarch_enabled()` so worlds with no visible SDF skip the slot
    // entirely.
    pub(super) raymarch: Option<super::raymarch::RaymarchResources>,

    // The environment drawn behind the opaque scene. See `directx/sky.rs`.
    pub(super) sky: super::sky::DxSky,

    // The shared `PassId::Transparent` slot and its two producers, translucent
    // glass panes and water surfaces. `Some` only when the world declared a
    // `GlassPanel` or a `WaterSurface`; with neither the field stays `None` and
    // the pass is skipped. Render-graph inclusion is gated on
    // `Self::transparent_enabled()`. Mirrors src/metal's transparent encoder.
    pub(super) transparent: Option<super::transparent::TransparentResources>,

    // Planar reflections for the transparent pass's flat reflectors: a per-frame
    // mirror render of the scene reflected across each distinct reflector plane
    // (a water surface's rest plane, a glass pane's plane), sampled by the
    // shaders at screen UV (sharper + scene-correct vs the box-projected probe
    // cube). `Some` only when the world has reflectors assigned to a planar slot.
    // Driven inline at the head of the transparent pass
    // (`encode_planar_reflections`).
    pub(super) planar_reflection: Option<super::planar::PlanarReflectionSet>,

    // Volumetric fog. See [`FogState`].
    pub(super) fog: FogState,

    // GPU-compute particle system. See [`ParticleState`].
    pub(super) particle: ParticleState,

    // Per-frame command allocators + lists (start / per-pass / end). See
    // `DxCommands`.
    pub(super) commands: DxCommands,
    pub(super) diagnostics: Diagnostics,
    // CPU/GPU frame synchronization (one monotonic fence + per-slot values).
    // See `DxFrameSync`.
    pub(super) frame_sync: DxFrameSync,
    pub(super) current_frame: usize,

    pub(super) stream: StreamState,

    // Instanced-prop per-frame upload buffers + LOD buckets. See `DxInstanced`.
    pub(super) instanced: DxInstanced,
    // Lazily-built wireframe twin of the main-pass pipeline; empty until the
    // first Wireframe frame. See [`super::wireframe`].
    pub(super) wireframe: super::wireframe::DxWireframe,

    // Auto-exposure (EV adaptation) state. See [`AutoExposureState`].
    pub(super) auto_exposure: AutoExposureState,

    // Per-pass GPU timestamp queries. Read at the top of `draw_frame` after
    // the matching fence wait so the CPU sees a fully committed block.
    pub(super) timestamps: TimestampState,

    // Shader hot-reload state. See [`HotReloadState`].
    pub(super) hot_reload: HotReloadState,
    // The world default Shader's compiled programs, `None` for the engine's
    // own. Kept past init so the built-in shader reload rebuilds bucket 0 from
    // the world's pair rather than the engine's.
    pub(super) world_shader: Option<concinnity_core::components::ShaderPrograms>,

    // Fixed descriptor-heap slots for the live-toggleable Quality effects (TAA /
    // SSAO / SSR / SSGI / RT-reflection output). Minted once at init (the slots
    // are reserved unconditionally) and stashed so `apply_quality_settings` can
    // build a launched-off feature into its slot without re-deriving the heap
    // layout.
    pub(super) quality_slots: super::quality::QualitySlotHandles,

    // Scene-captured reflection probes. See [`ProbeState`].
    pub(super) probe: ProbeState,

    // Device, queue, allocator and window. Declared last so every resource
    // above releases before the device and the window go.
    pub(super) hw: DxHardware,
}

// uniforms.view_ubo_ptrs are host-mapped and only touched on the render thread.
// text_upload's RefCells + map pointers are single-threaded.
// SAFETY: `DxContext` owns COM objects and host-mapped pointers that are only ever touched from the
// thread that built it, which `debug_assert_main_thread` enforces at every mutation entry point.
// Moving the whole context to another thread is therefore safe as long as it stays main-thread-only
// there, and nothing in it is shared across threads (hence `Send` without `Sync`).
unsafe impl Send for DxContext {}

// Win32 thread id of the thread that built the context. `DxContext::new` runs
// on the main thread and records it here; `debug_assert_main_thread` checks
// every mutation entry point against it.
static MAIN_THREAD_ID: OnceLock<u32> = OnceLock::new();

// Record the calling thread as the main (render) thread. Called once from
// `DxContext::new`, which always runs on the main thread.
pub(super) fn record_main_thread() {
    // SAFETY: a read of the calling thread's own id; it borrows nothing.
    let _ = MAIN_THREAD_ID.set(unsafe { GetCurrentThreadId() });
}

// Debug-only guard that the caller is on the main thread.
//
// The `unsafe impl Send for DxContext` above is sound only because the context
// is touched from the main thread alone: the Win32 window message pump and
// D3D12 command-queue submission are both thread-affine, and the parallel
// encoder fan-out only ever shares `&self` read-only. The `RenderBackend`
// mutation entry points (reached through the boxed trait object) had nothing
// proving this, so scheduling `GraphicsSystem` off the main thread would
// silently race the window/queue instead of failing. This makes that mistake
// panic loudly in debug builds and compiles to nothing in release. `entry` is
// the offending method name, for the message. Mirrors
// `metal/context.rs::debug_assert_main_thread`.
#[inline]
#[track_caller]
pub(super) fn debug_assert_main_thread(entry: &str) {
    debug_assert!(
        MAIN_THREAD_ID
            .get()
            // SAFETY: a read of the calling thread's own id; it borrows nothing.
            .is_none_or(|&main| unsafe { GetCurrentThreadId() } == main),
        "{entry} must be called from the main thread: DxContext is main-thread-only \
         (see `unsafe impl Send for DxContext`); driving GraphicsSystem off the main \
         thread races the Win32 window + D3D12 command submission",
    );
}

impl DxContext {
    pub(crate) fn draw_frame(&mut self, params: FrameParams<'_>) -> error::RenderResult<()> {
        let FrameParams {
            elapsed,
            fov_y_radians,
            near,
            view_distance,
            cam_pos,
            text_calls,
            lines,
            world_hidden,
            view_mode,
            show,
            sky_rot,
            history_reset,
        } = params;
        // Snapped for the passes recorded below (the wireframe pipeline
        // variant, the unlit shade flag, the composite's channel visualization
        // + depth normalization) and for the graph-input mask in record_frame.
        self.state.view.mode = view_mode;
        self.state.view.show = show;
        self.state.view.near = near;
        self.state.view.view_distance = view_distance;
        self.state.view.sky_rot = sky_rot;
        self.apply_pending_rebuilds()?;
        if history_reset {
            self.reset_temporal_history();
        }

        let frame = self.current_frame;

        let gpu_wait = self.wait_frame_slot(frame)?;
        // Staged geometry writes go ahead of everything this frame submits.
        self.flush_geometry_uploads()?;
        self.service_background_work(elapsed, frame);
        let timings = self.read_gpu_timings(frame);
        self.begin_frame_stats(&gpu_wait, timings);

        // Flush any D3D12 validation messages from the previous frame.
        self.flush_validation();

        // Frame command-list pipeline (parallel encoding):
        //
        //   start_cmd  : pre-init timestamps only (closed up-front)
        //   per-pass   : one cmd list per non-composite pass, recorded
        //                in parallel by rayon workers inside execute_graph
        //   end_cmd    : Composite + final timestamp + ResolveQueryData
        //                 + per-frame restore barriers (composed by
        //                 execute_graph's main-thread composite arm + the
        //                 tail of record_frame)
        //
        // ExecuteCommandLists is called once with the whole topological
        // sequence so the GPU sees them in submission order.
        let start_cmd = self.record_frame_start(frame)?;

        // Line resources: built on the first frame that publishes lines, so
        // the graph gate inside `record_frame` can see them live this same
        // frame and a world that never draws a line never compiles them.
        self.ensure_line_pipeline(!lines.is_empty());

        self.update_shadow_schedule(cam_pos, fov_y_radians, near, view_distance);
        // Reflection-probe count + records into this frame's ring CBV and records
        // buffer, which every probe-reading pass binds. A ring (one of each per
        // frame) so this write never races a prior frame's in-flight GPU read.
        self.upload_probe_set(frame)?;
        // The material parameter table's copy for this frame, after a change.
        if let Some(params) = self.cull.material_params.as_mut() {
            params.upload(frame);
        }

        // 2. Open the END cmd list (Composite + final timestamp +
        //    ResolveQueryData + per-frame restore barriers). The
        //    executor's main-thread Composite arm encodes onto this
        //    cmd list; `close_end_list` appends the final timestamp +
        //    resolve after `record_frame` returns.
        // SAFETY: the fence for this frame slot was already waited on, so no submission still
        // references what is being reset.
        unsafe { self.commands.end_command_allocators[frame].Reset() }
            .map_err(|e| super::error::map_hresult(e.code(), "end allocator reset"))?;
        let end_cmd = &self.commands.end_command_lists[frame];
        // SAFETY: the fence for this frame slot was already waited on, so no submission still
        // references what is being reset.
        unsafe { end_cmd.Reset(&self.commands.end_command_allocators[frame], None) }
            .map_err(|e| super::error::map_hresult(e.code(), "end cmd reset"))?;

        // SAFETY: a property query on a live COM object; it only reads.
        let back_idx = unsafe { self.swapchain.handle.GetCurrentBackBufferIndex() } as usize;
        let back_buffer = self.swapchain.back_buffers[back_idx].clone();
        // SAFETY: a property query on a live descriptor heap; it only reads.
        let rtv_base = unsafe { self.swapchain.rtv_heap.GetCPUDescriptorHandleForHeapStart() };
        let back_buffer_rtv = D3D12_CPU_DESCRIPTOR_HANDLE {
            ptr: rtv_base.ptr + back_idx * self.swapchain.rtv_descriptor_size,
        };

        // 3. record_frame fans non-composite passes onto rayon workers
        //    (each records into its own cmd list from the per-pass pool)
        //    and dispatches Composite + per-frame restore barriers onto
        //    `end_cmd`. Returns the per-pass cmd lists in topological
        //    pass order.
        let recorded = self.record_frame(
            crate::directx::draw::RecordFrameTargets {
                cmd: end_cmd,
                back_buffer: &back_buffer,
                back_buffer_rtv,
                frame_idx: frame,
            },
            crate::directx::draw::RecordFrameView {
                elapsed,
                fov_y_radians,
                near,
                view_distance,
                cam_pos,
                text_calls,
                lines,
            },
            crate::directx::draw::RecordFrameResolution {
                width: self.targets.extent.render_width.max(1),
                height: self.targets.extent.render_height.max(1),
                output_width: self.targets.extent.output_width.max(1),
                output_height: self.targets.extent.output_height.max(1),
            },
            world_hidden,
        )?;

        // Step the TAA accumulation ring: what this frame wrote is next frame's
        // history. After `record_frame` rather than inside it, so the write slot
        // is stable across the whole graph, and here rather than beside the
        // jitter tick because stepping the ring needs `&mut self`.
        if let Some(taa) = self.taa.as_mut() {
            taa.pass.advance();
        }
        if let Some(ssgi) = self.ssgi.as_mut() {
            ssgi.advance();
        }

        self.finish_frame_stats();
        let submitted = self.close_end_list(frame).and_then(|()| {
            self.submit_and_present(
                start_cmd,
                &recorded.pass_cmd_lists,
                back_idx,
                frame,
                gpu_wait,
            )
        });
        // A frame that took the history prime but never reached the GPU leaves
        // the ring unwritten, so the next frame primes instead.
        if submitted.is_err() && recorded.primed_model_history {
            self.state.model_history.get_mut().request_prime();
        }
        submitted
    }

    // Drain any queued D3D12 validation messages and emit them via tracing.
    pub(super) fn flush_validation(&self) {
        if let Some(ref iq) = self.hw.info_queue {
            drain_info_queue(iq);
        }
    }

    // Render statistics for the most recent `draw_frame`, for the profiler
    // overlay. `gpu_frame_us` is filled at the top of each `draw_frame` from
    // the timestamp pair this slot resolved on its previous trip through the
    // ring (so a `FRAMES`-stale window, matching Metal's "frame or two
    // stale" reading).
    pub(crate) fn render_stats(&self) -> profile::RenderStats {
        self.diagnostics.frame_stats.get()
    }

    // Current GPU memory residency in bytes. `Local` is the dedicated VRAM
    // budget on a discrete GPU and the local-process system-memory budget on
    // an integrated GPU; either way, `CurrentUsage` is what the HUD's
    // "VRAM N MB" chip reports. Zero when the adapter does not expose the
    // v3 interface (pre-WDDM 2.0).
    pub(super) fn query_vram_bytes(&self) -> u64 {
        let Some(adapter) = self.hw.adapter.as_ref() else {
            return 0;
        };
        let mut info = windows::Win32::Graphics::Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO::default();
        // 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.
        unsafe {
            adapter.QueryVideoMemoryInfo(
                0,
                windows::Win32::Graphics::Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL,
                &mut info,
            )
        }
        .map_or(0, |_| info.CurrentUsage)
    }

    // Shared atomic clone of the shader-reload flag, or `None` when the
    // context was built without hot-reload. Surfaced through the
    // `RenderBackend` trait so the debug server's
    // `reload-shaders` command can flip it from a non-render thread.
    pub(crate) fn shader_reload_pending(
        &self,
    ) -> Option<std::sync::Arc<std::sync::atomic::AtomicBool>> {
        self.hot_reload
            .reload_pending
            .as_ref()
            .map(std::sync::Arc::clone)
    }

    // True when the render graph should include `PassId::Raymarch`. Wraps
    // the `raymarch.any_visible()` check so callers don't have to know
    // the resource is `Option`. Drives `FrameGraphInputs::raymarch_enabled`
    // in `record_frame::seed_inputs`.
    pub(super) fn raymarch_enabled(&self) -> bool {
        self.raymarch
            .as_ref()
            .map(|r| r.any_visible())
            .unwrap_or(false)
    }

    // True when the render graph should include `PassId::RtReflections` (and
    // omit `SsrResolve`). Both the resolve resources and the acceleration
    // structure must be live; either being absent (DXR unsupported, DXC missing,
    // accel build failed, or an empty scene) falls the graph back to SSR. Drives
    // `FrameGraphInputs::rt_reflections_enabled` in `record_frame::seed_inputs`
    // and the `scene_srv_for_post` precedence.
    pub(super) fn rt_reflections_active(&self) -> bool {
        self.reflection_path().rt_trace
    }

    // Which reflection stages run this frame, from the authored SSR resolve and
    // the live RT pass and BVH. This backend reads the composite's output only
    // while a resolve writes it, so the RT node never runs without a BVH.
    pub(super) fn reflection_path(&self) -> ReflectionPath {
        ReflectionPath::new(
            self.ssr.as_ref().is_some_and(|s| s.resolve.is_some()),
            self.rt_reflections.is_some(),
            self.rt.accel.is_some(),
        )
    }

    // True when a reflection resolve (SSR resolve or RT reflections) runs this
    // frame. RT takes precedence at the graph level, so at most one resolve
    // runs; either feeds the same composite. Single-sources the predicate that
    // `scene_srv_for_post` and the glass pass use to pick the scene-with-
    // reflections target, and that the forward shader reads (via
    // `ViewUniforms::reflections_enabled`) to hand glossy dielectric specular to
    // that resolve instead of double-counting the forward probe reflection.
    pub(super) fn reflection_resolve_active(&self) -> bool {
        self.reflection_path().resolves()
    }

    // The single-sample scene target the render graph drives as `hdr_resolve`:
    // the resolve target with MSAA on, `hdr.color` itself with MSAA off. Every
    // pass that writes the spine finds it already in RENDER_TARGET, so a pass
    // that additionally needs it in some other state (the MSAA resolve, a
    // refraction snapshot) transitions from there and back within its own body.
    pub(in crate::directx) fn hdr_scene_target(&self) -> &ID3D12Resource {
        self.targets
            .hdr
            .resolve
            .as_ref()
            .unwrap_or(&self.targets.hdr.color)
    }

    // Render-target view of the spine `hdr_scene_target` returns. Every
    // decoration pass on the hdr_resolve chain binds this as its sole RTV.
    pub(in crate::directx) fn hdr_scene_rtv(&self) -> D3D12_CPU_DESCRIPTOR_HANDLE {
        match self.targets.hdr.resolve_rtv {
            Some(rtv) => rtv,
            None => self.targets.hdr.color_rtv,
        }
    }

    // The frame's unlit flag for ViewUniforms, from the viewport view mode.
    pub(super) fn shade_mode(&self) -> f32 {
        if self.state.view.mode == concinnity_core::gfx::view_modes::ViewMode::Unlit {
            1.0
        } else {
            0.0
        }
    }

    // True when the transparent pass traces a per-pixel RT reflection this frame:
    // RT is live AND every live producer's RT pipelines built (DXR + DXC).
    // Single-sources the decision so the two consumers agree: `encode_transparent`
    // selects the RT trace, and `graph_exec` skips the planar mirror re-render (RT
    // supersedes planar). They MUST gate on the same predicate -- if RT is live but
    // a producer's RT pipelines failed to build, that producer falls back to the
    // probe/planar path, so the planar resolve must still be rendered for it to
    // sample (gating the skip on `rt_reflections_active()` alone would leave it
    // sampling a stale resolve).
    pub(super) fn rt_transparent_active(&self) -> bool {
        self.rt_reflections_active()
            && self
                .transparent
                .as_ref()
                .is_some_and(|t| t.rt_pipelines_ready())
    }

    // True when the transparent pass samples planar mirrors, which puts the
    // `PlanarReflection` node in the graph. Water takes the mirror over its own
    // trace wherever it holds a slot (see `water.hlsl`), so a visible water
    // surface keeps the mirrors alive even while the trace is live; a glass-only
    // world under a live trace skips them. Shared with the other backends through
    // `planar_reflection::planar_pass_needed`.
    pub(super) fn planar_pass_needed(&self) -> bool {
        planar_reflection::planar_pass_needed(
            self.planar_reflection.is_some(),
            self.transparent
                .as_ref()
                .is_some_and(|t| t.water_planar_slot_live()),
            self.rt_transparent_active(),
        )
    }

    // True when the render graph should include `PassId::Transparent`. Wraps
    // the `transparent.any_visible()` check plus this frame's see-through mesh
    // visibility, which lives in `draw.objects` rather than in a static record;
    // drives `FrameGraphInputs::transparent_enabled` in
    // `record_frame::seed_inputs`.
    pub(super) fn transparent_enabled(&self) -> bool {
        self.transparent.as_ref().is_some_and(|t| t.any_visible()) || self.mesh_glass_visible()
    }

    // Whether a material opted into Layer 2 see-through glass AND the device can
    // drive it (the mesh pipelines built). Independent of `rt.accel`, so it
    // answers "would the see-through path run if RT is on" -- used at the RT-BLAS
    // build, which must exclude the meshes it will reroute before the
    // acceleration structure it gates on exists. Data-driven: see-through is
    // opt-in per `Material::see_through`, so a scene with no see-through material
    // never engages Layer 2 and its transparent glass stays Layer 1 (opaque, low
    // roughness, reflective).
    pub(super) fn seethrough_meshes_enabled(&self) -> bool {
        self.transparent
            .as_ref()
            .is_some_and(|t| t.mesh_pipelines_ready())
    }

    // Whether the see-through mesh (Layer 2) path is live this frame: the
    // pipelines built AND the pass can trace (`rt_transparent_active`, which
    // needs the TLAS). When false, those meshes render opaque + reflective in the
    // main pass (Layer 1) and the producer / opaque-skip / BLAS-exclude all stay
    // inert. Mirrors `MtlContext::mesh_glass_active`.
    pub(super) fn mesh_glass_active(&self) -> bool {
        self.seethrough_meshes_enabled() && self.rt_transparent_active()
    }

    // Whether any see-through mesh would actually draw this frame. Only then does
    // the mesh producer contribute, so the graph's Transparent node is not
    // scheduled for a world whose glass is all hidden or evicted.
    fn mesh_glass_visible(&self) -> bool {
        self.mesh_glass_active()
            && self.transparent.as_ref().is_some_and(|t| {
                t.seethrough_mesh_indices().iter().any(|&i| {
                    self.state
                        .draw
                        .objects
                        .get(i)
                        .is_some_and(|o| o.visible && o.resident)
                })
            })
    }

    // Bump this frame's CPU-issued draw-call counter. Called from each draw
    // site in the shadow, main, decal, composite, and text passes. Mirrors
    // `MtlContext::frame_stats.draw_calls += 1`; fullscreen post-process
    // passes (SSAO, SSR, TAA, bloom) are not counted per the `RenderStats`
    // doc comment.
    pub(super) fn inc_draw_calls(&self, n: u32) {
        // Bump the atomic accumulator so worker threads encoding in
        // parallel don't race. Drained into `diagnostics.frame_stats.draw_calls`
        // by `draw_frame` at the end of every frame.
        self.diagnostics
            .draw_calls_accum
            .fetch_add(n, std::sync::atomic::Ordering::Relaxed);
    }
}

impl DxContext {
    // The window state. Always `Some` on a live context; `None` only on the
    // outgoing context of a `reload_world` (which has moved the window into its
    // successor and calls no window method afterward), so the unwrap never fires.
    #[inline]
    pub(super) fn win(&self) -> &WindowState {
        self.hw
            .win_state
            .as_ref()
            .expect("DxContext window state present")
    }

    #[inline]
    pub(super) fn win_mut(&mut self) -> &mut WindowState {
        self.hw
            .win_state
            .as_mut()
            .expect("DxContext window state present")
    }

    pub(crate) fn window_closed(&mut self) -> bool {
        // Message pump + cursor window-exit / fullscreen-confinement refresh +
        // the Resolution-mode reconcile, shared with the Vulkan Windows window.
        // Partial field borrow (not `win_mut`) so `fullscreen_display` can be
        // borrowed disjointly in the same call.
        frame_tick(
            self.hw
                .win_state
                .as_mut()
                .expect("DxContext window state present"),
            &mut self.hw.fullscreen_display,
        )
    }

    // Submit every staged geometry write. Queue order puts the copies ahead of
    // any later submission, so nothing waits on them.
    pub(super) fn flush_geometry_uploads(&self) -> error::RenderResult<()> {
        self.geometry_uploads.borrow_mut().flush(
            &self.hw.device,
            &self.hw.command_queue,
            &GeometryDest {
                vertex: &self.scene.geometry.vertex_buffer,
                index: &self.scene.geometry.index_buffer,
            },
        )
    }

    pub(crate) fn wait_idle(&self) {
        // Staged geometry writes count as submitted work, so an idle GPU has
        // applied them.
        if let Err(e) = self.flush_geometry_uploads() {
            tracing::error!("geometry upload submit failed: {e}");
        }
        // Signal a new fence value and wait until the GPU reaches it.
        let val = self.frame_sync.next_fence_value.get();
        self.frame_sync.next_fence_value.set(val + 1);
        // SAFETY: the fence and the event were created from this device and are live for the call.
        if unsafe { self.hw.command_queue.Signal(&self.frame_sync.fence, val) }.is_ok()
            // SAFETY: the fence and the event were created from this device and are live for the
            // call.
            && unsafe { self.frame_sync.fence.GetCompletedValue() } < val
            // SAFETY: the fence and the event were created from this device and are live for the
            // call.
            && let Ok(()) = unsafe {
                self.frame_sync
                    .fence
                    .SetEventOnCompletion(val, self.frame_sync.fence_event)
            }
        {
            // SAFETY: the event handle was created in `DxContext::new` and lives as long as the
            // context, and the wait borrows nothing else.
            unsafe { WaitForSingleObject(self.frame_sync.fence_event, u32::MAX) };
        }
    }

    pub(crate) fn request_cursor_capture(&mut self) {
        // Don't grab the cursor immediately. A freshly spawned window may not be
        // focused yet, and clipping + hiding the system cursor before the user
        // has interacted with the window is jarring; it also diverges from the
        // Vulkan/GLFW backend, where a disabled cursor only engages once the
        // window gains focus. Instead arm the click-to-capture path: the first
        // left-click in the content area grabs the cursor, the same as
        // recapturing after Escape or a focus loss (see `wnd_proc`'s
        // `WM_LBUTTONDOWN` arm).
        self.win_mut().recapture_on_click = true;
    }

    // Hide or show the OS cursor for an in-engine UI cursor (e.g. a MainMenu),
    // without engaging camera capture. Edge-triggered in the helper, so calling
    // it every frame with the same value is cheap.
    pub(crate) fn set_ui_cursor_hidden(&mut self, hidden: bool) {
        window::set_ui_cursor_hidden(self.win_mut(), hidden);
    }

    // Whether the real cursor has left the window so the renderer should stop
    // drawing the in-engine UI cursor (windowed / borderless). Recomputed each
    // frame by `update_ui_cursor_confinement` in `window_closed`; false while
    // captured or in fullscreen (which confines the cursor instead).
    pub(crate) fn cursor_outside_window(&self) -> bool {
        self.win().cursor_outside_window
    }

    // A togglable menu coexists with a captured camera; see
    // `RenderBackend::set_menu_mode`. The wnd_proc reads this flag to route
    // Escape to the ECS and suppress click-to-recapture.
    pub(crate) fn set_menu_mode(&mut self, on: bool) {
        self.win_mut().menu_mode = on;
    }

    // Edge-triggered capture: capture for camera control, release while a menu
    // is open. GraphicsSystem calls this each frame in menu mode. Unlike the
    // startup `request_cursor_capture` (which arms click-to-capture), closing the menu
    // recaptures immediately so the camera resumes without an extra click.
    pub(crate) fn set_camera_capture(&mut self, capture: bool) {
        if capture == self.win().cursor_captured {
            return;
        }
        if capture {
            let hwnd = self.win().hwnd;
            window::capture_cursor(hwnd, self.win_mut());
        } else {
            window::release_cursor(self.win_mut());
        }
    }

    // Turn display sync (vsync) on or off at runtime. Only the present sync
    // interval changes (1 = lock to refresh, 0 = uncapped); the present flags
    // gate ALLOW_TEARING on this interval. The swapchain's ALLOW_TEARING flag
    // is fixed at creation, so true tearing is available only when the
    // swapchain was created with vsync off; turning vsync off later still
    // presents uncapped (interval 0) but without the tearing flag if the
    // swapchain lacks it.
    pub(crate) fn set_vsync(&mut self, on: bool) {
        self.swapchain.present_sync_interval = if on { 1 } else { 0 };
    }

    // Switch window mode / resize at runtime (windowed / borderless / fullscreen
    // and content-size presets). The Win32 work lives in `window.rs`; the resize
    // path picks up the resulting WM_SIZE.
    pub(crate) fn set_window_mode(&mut self, mode: components::WindowMode) {
        window::set_window_mode(self.win_mut(), mode);
    }

    pub(crate) fn set_window_size(&mut self, width: u32, height: u32) {
        window::set_window_size(self.win_mut(), width, height);
    }

    // The display modes (resolution + refresh rate) of the monitor the window
    // sits on, feeding the Resolution settings row (the caller dedups + sorts).
    pub(crate) fn display_modes(&self) -> Vec<display_mode::DisplayMode> {
        crate::win32::display_mode::enumerate(self.win().hwnd)
    }

    // The mode the window's monitor is currently running (what the Resolution
    // row shows before the user ever picks one).
    pub(crate) fn current_display_mode(&self) -> Option<display_mode::DisplayMode> {
        crate::win32::display_mode::current(self.win().hwnd)
    }

    // Remember the display mode to hold while the window is in fullscreen.
    // Applied by the per-frame reconcile in `window_closed` (which also
    // restores the desktop mode on leaving fullscreen), so a choice made in
    // any window mode takes effect when fullscreen is (or becomes) active.
    pub(crate) fn set_display_mode(&mut self, mode: display_mode::DisplayMode) {
        self.hw.fullscreen_display.set_desired(mode);
    }

    // Replace the live post-process tunables, pushed to the bloom + composite
    // shaders each frame. The composite's display-output flags are not part of
    // the payload, so the EDR path negotiated at init survives every push.
    pub(crate) fn update_post_process(&mut self, tunables: render_types::PostProcessTunables) {
        self.post_process.set_tunables(tunables);
    }

    // Set the live ambient (IBL) light scale (the Ambient slider). It lives in
    // `LightUniforms`, which rides a per-frame-in-flight CBV ring, so this
    // mutates the CPU-side copy and re-arms every slot; `record_frame` writes
    // the frame's own slot. Edge-triggered: a no-op when the value is unchanged
    // (e.g. an init push with no persisted override).
    pub(crate) fn set_ambient_intensity(&mut self, value: f32) {
        if self.uniforms.light_uniforms.ambient_intensity == value {
            return;
        }
        self.uniforms.light_uniforms.ambient_intensity = value;
        self.uniforms.mark_lights_dirty();
    }

    // Replace the live directional lights. The cascade shadow direction and the
    // fog sun are derived from the first light on the CPU, so both are
    // re-derived here. Edge-triggered: an unchanged set touches nothing, and a
    // changed one only re-arms the light CBV ring.
    pub(crate) fn update_directional_lights(&mut self, lights: &[components::DirectionalLight]) {
        let (directional, num_directional) = lights::directional_light_data(lights);
        let uniforms = &mut self.uniforms.light_uniforms;
        if uniforms.directional == directional && uniforms.num_directional == num_directional {
            return;
        }
        uniforms.directional = directional;
        uniforms.num_directional = num_directional;
        self.shadow.light_dir = lights::sun_direction(&self.uniforms.light_uniforms);
        self.fog.sun_dir = self.shadow.light_dir;
        self.fog.sun_color = lights::sun_color(&self.uniforms.light_uniforms);
        self.uniforms.mark_lights_dirty();
    }

    pub(crate) fn set_shadow_cadence(&mut self, cadence: backend_init::ShadowCadence) {
        self.shadow.cadence = cadence;
    }

    // Update the live scalar sub-tunables of the SSAO / SSR / SSGI / auto-exposure
    // passes without rebuilding anything. Each pass rebuilds its per-frame uniform
    // from these stored `*Settings` every draw (`settings.params(...)`), so
    // mutating the stored struct here is picked up on the next frame. Only a
    // feature whose resources are currently live has settings to mutate; the rest
    // are skipped (the value still persists for the next launch). SSAO / SSR /
    // auto-exposure are fully scalar, so they are replaced wholesale; SSGI's trace
    // resolution sizes its targets and rides `apply_quality_settings` with its ray
    // count, so only its scalar intensity / distance are updated. The SSR settings live one level deeper than Metal's (inside the
    // optional `resolve` half), so a SSGI-only build with no resolve is skipped.
    pub(crate) fn update_quality_params(&mut self, q: backend::QualitySettings) {
        if let (Some(live), Some(res)) = (q.ssao, self.ssao.resources.as_mut()) {
            res.settings = live;
        }
        if let (Some(live), Some(res)) = (q.ssr, self.ssr.as_mut())
            && let Some(r) = res.resolve.as_mut()
        {
            r.settings = live;
        }
        if let (Some(live), Some(res)) = (q.ssgi, self.ssgi.as_mut()) {
            res.settings.intensity = live.intensity;
            res.settings.max_distance = live.max_distance;
        }
        if let (Some(live), Some(cur)) = (q.auto_exposure, self.auto_exposure.adaptation.as_mut()) {
            cur.settings = live;
        }
    }

    // Replace the runtime movement key map. The window message loop decodes
    // key events through it, so a settings-menu rebind takes effect immediately.
    pub(crate) fn set_keymap(&mut self, keymap: &KeyMap) {
        self.win_mut().key.set_keymap(keymap);
    }

    pub(crate) fn take_input(&mut self) -> InputSnapshot {
        take_input_snapshot(self.win_mut())
    }

    // Live window size for overlay (view-owned UI) scaling and cursor
    // hit-testing. Returns the drawable (swapchain) pixel size, which is the
    // attachment the composite + text pass writes and the space the UI shader
    // divides vertices by; WM_MOUSEMOVE reports the cursor in the same client
    // pixels, so the overlay forward / inverse transforms stay consistent.
    pub(crate) fn logical_size(&self) -> (f32, f32) {
        (
            self.targets.extent.output_width as f32,
            self.targets.extent.output_height as f32,
        )
    }

    // Device capability flags for the settings menu. RT reflects the DXR-tier
    // query made at init (`hw.rt_capable`).
    pub(crate) fn capabilities(&self) -> backend::DeviceCapabilities {
        backend::DeviceCapabilities {
            ray_tracing: self.hw.rt_capable,
            selectable_upscaler: true,
            // The cull BVH + RT tables key fixed build-time slot indices and
            // cannot refit; only the runtime-append region recycles (tracked
            // as the RT incremental topology parity item).
            reuses_build_slots: false,
            // Per-object material state is baked into the GPU records at build
            // time, so a slot rewrite in `SceneState` would not reach the frame.
            rewrites_draws: false,
        }
    }

    // Coarse GPU performance profile for default-quality selection, read live
    // from the adapter description (vendor id + dedicated VRAM). `UNKNOWN` when
    // the adapter does not expose the v3 interface or the desc query fails.
    pub(crate) fn gpu_profile(&self) -> backend::GpuProfile {
        use concinnity_core::render::backend::{
            GpuClassInput, GpuProfile, GpuVendor, classify_tier,
        };
        let Some(adapter) = self.hw.adapter.as_ref() else {
            return GpuProfile::UNKNOWN;
        };
        // SAFETY: a property query on a live COM object; it only reads.
        let desc = match unsafe { adapter.GetDesc1() } {
            Ok(d) => d,
            Err(_) => return GpuProfile::UNKNOWN,
        };
        let vendor = match desc.VendorId {
            0x10DE => GpuVendor::Nvidia,
            0x1002 => GpuVendor::Amd,
            0x8086 => GpuVendor::Intel,
            _ => GpuVendor::Other,
        };
        let dedicated = desc.DedicatedVideoMemory as u64;
        // A discrete GPU has dedicated VRAM; an integrated part reports little or
        // none (and large shared system memory). A small floor keeps a few MB of
        // carve-out from reading as discrete.
        let discrete = dedicated >= (256u64 << 20);
        let tier = classify_tier(&GpuClassInput {
            vendor,
            memory_budget_bytes: dedicated,
            discrete,
            apple_family: 0,
        });
        GpuProfile {
            vendor,
            tier,
            memory_budget_bytes: dedicated,
            unified_memory: !discrete,
            discrete,
        }
    }
}

impl scene_flow::SceneControl for DxContext {
    fn update_visibility(&mut self, draw_idx: DrawIndex, visible: bool) {
        self.state.update_visibility(draw_idx, visible);
    }
    fn set_fade(&mut self, fade: f32) {
        self.state.set_fade(fade);
    }
}

impl Drop for DxContext {
    fn drop(&mut self) {
        self.wait_idle();
        // Persist and release the pipeline library. `win_state` is `None` only
        // on the outgoing context of a `reload_world`, whose successor keeps
        // the device and the installed library.
        if self.hw.win_state.is_some() {
            super::pso_library::shutdown();
            // Also writes whatever shader artifacts were compiled lazily since
            // init's own checkpoint.
            crate::shader::runtime_cache::checkpoint();
        }
        // Restore cursor clip + visibility so the OS isn't left in a bad state
        // if the caller didn't release explicitly. `None` on the outgoing context
        // of a `reload_world` (the window moved to its successor), so guard it.
        if let Some(ws) = self.hw.win_state.as_mut() {
            window::release_cursor(ws);
        }
        // Unmap persistent CBV mappings (view + shadow).
        self.uniforms.unmap();
        self.light_cull.unmap();
        // SAFETY: the event was created in `DxContext::new`, is closed exactly once here, and
        // `wait_idle` at the top of `drop` retired every wait that used it.
        unsafe { CloseHandle(self.frame_sync.fence_event) }.ok();
        // The remaining COM objects (device, swapchain, heaps, etc.) are reference-
        // counted and released automatically when the struct fields are dropped.
    }
}

// Standalone version of the per-frame flush_validation so init paths can dump
// validation messages before bailing; without this, PSO/root-sig failures
// surface only as the bare `E_INVALIDARG` HRESULT from CreateGraphicsPipelineState.

pub(super) fn drain_info_queue(iq: &ID3D12InfoQueue) {
    // SAFETY: a property query on a live COM object; it only reads.
    let count = unsafe { iq.GetNumStoredMessages() };
    for i in 0..count {
        let mut len = 0usize;
        // SAFETY: `iq` is live and a null message pointer asks for the message
        // size alone, which lands in the live local `len`.
        if unsafe { iq.GetMessage(i, None, &mut len) }.is_err() {
            continue;
        }
        // A D3D12_MESSAGE is variable length: the fixed header followed by the
        // description text it points into. Back it with u64s rather than bytes so
        // the header lands on the alignment the struct needs.
        if len < std::mem::size_of::<D3D12_MESSAGE>() {
            continue;
        }
        let mut buf = vec![0u64; len.div_ceil(std::mem::size_of::<u64>())];
        let msg_ptr = buf.as_mut_ptr() as *mut D3D12_MESSAGE;
        // SAFETY: `iq` is live, `len` is the size it just reported, and `msg_ptr`
        // addresses a live allocation of at least that many bytes.
        if unsafe { iq.GetMessage(i, Some(msg_ptr), &mut len) }.is_err() {
            continue;
        }
        // SAFETY: `GetMessage` filled `buf` with a message at least as long as the
        // header, and the u64 backing store is aligned for it. The borrow ends
        // before `buf` is dropped at the end of the iteration.
        let msg = unsafe { &*msg_ptr };
        let text = if msg.pDescription.is_null() {
            "(no description)".to_owned()
        } else {
            // SAFETY: `pDescription` is the non-null, NUL-terminated description
            // D3D12 wrote into `buf` alongside the header, so it stays live for
            // the copy this makes.
            unsafe { std::ffi::CStr::from_ptr(msg.pDescription as *const i8) }
                .to_string_lossy()
                .into_owned()
        };
        match msg.Severity {
            D3D12_MESSAGE_SEVERITY_CORRUPTION | D3D12_MESSAGE_SEVERITY_ERROR => {
                tracing::error!(target: "d3d12", "{text}");
            }
            D3D12_MESSAGE_SEVERITY_WARNING => {
                tracing::warn!(target: "d3d12", "{text}");
            }
            _ => {
                tracing::debug!(target: "d3d12", "{text}");
            }
        }
    }
    // SAFETY: `iq` is live and every message read above has been copied out.
    unsafe { iq.ClearStoredMessages() };
}

// Wrap an init-path Result so that any D3D12 validation messages queued
// during the failing op are dumped to tracing before the error bubbles up.
pub(super) fn dump_on_err<T, E>(
    info_queue: Option<&ID3D12InfoQueue>,
    r: Result<T, E>,
) -> Result<T, E> {
    if r.is_err()
        && let Some(iq) = info_queue
    {
        drain_info_queue(iq);
    }
    r
}