concinnity-device 0.18.66

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
// src/directx/quality.rs
//
// Runtime application of the Quality-group settings (TAA / SSAO / SSR / SSGI /
// auto-exposure). Each gates a render pass whose GPU resources (pipelines,
// render targets) are built once at init from the world's PostProcessConfig, so
// applying a change at runtime means building or tearing down those resources.
//
// Unlike the Vulkan backend, DirectX picks its scene-input + occlusion sources
// DYNAMICALLY every frame (`scene_srv_for_post`, `ssao_ao_srv_gpu`, and each
// feature's render-graph gate read the live `Option` state at encode time), so a
// toggle needs no descriptor rewrite and no swapchain rebuild: it just builds the
// effect into its pre-reserved fixed heap slot (the slots are reserved
// unconditionally at init, see `init/mod.rs`) or drops it. The next frame's draw
// adapts. The one coupling is SSAO's `ao_output`, which lives in the transient
// pool only while SSAO is on and shares a heap region with `bloom_top`; toggling
// it rebuilds the pool + the bloom mip chain, mirroring the resize path.
//
// Ray-traced reflections toggle the same way, with two extra costs: turning them
// on builds the scene acceleration structure (`build_rt_accel`, a one-shot
// fence-waited BLAS + TLAS over current geometry) plus the DXR reflection pass,
// so a live enable hitches once proportional to triangle count; and RT is only
// live-toggleable on a GPU that reports the DXR 1.1 tier (queried once at init
// into `rt_capable`), else the toggle no-ops with a warning and RT stays whatever
// it launched as. The RT output reserves its fixed heap slot unconditionally like
// the other five features, so an enable builds into it without shifting any other
// slot; the dynamic `scene_srv_for_post` picks the RT output over SSR each frame,
// so no rewire or rebuild is needed.

use windows::Win32::Graphics::Direct3D12::*;

use crate::gfx::backend::QualitySettings;

use super::context::DxContext;
use super::post::bloom::{create_bloom_mips_at, write_color_rtv};
use super::post::gbuffer::GbufferSlots;
use super::post::reflection_composite::ReflectionCompositeSlots;
use super::texture::write_hdr_srv;

// The fixed descriptor-heap slots the live-toggleable effects build into. Minted
// once at init (the slots are reserved unconditionally, independent of the
// init-time quality gates) and stashed on `DxContext` so a live toggle can
// construct a launched-off feature into its slot without re-deriving the heap
// layout. The handles are stable for the context's lifetime: a resize rewrites
// the resources behind them but never moves the slots.
#[derive(Clone, Copy)]
pub(in crate::directx) struct QualitySlotHandles {
    pub taa_history_rtv: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
    pub taa_history_srv: [(D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE); 2],
    pub ssao_ao_raw_rtv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub ssao_ao_raw_srv: (D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE),
    pub ssao_ao_rtv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub ssao_ao_srv: (D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE),
    pub ssr_output_rtv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub ssr_output_srv: (D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE),
    pub ssgi_gi_rtv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub ssgi_gi_srv: (D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE),
    pub rt_output_rtv: D3D12_CPU_DESCRIPTOR_HANDLE,
    pub rt_output_srv: (D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE),
    pub refl_composite: ReflectionCompositeSlots,
    pub gbuffer: GbufferSlots,
}

impl DxContext {
    // Bring the toggle-controlled features to match `q`, applied between frames
    // (the GraphicsSystem reads the SettingCommand before the next draw_frame).
    // A build failure logs and leaves the prior state intact.
    pub(crate) fn apply_quality_settings(&mut self, q: QualitySettings) {
        if let Err(e) = self.apply_quality_settings_inner(q) {
            tracing::error!("apply_quality_settings: rebuild failed: {e}");
        }
    }

    fn apply_quality_settings_inner(&mut self, q: QualitySettings) -> Result<(), String> {
        // Every build / teardown below frees or replaces GPU resources a prior
        // frame may still reference; drain the device first so the swap is safe.
        self.wait_idle();

        let hot_reload = self.hot_reload.enabled;
        let render_w = self.extent.render_width;
        let render_h = self.extent.render_height;
        let slots = self.quality_slots;

        // RT is gated on the GPU reporting the DXR 1.1 tier: a non-DXR GPU cannot
        // build the acceleration structure, so the toggle no-ops with a warning
        // and RT stays whatever it launched as (persisted for the next launch).
        let desired_rt = q.rt_reflections.is_some() && self.rt_capable;
        if q.rt_reflections.is_some() && !self.rt_capable {
            tracing::warn!(
                "ray-traced reflections requested but the GPU does not report DXR \
                 tier 1.1; keeping SSR"
            );
        }

        let desired_ssr = q.ssr.is_some();
        let desired_ssgi = q.ssgi.is_some();
        let desired_ssao = q.ssao.is_some();
        let desired_ae = q.auto_exposure.is_some();
        // TAA resources are forced present while temporal upscaling is active
        // (the upscaler consumes the velocity pre-pass); the TAA resolve is then
        // dropped from the graph. Mirrors the init `taa_enabled` derivation.
        let upscale_on = self.upscale.backend.is_some();
        let desired_taa = q.taa || upscale_on;

        // The SSR pre-pass resources (`SsrResources`) exist whenever SSR, SSGI,
        // or RT is on (SSGI / RT reuse the SSR resolve's G-buffer plumbing); its
        // `resolve` half is built only when SSR itself is authored. The unified
        // G-buffer pre-pass is needed by any screen-space consumer (RT samples
        // its normal+depth and roughness). Mirrors the init `ssr_prepass_present`
        // / `gbuffer_enabled` gates.
        let ssr_needed = desired_ssr || desired_ssgi || desired_rt;
        let gbuffer_needed = ssr_needed || desired_ssao || desired_taa;

        // Unified G-buffer pre-pass (shared dependency): build it before any
        // consumer that samples it. Kept alive once built (a later toggle-off of
        // the last consumer leaves it resident until the next launch / resize),
        // which is harmless: with no consumer the graph omits its readers.
        if gbuffer_needed && self.gbuffer.is_none() {
            // Its three colour targets are pooled, so the pool has to place them
            // before the feature can view them. Rebuilding with the G-buffer gate
            // on also relocates `ao_output` / `bloom_top`, which the rebuild
            // re-points.
            self.rebuild_transient_pool_and_consumers(self.ssao.resources.is_some(), true)?;
            let pooled = self
                .transient_pool
                .gbuffer_pooled()
                .ok_or("transient pool missing the gbuffer colour targets after enable")?;
            let gbuffer = super::post::gbuffer::GbufferResources::new(
                super::post::gbuffer::GbufferDeviceCtx {
                    alloc: &self.alloc,
                    info_queue: self.diagnostics.info_queue.as_ref(),
                },
                super::post::gbuffer::GbufferExtent {
                    width: render_w,
                    height: render_h,
                    need_instanced: self.draw.n_clusters > 0,
                    // Skinned variant builds lazily in `upload_skinned`, as at init.
                    need_skinned: false,
                    hot_reload,
                },
                slots.gbuffer,
                &pooled,
            )?;
            self.gbuffer = Some(gbuffer);
        }

        // TAA.
        if desired_taa && self.taa.is_none() {
            let taa = super::post::taa::TaaResources::new(
                &self.device,
                render_w,
                render_h,
                slots.taa_history_rtv,
                slots.taa_history_srv,
                self.diagnostics.info_queue.as_ref(),
                hot_reload,
            )?;
            self.taa = Some(taa);
        } else if !desired_taa && self.taa.is_some() {
            self.taa = None;
        }

        // SSR pre-pass + resolve. `q.ssr` (Option) drives the resolve half:
        // `Some` builds it (SSR authored), `None` leaves it off (SSGI-only /
        // RT-only build the pre-pass but no resolve), matching init.
        if ssr_needed && self.ssr.is_none() {
            let ssr = super::post::ssr::SsrResources::new(
                &self.alloc,
                render_w,
                render_h,
                super::post::ssr::SsrInitInputs {
                    resolve_settings: q.ssr,
                    output_rtv: slots.ssr_output_rtv,
                    output_srv: slots.ssr_output_srv,
                },
                self.diagnostics.info_queue.as_ref(),
                hot_reload,
            )?;
            self.ssr = Some(ssr);
        } else if !ssr_needed && self.ssr.is_some() {
            self.ssr = None;
        }

        // SSGI (samples the unified G-buffer; `gbuffer_needed` keeps it alive).
        if desired_ssgi && self.ssgi.is_none() {
            let settings = q.ssgi.expect("desired_ssgi implies ssgi settings");
            let ssgi = super::post::ssgi::SsgiResources::new(
                super::post::ssgi::SsgiDevice {
                    alloc: &self.alloc,
                    info_queue: self.diagnostics.info_queue.as_ref(),
                },
                render_w,
                render_h,
                settings,
                super::post::ssgi::SsgiDescriptors {
                    gi_rtv: slots.ssgi_gi_rtv,
                    gi_srv: slots.ssgi_gi_srv,
                },
                hot_reload,
            )?;
            self.ssgi = Some(ssgi);
        } else if !desired_ssgi && self.ssgi.is_some() {
            self.ssgi = None;
        }

        // Ray-traced reflections. Turning on builds the scene acceleration
        // structure (one-shot, fence-waited) + the DXR pass into the fixed RT
        // output slot; the unified G-buffer it samples is built above
        // (`gbuffer_needed` folds in `desired_rt`). Turning off drops both
        // (their COM resources release on drop); `scene_srv_for_post` falls back
        // to the SSR resolve / HDR dynamically next frame, so no rewire is needed.
        if desired_rt && self.rt_reflections.is_none() {
            self.build_rt_runtime(q.rt_reflections.expect("desired_rt implies settings"))?;
        } else if !desired_rt && self.rt_reflections.is_some() {
            self.rt_reflections = None;
            self.rt_accel = None;
        }

        // Reflection composite: the on-screen target the SSR/RT resolve writes its
        // radiance+weight into, then blurs/blends over the scene by roughness.
        // Present whenever a resolve can composite (SSR resolve or RT), mirroring
        // the init `ssr_settings || rt_reflection_settings` gate, and built into the
        // unconditionally-reserved refl_composite slots. Without this reconcile a
        // live RT/SSR enable on a world that authored neither leaves it `None`, so
        // `encode_reflection_composite` early-returns and the resolve's reflection
        // is computed but never shown (`scene_srv_for_post` / glass / the forward
        // `reflections_enabled` fade all gate on its presence).
        let refl_composite_needed = desired_ssr || desired_rt;
        if refl_composite_needed && self.reflection_composite.is_none() {
            let rc = super::post::reflection_composite::ReflectionCompositeResources::new(
                &self.device,
                render_w,
                render_h,
                q.reflection_blur_scale,
                slots.refl_composite,
                self.diagnostics.info_queue.as_ref(),
                hot_reload,
            )?;
            self.reflection_composite = Some(rc);
        } else if !refl_composite_needed && self.reflection_composite.is_some() {
            self.reflection_composite = None;
        }

        // Auto-exposure. Needs no descriptor-heap slots (own root UAVs +
        // readback ring). When it turns off the static authored EV drives
        // exposure again (the GraphicsSystem re-pushes `update_post_process`
        // after this call), so only the GPU + adaptation state is swapped here.
        if desired_ae && self.auto_exposure.resources.is_none() {
            let resources =
                super::auto_exposure::AutoExposureResources::new(&self.alloc, hot_reload)?;
            self.auto_exposure.resources = Some(resources);
            self.auto_exposure.state = q
                .auto_exposure
                .as_ref()
                .map(crate::gfx::auto_exposure::AutoExposureState::new);
            self.auto_exposure.settings = q.auto_exposure;
            self.auto_exposure.bias_ev = q.auto_exposure_bias_ev;
        } else if !desired_ae && self.auto_exposure.resources.is_some() {
            self.auto_exposure.resources = None;
            self.auto_exposure.settings = None;
            self.auto_exposure.state = None;
        }

        // SSAO. Its blurred `ao_output` is a transient-pool resource that only
        // exists while SSAO is on and shares a heap region with `bloom_top`, so a
        // toggle rebuilds the pool (relocating `bloom_top` -> rebuild the bloom
        // mip chain) and, on a turn-on, constructs the SSAO resources from the
        // freshly pooled `ao_output`. The main pass's occlusion binding
        // (`ssao_ao_srv_gpu`) falls back to the 1x1 white slot when off, so a
        // turn-off needs no rewire beyond dropping the resources.
        let ssao_was = self.ssao.resources.is_some();
        let gbuffer_on = self.gbuffer.is_some();
        if desired_ssao && !ssao_was {
            self.rebuild_transient_pool_and_consumers(true, gbuffer_on)?;
            let ao_resource = self
                .transient_pool
                .resource_for("ao_output")
                .ok_or("transient pool missing ao_output after SSAO enable")?
                .clone();
            let settings = q.ssao.expect("desired_ssao implies ssao settings");
            let ssao = super::post::ssao::SsaoResources::new(
                super::post::ssao::SsaoDeviceCtx {
                    device: &self.device,
                    info_queue: self.diagnostics.info_queue.as_ref(),
                },
                render_w,
                render_h,
                settings,
                super::post::ssao::SsaoDescriptorHandles {
                    ao_raw_rtv: slots.ssao_ao_raw_rtv,
                    ao_raw_srv: slots.ssao_ao_raw_srv,
                    ao_rtv: slots.ssao_ao_rtv,
                    ao_srv: slots.ssao_ao_srv,
                },
                &ao_resource,
                hot_reload,
            )?;
            self.ssao.resources = Some(ssao);
        } else if !desired_ssao && ssao_was {
            // Drop before the pool rebuild removes the `ao_output` it points at.
            self.ssao.resources = None;
            self.rebuild_transient_pool_and_consumers(false, gbuffer_on)?;
        }

        Ok(())
    }

    // Build the RT acceleration structure + reflection pass at runtime (a live
    // toggle-on). Mirrors the init RT block: an empty scene, an AS-build error,
    // or a shader-compile failure leaves both `rt_accel` / `rt_reflections`
    // `None` and the renderer stays on SSR (a soft failure, returns `Ok`). The
    // caller has ensured the unified G-buffer pre-pass exists and drained the
    // device (`wait_idle`). The skinned BLAS is seeded on the first dynamic
    // frame, so the skin pipeline is attached here (a build failure is non-fatal:
    // static geometry still reflects, just without skinned hits).
    fn build_rt_runtime(
        &mut self,
        settings: crate::gfx::rt_reflections::RtReflectionSettings,
    ) -> Result<(), String> {
        let hot_reload = self.hot_reload.enabled;
        let mut accel = match super::raytrace::build_rt_accel(super::raytrace::RtInitGeometry {
            alloc: &self.alloc,
            vertex_buffer: &self.geometry.vertex_buffer,
            index_buffer: &self.geometry.index_buffer,
            draw_objects: &self.draw.objects,
            clusters: &self.instanced.clusters,
            total_vertices: self.rt_static_vertex_count,
            albedo_count: self.descriptors.textures.len() as u32,
            exclude_seethrough: self.seethrough_meshes_enabled(),
        }) {
            Ok(Some(accel)) => accel,
            Ok(None) => {
                tracing::info!(
                    "RT reflections enabled but no resident triangle geometry to trace; keeping SSR"
                );
                return Ok(());
            }
            Err(e) => {
                tracing::warn!("RT acceleration-structure build failed (keeping SSR): {e}");
                return Ok(());
            }
        };
        match super::raytrace::build_rt_skin_pipeline(&self.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}"
            ),
        }
        let slots = self.quality_slots;
        let rt = match super::post::rt_reflections::RtReflectionsResources::new(
            super::post::rt_reflections::RtBuildContext {
                alloc: &self.alloc,
                width: self.extent.render_width,
                height: self.extent.render_height,
            },
            settings,
            super::post::rt_reflections::RtOutputDescriptors {
                output_rtv: slots.rt_output_rtv,
                output_srv: slots.rt_output_srv,
            },
            super::post::rt_reflections::RtBuildInit {
                info_queue: self.diagnostics.info_queue.as_ref(),
                hot_reload,
            },
        ) {
            Ok(rt) => rt,
            Err(e) => {
                tracing::warn!("RT reflections pass build failed (keeping SSR): {e}");
                return Ok(());
            }
        };
        self.rt_accel = Some(accel);
        self.rt_reflections = Some(rt);
        Ok(())
    }

    // Rebuild the transient pool with the given gates (which of `ao_output` and
    // the G-buffer colour targets it places), then re-point every consumer of a
    // pooled resource. Mirrors `handle_resize`'s transient-pool + bloom +
    // G-buffer steps (the device is idle when this is reached).
    //
    // **Every** pooled consumer has to be re-pointed here, not just the one the
    // caller is toggling: a rebuild repacks the whole pool, so changing the SSAO
    // gate relocates the G-buffer's targets and vice versa. Re-pointing only the
    // toggled feature leaves the other one's descriptors naming freed memory.
    fn rebuild_transient_pool_and_consumers(
        &mut self,
        ssao_on: bool,
        gbuffer_on: bool,
    ) -> Result<(), String> {
        self.transient_pool.rebuild(
            &self.device,
            &self.command_queue,
            &super::transient_pool::transient_slots(
                ssao_on,
                gbuffer_on,
                (self.extent.render_width, self.extent.render_height),
                (self.extent.output_width, self.extent.output_height),
            )?,
        )?;
        if let Some(pooled) = self.transient_pool.gbuffer_pooled() {
            // SAFETY: a property query on a live descriptor heap; it only reads.
            let srv_cpu_base = unsafe {
                self.descriptors
                    .srv_heap
                    .GetCPUDescriptorHandleForHeapStart()
            };
            // SAFETY: a property query on a live descriptor heap; it only reads.
            let srv_gpu_base = unsafe {
                self.descriptors
                    .srv_heap
                    .GetGPUDescriptorHandleForHeapStart()
            };
            let device = self.device.clone();
            if let Some(gbuffer) = self.gbuffer.as_mut() {
                gbuffer.repoint_pooled(&device, srv_cpu_base, srv_gpu_base, &pooled);
            }
        }
        let bloom_count = self.bloom.mips.len();
        if bloom_count > 0 {
            let bloom_top = self
                .transient_pool
                .resource_for("bloom_top")
                .ok_or("transient pool missing bloom_top after rebuild")?
                .clone();
            let (mips, extents) = create_bloom_mips_at(
                &self.device,
                self.extent.output_width,
                self.extent.output_height,
                bloom_count,
                bloom_top,
            )?;
            self.bloom.mips = mips;
            self.bloom.mip_extents = extents;
            // Rewrite each mip's RTV + SRV into its existing (fixed) slot. The
            // SRV CPU handle is derived from the stored GPU handle the same way
            // the resize path does (the slot never moves).
            // SAFETY: a property query on a live descriptor heap; it only reads.
            let srv_cpu_base = unsafe {
                self.descriptors
                    .srv_heap
                    .GetCPUDescriptorHandleForHeapStart()
            };
            // SAFETY: a property query on a live descriptor heap; it only reads.
            let srv_gpu_base = unsafe {
                self.descriptors
                    .srv_heap
                    .GetGPUDescriptorHandleForHeapStart()
            };
            let srv_cpu_of = |gpu: D3D12_GPU_DESCRIPTOR_HANDLE| D3D12_CPU_DESCRIPTOR_HANDLE {
                ptr: srv_cpu_base.ptr + (gpu.ptr - srv_gpu_base.ptr) as usize,
            };
            for i in 0..bloom_count {
                write_color_rtv(&self.device, &self.bloom.mips[i], self.bloom.mip_rtvs[i]);
                write_hdr_srv(
                    &self.device,
                    &self.bloom.mips[i],
                    srv_cpu_of(self.bloom.mip_srv_gpus[i]),
                );
            }
        }
        Ok(())
    }
}