concinnity-device 0.18.69

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// src/directx/post/bloom.rs
//
// Bloom post-process: prefilter + downsample chain + additive upsample chain.
// Owns the per-mip render targets, the three PSOs they share (all using the
// shared single-source fullscreen-triangle VS), the root signature, and the
// `encode_bloom` per-frame encoder.
//
// Mirrors src/metal/post/bloom.rs: same mip-count clamp (4..=6), same
// Karis 13-tap prefilter, same plain 13-tap downsample + 9-tap tent upsample.

use windows::Win32::Foundation::RECT;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;

use crate::gfx::render_types::PostProcessParams;

use crate::directx::com;
use crate::directx::context::DxContext;
use crate::directx::pipeline::serialize_desc_and_create;
use crate::directx::slang_builtins;
use crate::directx::slang_builtins::SlangCompile;
use crate::directx::texture::{HDR_FORMAT, transition_barrier};

// Shader compilation

// Compiled bloom-chain shader bytecode. All three passes share the
// single-source fullscreen-triangle vertex shader.
pub(in crate::directx) struct BloomShaders {
    pub vs: Vec<u8>,
    pub prefilter_ps: Vec<u8>,
    pub downsample_ps: Vec<u8>,
    pub upsample_ps: Vec<u8>,
}

// Compile the bloom prefilter / downsample / upsample shaders.
pub(in crate::directx) fn compile_bloom_shaders(hot_reload: bool) -> Result<BloomShaders, String> {
    Ok(BloomShaders {
        vs: slang_builtins::FULLSCREEN_VERT.compile(hot_reload)?,
        prefilter_ps: slang_builtins::BLOOM_PREFILTER.compile(hot_reload)?,
        downsample_ps: slang_builtins::BLOOM_DOWNSAMPLE.compile(hot_reload)?,
        upsample_ps: slang_builtins::BLOOM_UPSAMPLE.compile(hot_reload)?,
    })
}

// Root signature + PSO

// Root signature for the bloom-chain passes: one SRV descriptor table at t0
// (the pass's source image), six 32-bit root constants at b0
// (`PostProcessParams`, read only by the prefilter), and a static linear-clamp
// sampler at s0. Shared by the prefilter, downsample, and upsample PSOs.
pub(in crate::directx) fn create_bloom_root_signature(
    device: &ID3D12Device,
) -> Result<ID3D12RootSignature, String> {
    let srv_range = D3D12_DESCRIPTOR_RANGE {
        RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
        NumDescriptors: 1,
        BaseShaderRegister: 0, // t0
        RegisterSpace: 0,
        OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
    };
    let params = [
        // [0] Descriptor table: source image SRV (t0)
        D3D12_ROOT_PARAMETER {
            ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
            Anonymous: D3D12_ROOT_PARAMETER_0 {
                DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE {
                    NumDescriptorRanges: 1,
                    pDescriptorRanges: &srv_range,
                },
            },
            ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL,
        },
        // [1] Root constants: PostProcessParams (6 floats) at b0
        D3D12_ROOT_PARAMETER {
            ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
            Anonymous: D3D12_ROOT_PARAMETER_0 {
                Constants: D3D12_ROOT_CONSTANTS {
                    ShaderRegister: 0,
                    RegisterSpace: 0,
                    Num32BitValues: 6,
                },
            },
            ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL,
        },
    ];
    let static_sampler = D3D12_STATIC_SAMPLER_DESC {
        Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
        AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
        ComparisonFunc: D3D12_COMPARISON_FUNC_ALWAYS,
        BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK,
        MinLOD: 0.0,
        MaxLOD: f32::MAX,
        ShaderRegister: 0, // s0
        RegisterSpace: 0,
        ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL,
        ..Default::default()
    };
    let desc = D3D12_ROOT_SIGNATURE_DESC {
        NumParameters: params.len() as u32,
        pParameters: params.as_ptr(),
        NumStaticSamplers: 1,
        pStaticSamplers: &static_sampler,
        Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE,
    };
    serialize_desc_and_create(device, &desc, "bloom root sig")
}

// PSO for a bloom-chain pass: a vertex-buffer-less fullscreen triangle that
// samples one source mip and writes an `HDR_FORMAT` bloom mip. No input
// layout, no depth. `additive` enables one-to-one additive blending, set for
// the upsample passes so each coarser mip accumulates onto the finer one.
pub(in crate::directx) fn create_bloom_pso(
    device: &ID3D12Device,
    root_sig: &ID3D12RootSignature,
    vs: &[u8],
    ps: &[u8],
    rtv_format: DXGI_FORMAT,
    additive: bool,
) -> Result<ID3D12PipelineState, String> {
    let blend_rt = D3D12_RENDER_TARGET_BLEND_DESC {
        BlendEnable: additive.into(),
        SrcBlend: D3D12_BLEND_ONE,
        DestBlend: D3D12_BLEND_ONE,
        BlendOp: D3D12_BLEND_OP_ADD,
        SrcBlendAlpha: D3D12_BLEND_ONE,
        DestBlendAlpha: D3D12_BLEND_ONE,
        BlendOpAlpha: D3D12_BLEND_OP_ADD,
        RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8,
        ..Default::default()
    };
    let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
        pRootSignature: com::borrowed(root_sig),
        VS: D3D12_SHADER_BYTECODE {
            pShaderBytecode: vs.as_ptr() as _,
            BytecodeLength: vs.len(),
        },
        PS: D3D12_SHADER_BYTECODE {
            pShaderBytecode: ps.as_ptr() as _,
            BytecodeLength: ps.len(),
        },
        PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
        NumRenderTargets: 1,
        RTVFormats: {
            let mut a = [DXGI_FORMAT_UNKNOWN; 8];
            a[0] = rtv_format;
            a
        },
        DSVFormat: DXGI_FORMAT_UNKNOWN,
        SampleDesc: DXGI_SAMPLE_DESC {
            Count: 1,
            Quality: 0,
        },
        SampleMask: u32::MAX,
        RasterizerState: D3D12_RASTERIZER_DESC {
            FillMode: D3D12_FILL_MODE_SOLID,
            CullMode: D3D12_CULL_MODE_NONE,
            FrontCounterClockwise: true.into(),
            DepthClipEnable: true.into(),
            ..Default::default()
        },
        DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
            DepthEnable: false.into(),
            DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
            DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
            StencilEnable: false.into(),
            ..Default::default()
        },
        BlendState: D3D12_BLEND_DESC {
            RenderTarget: {
                let mut arr = [D3D12_RENDER_TARGET_BLEND_DESC::default(); 8];
                arr[0] = blend_rt;
                arr
            },
            ..Default::default()
        },
        ..Default::default()
    };

    // SAFETY: `desc` outlives this synchronous call, and so do the root signature, shader bytecode
    // and input-element array whose raw pointers it borrows.
    unsafe { crate::directx::pso_library::create_graphics(device, &pso_desc) }
        .map_err(|e| format!("create bloom PSO: {e}"))
}

// Targets

// Number of mip levels in the bloom chain for an HDR target of the given
// resolution. Clamped to 4..=6: enough octaves for a wide soft glow without
// spending a dozen render passes on sub-pixel mips. Mirrors `bloom_mip_count`
// in vulkan/texture.rs.
pub(in crate::directx) fn bloom_mip_count(width: u32, height: u32) -> u32 {
    let min_dim = width.min(height).max(1);
    // mip 0 is already half-res, so subtract one octave before clamping.
    let levels = (min_dim as f32).log2().floor() as i32 - 1;
    levels.clamp(4, 6) as u32
}

// Bloom mip chain: the mip render targets paired with their (width, height).
type BloomMips = (Vec<ID3D12Resource>, Vec<(u32, u32)>);

// Create the bloom mip chain for an HDR target of `width`x`height`. `mips[i]`
// has resolution `(width >> (i+1), height >> (i+1))`, floored at one texel, so
// `mips[0]` is half-res. `mips[0]` (`bloom_top`) is the transient pool's placed
// resource passed in as `top` (so the graph can alias its memory); the finer
// mips are committed single-sample `HDR_FORMAT` colour targets usable as both a
// render target and a sampled texture, created in the PIXEL_SHADER_RESOURCE
// state so the composite pass can bind `mips[0]` even when bloom is disabled and
// the bloom passes never run.
pub(in crate::directx) fn create_bloom_mips(
    device: &ID3D12Device,
    width: u32,
    height: u32,
    top: ID3D12Resource,
) -> Result<BloomMips, String> {
    let full_w = width.max(1);
    let full_h = height.max(1);
    let count = bloom_mip_count(full_w, full_h);
    create_bloom_mips_at(device, full_w, full_h, count as usize, top)
}

// Same shape as [`create_bloom_mips`], but with an explicit `count` so the
// resize handler can recreate the chain at the new resolution while keeping
// the SRV/RTV-heap-slot layout (which was sized for the init-time count)
// stable. The trailing mips fall to `1×1` once `(w >> i) < 1`, harmless,
// the bloom passes still sample them and the composite ignores them.
pub(in crate::directx) fn create_bloom_mips_at(
    device: &ID3D12Device,
    width: u32,
    height: u32,
    count: usize,
    top: ID3D12Resource,
) -> Result<BloomMips, String> {
    let full_w = width.max(1);
    let full_h = height.max(1);
    let heap_props = D3D12_HEAP_PROPERTIES {
        Type: D3D12_HEAP_TYPE_DEFAULT,
        ..Default::default()
    };
    let clear_value = D3D12_CLEAR_VALUE {
        Format: HDR_FORMAT,
        Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] },
    };
    let mut mips = Vec::with_capacity(count);
    let mut extents = Vec::with_capacity(count);
    // mip 0 (`bloom_top`) is the pool-owned placed resource; the finer octaves
    // below stay committed. The pool sizes it from the graph's own
    // `DrawableScaled(0.5)` desc, which resolves to the same half-extent.
    let (tw, th) = ((full_w.max(1) >> 1).max(1), (full_h.max(1) >> 1).max(1));
    mips.push(top);
    extents.push((tw, th));
    for i in 1..count {
        let mw = (full_w >> (i + 1)).max(1);
        let mh = (full_h >> (i + 1)).max(1);
        let desc = D3D12_RESOURCE_DESC {
            Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
            Width: mw as u64,
            Height: mh,
            DepthOrArraySize: 1,
            MipLevels: 1,
            Format: HDR_FORMAT,
            SampleDesc: DXGI_SAMPLE_DESC {
                Count: 1,
                Quality: 0,
            },
            Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
            ..Default::default()
        };
        let mut res_opt: Option<ID3D12Resource> = 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.
        unsafe {
            device.CreateCommittedResource(
                &heap_props,
                D3D12_HEAP_FLAG_NONE,
                &desc,
                D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
                Some(&clear_value),
                &mut res_opt,
            )
        }
        .map_err(|e| format!("create bloom mip {i}: {e}"))?;
        mips.push(res_opt.ok_or_else(|| format!("bloom mip {i} returned None"))?);
        extents.push((mw, mh));
    }
    Ok((mips, extents))
}

// Write an `HDR_FORMAT` single-sample Texture2D render-target view at the
// given heap slot, used for the bloom mips.
pub(in crate::directx) fn write_color_rtv(
    device: &ID3D12Device,
    resource: &ID3D12Resource,
    rtv_cpu: D3D12_CPU_DESCRIPTOR_HANDLE,
) {
    let rtv_desc = D3D12_RENDER_TARGET_VIEW_DESC {
        Format: HDR_FORMAT,
        ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D,
        ..Default::default()
    };
    // SAFETY: the view descriptor and the resource it names are live for the call, and the
    // destination handle addresses a slot this context reserved for the view in a heap it owns.
    unsafe { device.CreateRenderTargetView(resource, Some(&rtv_desc), rtv_cpu) };
}

// Encoder

// The bloom chain orchestration lives once in `gfx::fullscreen`; this impl binds
// + draws each sub-pass in D3D12. `Args` is the scene-colour SRV the prefilter
// samples (post-TAA when TAA is on, the HDR scene SRV otherwise). Each sub-pass
// transitions its destination mip to RENDER_TARGET for the draw and back to
// PIXEL_SHADER_RESOURCE so the next pass (or composite) can sample it; every mip
// therefore ends the frame back in its created state.
impl crate::gfx::fullscreen::BloomEncoder for DxContext {
    type Rec = ID3D12GraphicsCommandList;
    type Args = D3D12_GPU_DESCRIPTOR_HANDLE;

    fn bloom_mip_count(&self) -> usize {
        self.bloom.mips.len()
    }

    fn begin_bloom(&self, cmd: &Self::Rec, _scene_srv: &Self::Args) {
        // SAFETY: the command list is in the recording state, and every resource, descriptor and
        // slice these commands name is live for the call.
        unsafe {
            cmd.SetGraphicsRootSignature(&self.bloom.root_sig);
            cmd.SetDescriptorHeaps(&[Some(self.descriptors.srv_heap.clone())]);
            cmd.IASetPrimitiveTopology(
                windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
            );
            // The bloom shaders build the fullscreen triangle from SV_VertexID.
            cmd.IASetVertexBuffers(0, None);
            cmd.IASetIndexBuffer(None);
        }
    }

    fn bloom_prefilter(&self, cmd: &Self::Rec, scene_srv: &Self::Args) {
        // Mip 0 is the graph's `bloom_top`, so it arrives in RENDER_TARGET and
        // must leave in it. In between the downsample chain samples it, which is
        // the one state change this node owns.
        let after = if self.bloom.mips.len() > 1 {
            D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
        } else {
            D3D12_RESOURCE_STATE_RENDER_TARGET
        };
        self.bloom_run_pass(
            cmd,
            BloomSubPass {
                dst: 0,
                src_srv: *scene_srv,
                pso: &self.bloom.pso_prefilter,
                before: D3D12_RESOURCE_STATE_RENDER_TARGET,
                after,
            },
        );
    }

    fn bloom_downsample(&self, cmd: &Self::Rec, _scene_srv: &Self::Args, dst: usize) {
        self.bloom_run_pass(
            cmd,
            BloomSubPass {
                dst,
                src_srv: self.bloom.mip_srv_gpus[dst - 1],
                pso: &self.bloom.pso_downsample,
                before: D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
                after: D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
            },
        );
    }

    fn bloom_upsample(&self, cmd: &Self::Rec, _scene_srv: &Self::Args, dst: usize) {
        // The chain walks back down to mip 0, whose last write hands
        // `bloom_top` back to the graph in RENDER_TARGET.
        let after = if dst == 0 {
            D3D12_RESOURCE_STATE_RENDER_TARGET
        } else {
            D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
        };
        self.bloom_run_pass(
            cmd,
            BloomSubPass {
                dst,
                src_srv: self.bloom.mip_srv_gpus[dst + 1],
                pso: &self.bloom.pso_upsample,
                before: D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
                after,
            },
        );
    }
}

// One bloom sub-pass: which mip it renders into, what it samples, and the states
// that mip is in on either side of it. Every mip but 0 rests sampled inside the
// chain; mip 0 is the graph's `bloom_top` and rests in RENDER_TARGET at the node
// boundary, so it is the only one whose `before` and `after` differ from the
// rest.
struct BloomSubPass<'a> {
    dst: usize,
    src_srv: D3D12_GPU_DESCRIPTOR_HANDLE,
    pso: &'a ID3D12PipelineState,
    before: D3D12_RESOURCE_STATES,
    after: D3D12_RESOURCE_STATES,
}

impl DxContext {
    // Encode the bloom prefilter, downsample, and additive upsample passes via
    // the shared `gfx::fullscreen` driver. On return `bloom_mips[0]` holds the
    // accumulated soft glow the composite pass samples. Called only when
    // `post_process.bloom_intensity > 0`, and after the HDR resolve (and the TAA
    // resolve, if any) so the prefilter can sample `scene_srv`.
    pub(in crate::directx) fn encode_bloom(
        &self,
        cmd: &ID3D12GraphicsCommandList,
        scene_srv: D3D12_GPU_DESCRIPTOR_HANDLE,
    ) {
        crate::gfx::fullscreen::encode_bloom_chain(self, cmd, scene_srv);
    }

    // One fullscreen-triangle bloom sub-pass: sample `src_srv`, render into
    // bloom mip `dst` with `pso` bound, opening from the mip's `before` state
    // and closing into its `after`. A sub-pass whose mip is already a render
    // target on both sides (mip 0, handed over by the graph) emits neither.
    fn bloom_run_pass(&self, cmd: &ID3D12GraphicsCommandList, pass: BloomSubPass<'_>) {
        let BloomSubPass {
            dst,
            src_srv,
            pso,
            before,
            after,
        } = pass;
        let (mw, mh) = self.bloom.mip_extents[dst];
        let post = self.post_process;
        if before != D3D12_RESOURCE_STATE_RENDER_TARGET {
            let to_rt = transition_barrier(
                &self.bloom.mips[dst],
                before,
                D3D12_RESOURCE_STATE_RENDER_TARGET,
            );
            // SAFETY: the command list is in the recording state, and every resource, descriptor
            // and slice these commands name is live for the call.
            unsafe { cmd.ResourceBarrier(&[to_rt]) };
        }
        // SAFETY: the command list is in the recording state, and every resource, descriptor and
        // slice these commands name is live for the call.
        unsafe {
            cmd.OMSetRenderTargets(1, Some(&self.bloom.mip_rtvs[dst]), false, None);
            let vp = D3D12_VIEWPORT {
                TopLeftX: 0.0,
                TopLeftY: 0.0,
                Width: mw as f32,
                Height: mh as f32,
                MinDepth: 0.0,
                MaxDepth: 1.0,
            };
            cmd.RSSetViewports(&[vp]);
            let scissor = RECT {
                left: 0,
                top: 0,
                right: mw as i32,
                bottom: mh as i32,
            };
            cmd.RSSetScissorRects(&[scissor]);
            cmd.SetPipelineState(pso);
            cmd.SetGraphicsRootDescriptorTable(0, src_srv);
            cmd.SetGraphicsRoot32BitConstants(
                1,
                6,
                &post as *const PostProcessParams as *const std::ffi::c_void,
                0,
            );
            cmd.DrawInstanced(3, 1, 0, 0);
        }
        if after != D3D12_RESOURCE_STATE_RENDER_TARGET {
            let from_rt = transition_barrier(
                &self.bloom.mips[dst],
                D3D12_RESOURCE_STATE_RENDER_TARGET,
                after,
            );
            // SAFETY: the command list is in the recording state, and every resource, descriptor
            // and slice these commands name is live for the call.
            unsafe { cmd.ResourceBarrier(&[from_rt]) };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::bloom_mip_count;

    #[test]
    fn bloom_mip_count_clamps_to_four_to_six() {
        // Common HD resolutions land in the wide-glow sweet spot (6 octaves).
        assert_eq!(bloom_mip_count(1920, 1080), 6);
        assert_eq!(bloom_mip_count(1280, 720), 6);
        // Smaller resolutions earn fewer octaves before the clamp.
        assert_eq!(bloom_mip_count(64, 64), 5);
        // Floor: ridiculously small resolutions still get four octaves.
        assert_eq!(bloom_mip_count(16, 16), 4);
        assert_eq!(bloom_mip_count(1, 1), 4);
        assert_eq!(bloom_mip_count(0, 0), 4);
    }
}