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
//! Volumetric fog for the Vulkan backend. Frostbite-style froxel volume:
//!
//!   * The `fog_froxel_kernel` compute pass (`encode_fog_froxel`) populates a
//!     screen-aligned `(80 x 45 x 64)` 3D `RGBA16F` volume of
//!     `(scattered_rgb, 1 - T)` across the view frustum. One thread per
//!     (x, y) tile; each thread walks Z front-to-back, accumulating the
//!     per-slab scatter + transmittance with a CSM shadow tap per slice.
//!
//!   * The fullscreen `Fog` render pass (`encode_fog`) samples the volume by
//!     `(screen_uv, view_z)` instead of marching per pixel and composites
//!     `(scattered, 1 - T)` over the resolved HDR target with the standard
//!     `over` blend (`final = scene * T + scattered`).
//!
//! Runs between the projected-decal pass and the SSR resolve so the fog wraps
//! the decal-stamped scene and SSR reflects through it; TAA history then
//! reprojects the integrated fog color and transmittance.
//!
//! Mirrors src/directx/fog.rs and src/metal/fog.rs.

use ash::vk;
use concinnity_core::gfx::render_types::{FogFroxelParams, FogParams, ShadowUniforms};
use concinnity_core::render::error::RenderResult;
use concinnity_core::render::render_graph::{FOG_FROXEL_X, FOG_FROXEL_Y, FOG_FROXEL_Z};
use concinnity_core::render::volumetric_fog;
use concinnity_core::transform::mat4_inverse;

use super::allocator::{DeviceAllocator, PooledBuffer, PooledImage};
use super::context::VkContext;
use super::descriptor_layout::{Binding, PoolSizes};
use super::pipeline_desc::{Blend, GraphicsPipelineDesc, compute_pipeline};
use super::resources::{alloc_descriptor_sets, create_descriptor_set_layout};
use super::set_writes::SetWrites;
use super::texture::{
    LayoutTransition, SubresourceRange, one_shot_submit, transition_image_layout_range,
};
use crate::vulkan::builtin_shaders::CompileProgram;
use crate::vulkan::owned::{
    OwnedDescriptorPool, OwnedFramebuffer, OwnedPipeline, OwnedPipelineLayout, OwnedRenderPass,
    OwnedSampler, OwnedSetLayout, VkDevice,
};
use crate::vulkan::record::Recorder;

// Threadgroup tile for the froxel kernel (8x8, one thread per (x, y) froxel),
// matching the DirectX `[numthreads(8, 8, 1)]` and the Metal dispatch.
const FROXEL_TILE: u32 = 8;

// 3D froxel volume pixel format. RGBA16F holds `(scattered_rgb, 1 - T)` per
// slice; mirrors the DirectX / Metal `RGBA16Float` volume.
const VOLUME_FORMAT: vk::Format = vk::Format::R16G16B16A16_SFLOAT;

// Owned by `VkContext` exactly when the world declared a `VolumetricFog`:
// the fog render pipeline + the froxel compute pipeline + the per-frame
// uniform rings + the shared 3D froxel volume the kernel writes and the
// fragment shader samples.
pub(in crate::vulkan) struct FogResources {
    pub(in crate::vulkan) render_pass: OwnedRenderPass,
    pub(in crate::vulkan) pipeline: OwnedPipeline,
    pub(in crate::vulkan) pipeline_layout: OwnedPipelineLayout,
    pub(in crate::vulkan) _view_set_layout: OwnedSetLayout,
    pub(in crate::vulkan) _descriptor_pool: OwnedDescriptorPool,

    // Per-frame FogParams view UBO (176 bytes). Persistently mapped.
    pub(in crate::vulkan) params_ubos: Vec<PooledBuffer>,

    // Per-frame FogFroxelParams UBO (96 bytes). Persistently mapped. Bound at
    // the froxel kernel's set binding 1 and the fog fragment's set binding 2.
    pub(in crate::vulkan) froxel_ubos: Vec<PooledBuffer>,

    // Per-frame fog-render view sets (binding 0 FogParams, 1 depth, 2
    // FogFroxelParams, 3 volume, 4 the volume's sampler).
    pub(in crate::vulkan) view_sets: Vec<vk::DescriptorSet>,

    // Froxel compute pipeline + its per-frame sets (binding 0 FogParams, 1
    // FogFroxelParams, 2 ShadowUniforms, 3 shadow_map, 4 volume image3D, 5 the
    // shadow map's compare sampler).
    pub(in crate::vulkan) froxel_pipeline: OwnedPipeline,
    pub(in crate::vulkan) froxel_pipeline_layout: OwnedPipelineLayout,
    pub(in crate::vulkan) _froxel_set_layout: OwnedSetLayout,
    pub(in crate::vulkan) froxel_sets: Vec<vk::DescriptorSet>,

    // Shared 3D RGBA16F volume: written by the compute kernel (GENERAL),
    // sampled by the fog fragment (SHADER_READ_ONLY). The open
    // (SHADER_READ_ONLY -> GENERAL) and close (GENERAL -> SHADER_READ_ONLY)
    // transitions are graph-driven (fog_froxel_volume's FogFroxel producer + Fog
    // consumer barriers, emitted by the executor); the cross-frame hazard chain
    // spans submission order on the one queue (same reasoning as the Hi-Z
    // pyramid).
    pub(in crate::vulkan) volume: PooledImage,

    // One framebuffer per frame-in-flight slot, each binding its frame slot's
    // `hdr_resolve_images[i].view` as the sole color attachment.
    pub(in crate::vulkan) framebuffers: Vec<OwnedFramebuffer>,

    // Linear-clamp sampler for the trilinear volume read.
    pub(in crate::vulkan) _volume_sampler: OwnedSampler,
}

// The Vulkan device handles `FogResources::new` needs to create its GPU
// resources and run the one-shot volume-layout transition. `command_pool` /
// `queue` are used once to move the volume into `SHADER_READ_ONLY_OPTIMAL`.
#[derive(Clone, Copy)]
pub(in crate::vulkan) struct FogDeviceContext<'a> {
    pub(in crate::vulkan) alloc: &'a DeviceAllocator,
    pub(in crate::vulkan) device: &'a VkDevice,
    pub(in crate::vulkan) command_pool: vk::CommandPool,
    pub(in crate::vulkan) queue: vk::Queue,
}

// The per-frame render targets + config the fog pipeline binds against: the
// resolved HDR color views (framebuffer attachments), the scene depth views,
// and the frame count / MSAA / format / extent.
#[derive(Clone, Copy)]
pub(in crate::vulkan) struct FogFrameTargets<'a> {
    pub(in crate::vulkan) frames: usize,
    pub(in crate::vulkan) msaa: bool,
    pub(in crate::vulkan) hdr_format: vk::Format,
    pub(in crate::vulkan) hdr_resolve_views: &'a [vk::ImageView],
    pub(in crate::vulkan) depth_views: &'a [vk::ImageView],
    pub(in crate::vulkan) extent: vk::Extent2D,
}

// The shared CSM resources the froxel kernel taps per slab. `ubos` is the
// per-frame-in-flight ShadowUniforms ring; slot `i` binds into froxel set `i`.
#[derive(Clone, Copy)]
pub(in crate::vulkan) struct FogShadowResources<'a> {
    pub(in crate::vulkan) ubos: &'a [PooledBuffer],
    pub(in crate::vulkan) map_view: vk::ImageView,
    pub(in crate::vulkan) sampler: vk::Sampler,
}

impl FogResources {
    // Build the fog render pipeline + the froxel compute pipeline + their
    // dependent resources. Called from `VkContext::new` only when the world
    // declared a `VolumetricFog` and `FogSettings::resolve` returned a value.
    pub(in crate::vulkan) fn new(
        ctx: FogDeviceContext,
        targets: FogFrameTargets,
        shadow: FogShadowResources<'_>,
        hot_reload: bool,
    ) -> RenderResult<Self> {
        let FogDeviceContext {
            alloc,
            device,
            command_pool,
            queue,
        } = ctx;
        let FogFrameTargets {
            frames,
            msaa,
            hdr_format,
            hdr_resolve_views,
            depth_views,
            extent,
        } = targets;
        let FogShadowResources {
            ubos: shadow_ubos,
            map_view: shadow_map_view,
            sampler: shadow_sampler,
        } = shadow;
        let render_pass = create_fog_render_pass(device, hdr_format)?;
        let view_set_layout = create_descriptor_set_layout(device, &fog_set_bindings())?;
        let pipeline_layout = create_fog_pipeline_layout(device, view_set_layout.handle())?;

        let (vert_spv, frag_spv) = compile_fog_shaders(hot_reload, msaa)?;
        let pipeline = create_fog_pipeline(
            device,
            render_pass.handle(),
            pipeline_layout.handle(),
            &vert_spv,
            &frag_spv,
        )?;

        // Froxel compute pipeline.
        let froxel_set_layout = create_descriptor_set_layout(device, &froxel_set_bindings())?;
        let froxel_pipeline_layout =
            create_froxel_pipeline_layout(device, froxel_set_layout.handle())?;
        let froxel_spv = compile_fog_froxel_shader(hot_reload)?;
        let froxel_pipeline = compute_pipeline(
            device,
            froxel_pipeline_layout.handle(),
            &froxel_spv,
            "fog froxel",
        )?;

        // The shared 3D volume + its storage (compute write) + sampled
        // (fragment read) views. Rest it in SHADER_READ_ONLY so the first
        // froxel build's opening barrier (SHADER_READ_ONLY -> GENERAL) matches.
        let volume = create_volume_image(alloc)?;
        one_shot_submit(device, command_pool, queue, |cmd| {
            transition_image_layout_range(
                device,
                cmd,
                volume.image(),
                LayoutTransition {
                    old_layout: vk::ImageLayout::UNDEFINED,
                    new_layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
                    aspect: vk::ImageAspectFlags::COLOR,
                },
                SubresourceRange {
                    base_layer: 0,
                    layer_count: 1,
                    base_mip: 0,
                    mip_count: 1,
                },
            );
        })?;
        let volume_storage_view = create_volume_view(device, volume.image())?;
        volume.attach_view(volume_storage_view);
        let volume_sampled_view = create_volume_view(device, volume.image())?;
        volume.attach_view(volume_sampled_view);
        let volume_sampler = create_volume_sampler(device)?;

        // Per-frame FogParams UBOs (HOST_VISIBLE | HOST_COHERENT, mapped).
        let params_ubos = alloc_ubo_ring(alloc, frames, std::mem::size_of::<FogParams>() as u64)?;
        // Per-frame FogFroxelParams UBOs.
        let froxel_ubos =
            alloc_ubo_ring(alloc, frames, std::mem::size_of::<FogFroxelParams>() as u64)?;

        let descriptor_pool = create_fog_descriptor_pool(device, frames)?;
        let view_layouts: Vec<_> = (0..frames).map(|_| view_set_layout.handle()).collect();
        let view_sets = alloc_descriptor_sets(device, descriptor_pool.handle(), &view_layouts)?;
        let froxel_layouts: Vec<_> = (0..frames).map(|_| froxel_set_layout.handle()).collect();
        let froxel_sets = alloc_descriptor_sets(device, descriptor_pool.handle(), &froxel_layouts)?;

        let last_depth = depth_views.len().saturating_sub(1);
        for (i, &set) in view_sets.iter().enumerate() {
            write_view_set(
                device,
                set,
                FogViewBindings {
                    params_ubo: params_ubos[i].buffer(),
                    depth_view: depth_views[i.min(last_depth)],
                    froxel_ubo: froxel_ubos[i].buffer(),
                    volume_view: volume_sampled_view,
                    volume_sampler: volume_sampler.handle(),
                },
            );
        }
        for (i, &set) in froxel_sets.iter().enumerate() {
            write_froxel_set(
                device,
                set,
                FogFroxelBindings {
                    params_ubo: params_ubos[i].buffer(),
                    froxel_ubo: froxel_ubos[i].buffer(),
                    shadow_ubo: shadow_ubos[i].buffer(),
                    shadow_map_view,
                    shadow_sampler,
                    volume_storage_view,
                },
            );
        }

        // Per-frame framebuffers (one per frame slot binding that slot's
        // hdr_resolve view as the color attachment).
        let mut framebuffers = Vec::with_capacity(frames);
        for &view in hdr_resolve_views.iter().take(frames) {
            let attachments = [view];
            let fb_info = vk::FramebufferCreateInfo::default()
                .render_pass(render_pass.handle())
                .attachments(&attachments)
                .width(extent.width.max(1))
                .height(extent.height.max(1))
                .layers(1);
            let fb = device
                .create_framebuffer(&fb_info)
                .map_err(|e| super::error::map_vk_result(e, "fog framebuffer"))?;
            framebuffers.push(fb);
        }

        Ok(Self {
            render_pass,
            pipeline,
            pipeline_layout,
            _view_set_layout: view_set_layout,
            _descriptor_pool: descriptor_pool,
            params_ubos,
            froxel_ubos,
            view_sets,
            froxel_pipeline,
            froxel_pipeline_layout,
            _froxel_set_layout: froxel_set_layout,
            froxel_sets,
            volume,
            framebuffers,
            _volume_sampler: volume_sampler,
        })
    }

    // Rebuild the framebuffers + re-point the per-frame view set's depth
    // binding after a swapchain resize. Called from
    // `VkContext::rebuild_swapchain`; same pattern as `DecalResources`. The
    // pipelines, layouts, buffers, the froxel sets, the 3D volume, and the
    // samplers all survive (the volume is screen-aligned via the per-froxel
    // reconstruction, not tied to render resolution).
    pub(in crate::vulkan) fn rebuild(
        &mut self,
        device: &VkDevice,
        hdr_resolve_views: &[vk::ImageView],
        depth_views: &[vk::ImageView],
        extent: vk::Extent2D,
    ) -> RenderResult<()> {
        self.framebuffers.clear();
        for &view in hdr_resolve_views.iter().take(self.params_ubos.len()) {
            let attachments = [view];
            let fb_info = vk::FramebufferCreateInfo::default()
                .render_pass(self.render_pass.handle())
                .attachments(&attachments)
                .width(extent.width.max(1))
                .height(extent.height.max(1))
                .layers(1);
            let fb = device
                .create_framebuffer(&fb_info)
                .map_err(|e| super::error::map_vk_result(e, "fog framebuffer (rebuild)"))?;
            self.framebuffers.push(fb);
        }
        let last_depth = depth_views.len().saturating_sub(1);
        for (i, &set) in self.view_sets.iter().enumerate() {
            SetWrites::new(set)
                .sampled_image(1, depth_views[i.min(last_depth)])
                .apply(device);
        }
        Ok(())
    }

    // Destroy every non-pooled GPU resource and drop the pooled ones (the
    // UBO rings and the volume + its views retire through the allocator).
    // Called from `VkContext::drop` after `wait_idle`.
    pub(in crate::vulkan) fn destroy(&mut self, _device: &VkDevice) {
        self.framebuffers.clear();
        self.params_ubos.clear();
        self.froxel_ubos.clear();
        self.volume = PooledImage::null();
    }
}

// Allocate `count` host-visible/coherent uniform buffers of `size` bytes,
// each persistently mapped through its pooled block.
fn alloc_ubo_ring(
    alloc: &DeviceAllocator,
    count: usize,
    size: u64,
) -> RenderResult<Vec<PooledBuffer>> {
    (0..count)
        .map(|_| {
            alloc.create_buffer(
                size,
                vk::BufferUsageFlags::UNIFORM_BUFFER,
                vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
            )
        })
        .collect()
}

// Render pass / pipeline construction

fn create_fog_render_pass(device: &VkDevice, format: vk::Format) -> RenderResult<OwnedRenderPass> {
    // One color attachment: the resolved HDR scene. The main pass (and
    // any preceding decal pass) left it in SHADER_READ_ONLY_OPTIMAL; we
    // want it in COLOR_ATTACHMENT during the subpass and
    // SHADER_READ_ONLY_OPTIMAL again on exit so SSR / TAA / bloom /
    // composite can sample it. Mirrors the decal render pass.
    let attachment = vk::AttachmentDescription::default()
        .format(format)
        .samples(vk::SampleCountFlags::TYPE_1)
        .load_op(vk::AttachmentLoadOp::LOAD)
        .store_op(vk::AttachmentStoreOp::STORE)
        .stencil_load_op(vk::AttachmentLoadOp::DONT_CARE)
        .stencil_store_op(vk::AttachmentStoreOp::DONT_CARE)
        .initial_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
        .final_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
    let color_ref = vk::AttachmentReference::default()
        .attachment(0)
        .layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL);
    let subpass = vk::SubpassDescription::default()
        .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
        .color_attachments(std::slice::from_ref(&color_ref));
    let dep_in = vk::SubpassDependency::default()
        .src_subpass(vk::SUBPASS_EXTERNAL)
        .dst_subpass(0)
        .src_stage_mask(
            vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT
                | vk::PipelineStageFlags::FRAGMENT_SHADER,
        )
        .src_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::COLOR_ATTACHMENT_WRITE)
        .dst_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
        .dst_access_mask(
            vk::AccessFlags::COLOR_ATTACHMENT_WRITE | vk::AccessFlags::COLOR_ATTACHMENT_READ,
        );
    let dep_out = vk::SubpassDependency::default()
        .src_subpass(0)
        .dst_subpass(vk::SUBPASS_EXTERNAL)
        .src_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
        .src_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE)
        .dst_stage_mask(vk::PipelineStageFlags::FRAGMENT_SHADER)
        .dst_access_mask(vk::AccessFlags::SHADER_READ);
    let deps = [dep_in, dep_out];
    let info = vk::RenderPassCreateInfo::default()
        .attachments(std::slice::from_ref(&attachment))
        .subpasses(std::slice::from_ref(&subpass))
        .dependencies(&deps);
    device
        .create_render_pass(&info)
        .map_err(|e| super::error::map_vk_result(e, "fog render pass"))
}

// The fog-render view set: FogParams UBO, the scene depth (read by texel),
// FogFroxelParams UBO, the froxel volume and the volume's sampler.
fn fog_set_bindings() -> [Binding; 5] {
    use vk::DescriptorType as T;
    let frag = vk::ShaderStageFlags::FRAGMENT;
    [
        (0, T::UNIFORM_BUFFER, frag),
        (1, T::SAMPLED_IMAGE, frag),
        (2, T::UNIFORM_BUFFER, frag),
        (3, T::SAMPLED_IMAGE, frag),
        (4, T::SAMPLER, frag),
    ]
}

// The froxel compute set: FogParams, FogFroxelParams and ShadowUniforms UBOs,
// the shadow map array, the volume storage image and the shadow compare sampler.
fn froxel_set_bindings() -> [Binding; 6] {
    use vk::DescriptorType as T;
    let compute = vk::ShaderStageFlags::COMPUTE;
    [
        (0, T::UNIFORM_BUFFER, compute),
        (1, T::UNIFORM_BUFFER, compute),
        (2, T::UNIFORM_BUFFER, compute),
        (3, T::SAMPLED_IMAGE, compute),
        (4, T::STORAGE_IMAGE, compute),
        (5, T::SAMPLER, compute),
    ]
}

fn create_fog_pipeline_layout(
    device: &VkDevice,
    view_set_layout: vk::DescriptorSetLayout,
) -> RenderResult<OwnedPipelineLayout> {
    let set_layouts = [view_set_layout];
    let info = vk::PipelineLayoutCreateInfo::default().set_layouts(&set_layouts);
    device
        .create_pipeline_layout(&info)
        .map_err(|e| super::error::map_vk_result(e, "fog pipeline layout"))
}

fn create_froxel_pipeline_layout(
    device: &VkDevice,
    froxel_set_layout: vk::DescriptorSetLayout,
) -> RenderResult<OwnedPipelineLayout> {
    let set_layouts = [froxel_set_layout];
    let info = vk::PipelineLayoutCreateInfo::default().set_layouts(&set_layouts);
    device
        .create_pipeline_layout(&info)
        .map_err(|e| super::error::map_vk_result(e, "fog froxel pipeline layout"))
}

fn create_fog_descriptor_pool(
    device: &VkDevice,
    frames: usize,
) -> RenderResult<OwnedDescriptorPool> {
    let f = frames as u32;
    let sizes = PoolSizes::default()
        .sets(&fog_set_bindings(), f)
        .sets(&froxel_set_bindings(), f)
        .build();
    let info = vk::DescriptorPoolCreateInfo::default()
        .max_sets(2 * f)
        .pool_sizes(&sizes);
    device
        .create_descriptor_pool(&info)
        .map_err(|e| super::error::map_vk_result(e, "fog descriptor pool"))
}

// The five bindings of a per-frame fog-render view set: the FogParams +
// FogFroxelParams UBOs, the scene depth, and the froxel volume with its sampler.
#[derive(Clone, Copy)]
struct FogViewBindings {
    params_ubo: vk::Buffer,
    depth_view: vk::ImageView,
    froxel_ubo: vk::Buffer,
    volume_view: vk::ImageView,
    volume_sampler: vk::Sampler,
}

fn write_view_set(device: &VkDevice, set: vk::DescriptorSet, bindings: FogViewBindings) {
    let FogViewBindings {
        params_ubo,
        depth_view,
        froxel_ubo,
        volume_view,
        volume_sampler,
    } = bindings;
    SetWrites::new(set)
        .uniform_buffer(0, params_ubo, std::mem::size_of::<FogParams>() as u64)
        .sampled_image(1, depth_view)
        .uniform_buffer(2, froxel_ubo, std::mem::size_of::<FogFroxelParams>() as u64)
        .sampled_image(3, volume_view)
        .sampler(4, volume_sampler)
        .apply(device);
}

// The six bindings of a per-frame froxel compute set: the FogParams,
// FogFroxelParams, and ShadowUniforms UBOs, the CSM shadow map with its compare
// sampler, and the froxel volume storage image.
#[derive(Clone, Copy)]
struct FogFroxelBindings {
    params_ubo: vk::Buffer,
    froxel_ubo: vk::Buffer,
    shadow_ubo: vk::Buffer,
    shadow_map_view: vk::ImageView,
    shadow_sampler: vk::Sampler,
    volume_storage_view: vk::ImageView,
}

fn write_froxel_set(device: &VkDevice, set: vk::DescriptorSet, bindings: FogFroxelBindings) {
    let FogFroxelBindings {
        params_ubo,
        froxel_ubo,
        shadow_ubo,
        shadow_map_view,
        shadow_sampler,
        volume_storage_view,
    } = bindings;
    SetWrites::new(set)
        .uniform_buffer(0, params_ubo, std::mem::size_of::<FogParams>() as u64)
        .uniform_buffer(1, froxel_ubo, std::mem::size_of::<FogFroxelParams>() as u64)
        .uniform_buffer(2, shadow_ubo, std::mem::size_of::<ShadowUniforms>() as u64)
        .sampled_image(3, shadow_map_view)
        .storage_image(4, volume_storage_view)
        .sampler(5, shadow_sampler)
        .apply(device);
}

// Create the shared 3D RGBA16F froxel volume (STORAGE | SAMPLED, GPU-local).
fn create_volume_image(alloc: &DeviceAllocator) -> RenderResult<PooledImage> {
    let img_info = vk::ImageCreateInfo::default()
        .image_type(vk::ImageType::TYPE_3D)
        .extent(vk::Extent3D {
            width: FOG_FROXEL_X,
            height: FOG_FROXEL_Y,
            depth: FOG_FROXEL_Z,
        })
        .mip_levels(1)
        .array_layers(1)
        .format(VOLUME_FORMAT)
        .tiling(vk::ImageTiling::OPTIMAL)
        .initial_layout(vk::ImageLayout::UNDEFINED)
        .usage(vk::ImageUsageFlags::STORAGE | vk::ImageUsageFlags::SAMPLED)
        .sharing_mode(vk::SharingMode::EXCLUSIVE)
        .samples(vk::SampleCountFlags::TYPE_1);
    alloc.create_image(&img_info, vk::MemoryPropertyFlags::DEVICE_LOCAL)
}

// A whole-image 3D view of the froxel volume (used for both the compute
// storage bind and the fragment sampled bind).
fn create_volume_view(device: &VkDevice, image: vk::Image) -> RenderResult<vk::ImageView> {
    let info = vk::ImageViewCreateInfo::default()
        .image(image)
        .view_type(vk::ImageViewType::TYPE_3D)
        .format(VOLUME_FORMAT)
        .subresource_range(vk::ImageSubresourceRange {
            aspect_mask: vk::ImageAspectFlags::COLOR,
            base_mip_level: 0,
            level_count: 1,
            base_array_layer: 0,
            layer_count: 1,
        });
    // SAFETY: the create-info and every slice it borrows are live for the call, and each handle it
    // names belongs to this device.
    unsafe { device.create_image_view(&info, None) }
        .map_err(|e| super::error::map_vk_result(e, "fog volume view"))
}

// Linear clamp-to-edge sampler for the trilinear volume read.
fn create_volume_sampler(device: &VkDevice) -> RenderResult<OwnedSampler> {
    let info = vk::SamplerCreateInfo::default()
        .mag_filter(vk::Filter::LINEAR)
        .min_filter(vk::Filter::LINEAR)
        .mipmap_mode(vk::SamplerMipmapMode::NEAREST)
        .address_mode_u(vk::SamplerAddressMode::CLAMP_TO_EDGE)
        .address_mode_v(vk::SamplerAddressMode::CLAMP_TO_EDGE)
        .address_mode_w(vk::SamplerAddressMode::CLAMP_TO_EDGE);
    device
        .create_sampler(&info)
        .map_err(|e| super::error::map_vk_result(e, "fog volume sampler"))
}

fn compile_fog_shaders(hot_reload: bool, msaa: bool) -> RenderResult<(Vec<u8>, Vec<u8>)> {
    let vert = super::builtin_shaders::FULLSCREEN_VERT.compile(hot_reload)?;
    let frag = super::builtin_shaders::FOG_FRAG
        .at(msaa)
        .compile(hot_reload)?;
    Ok((vert, frag))
}

// Compile the froxel-volume compute kernel. MSAA-independent (the kernel does
// not read the scene depth attachment).
fn compile_fog_froxel_shader(hot_reload: bool) -> RenderResult<Vec<u8>> {
    super::builtin_shaders::FOG_FROXEL.compile(hot_reload)
}

// Rebuild the fog graphics pipeline against the existing render pass +
// layout. Used by the Vulkan shader hot-reload path. The caller is
// responsible for destroying the previous pipeline only after this call
// succeeds.
pub(in crate::vulkan) fn rebuild_fog_pipeline(
    device: &VkDevice,
    fog: &FogResources,
    msaa: bool,
    hot_reload: bool,
) -> RenderResult<OwnedPipeline> {
    let (vert_spv, frag_spv) = compile_fog_shaders(hot_reload, msaa)?;
    create_fog_pipeline(
        device,
        fog.render_pass.handle(),
        fog.pipeline_layout.handle(),
        &vert_spv,
        &frag_spv,
    )
}

// Rebuild the froxel compute pipeline against the existing layout. Hot-reload.
pub(in crate::vulkan) fn rebuild_fog_froxel_pipeline(
    device: &VkDevice,
    fog: &FogResources,
    hot_reload: bool,
) -> RenderResult<OwnedPipeline> {
    let spv = compile_fog_froxel_shader(hot_reload)?;
    compute_pipeline(
        device,
        fog.froxel_pipeline_layout.handle(),
        &spv,
        "fog froxel",
    )
}

// The fog pass composites `(scattered, 1 - T)` over the SINGLE-SAMPLE resolved
// HDR target (`final = scattered + transmittance * scene`) regardless of MSAA.
fn create_fog_pipeline(
    device: &VkDevice,
    render_pass: vk::RenderPass,
    layout: vk::PipelineLayout,
    vert_spv: &[u8],
    frag_spv: &[u8],
) -> RenderResult<OwnedPipeline> {
    GraphicsPipelineDesc::fullscreen(
        vert_spv,
        frag_spv,
        layout,
        render_pass,
        &[Blend::PremultipliedOver],
    )
    .build(device, "fog")
}

// Encoder

impl VkContext {
    // Hot-reload entry point for the volumetric-fog tunables (driven by
    // `world.jsonl` hot-reload under `cn debug`). Writes the new
    // `Option<FogSettings>` into `self.fog.settings`; the next frame's graph
    // seed re-reads it (so `None` drops the FogFroxel + Fog passes) and
    // `encode_fog_froxel` rebuilds `FogParams` / `FogFroxelParams` from it.
    // Mirrors `MtlContext::update_fog_settings`.
    //
    // If the world started with no `VolumetricFog` (so `fog.resources` is
    // `None`), a `Some` update logs once and is dropped: re-enabling fog
    // mid-run requires a relaunch (the froxel pipeline + volume were never
    // built).
    //
    // Named distinctly from the `RenderBackend::update_fog_settings` trait
    // method so the backend forwarder's `self.apply_fog_settings(...)` is
    // unambiguous. Reached through the `RenderBackend` vtable (the bin's
    // `cn debug` world.jsonl hot-reload).
    pub(in crate::vulkan) fn apply_fog_settings(
        &mut self,
        settings: Option<volumetric_fog::FogSettings>,
    ) {
        if settings.is_some() && self.fog.resources.is_none() {
            tracing::warn!(
                "VolumetricFog hot-reload: world started without fog, so the fog \
                 pipeline + froxel volume were never built: re-enabling fog mid-run \
                 is not supported (relaunch required). Ignoring update."
            );
            return;
        }
        self.fog.settings = settings;
    }

    // Encode the volumetric-fog froxel-volume compute pass. Populates the 3D
    // `(scattered, 1 - T)` volume the fog fragment shader samples. The shared
    // graph seeds `PassId::FogFroxel` before `Fog` so the RAW edge orders the
    // dispatch ahead of the render-pass read. Uploads both per-frame UBOs
    // (`FogParams` + `FogFroxelParams`) so `encode_fog` only reads them.
    pub(in crate::vulkan) fn encode_fog_froxel(
        &self,
        rec: &Recorder<'_>,
        frame_idx: usize,
        near: f32,
        vp: [[f32; 4]; 4],
        cam_pos: [f32; 3],
    ) {
        let fog_settings = match &self.fog.settings {
            Some(s) => *s,
            None => return,
        };
        let fog = match &self.fog.resources {
            Some(f) => f,
            None => return,
        };

        // Per-frame FogParams (drives the volume integration + the fragment's
        // viewport / reconstruction). Uploaded here so `encode_fog` only reads.
        let inv_vp = mat4_inverse(vp);
        let viewport_pix = [
            self.targets.render_extent.width as f32,
            self.targets.render_extent.height as f32,
        ];
        let params = fog_settings.params(
            inv_vp,
            cam_pos,
            self.fog.sun_dir,
            self.fog.sun_color,
            viewport_pix,
        );
        // Per-frame FogFroxelParams: world->view matrix + the volume's discrete
        // dimensions + the linear-Z `[near, max_distance]` mapping. `near` is
        // clamped to >= 1e-3 so the linear-Z reconstruction stays finite.
        let froxel_params = FogFroxelParams {
            view: self.state.view.matrix,
            froxel_dims: [FOG_FROXEL_X, FOG_FROXEL_Y, FOG_FROXEL_Z],
            _pad_align: 0,
            z_near: near.max(1e-3),
            z_far: fog_settings.max_distance,
            _pad: [0.0; 2],
        };
        fog.params_ubos[frame_idx].write_val(0, &params);
        fog.froxel_ubos[frame_idx].write_val(0, &froxel_params);

        // Both of this pass's transitions are graph-driven. The froxel volume's
        // SHADER_READ_ONLY -> GENERAL open comes from the FogFroxel producer
        // barrier, whose source scope also orders the previous frame's fog
        // fragment read before this write; the shadow map's cascade tap is a
        // declared read of this pass, so the Shadow consumer barrier's stage union
        // carries the compute stage.
        rec.bind_pipeline(vk::PipelineBindPoint::COMPUTE, &fog.froxel_pipeline);
        rec.bind_descriptor_sets(
            vk::PipelineBindPoint::COMPUTE,
            &fog.froxel_pipeline_layout,
            0,
            std::slice::from_ref(&fog.froxel_sets[frame_idx]),
            &[],
        );
        rec.dispatch(
            FOG_FROXEL_X.div_ceil(FROXEL_TILE),
            FOG_FROXEL_Y.div_ceil(FROXEL_TILE),
            1,
        );

        // The froxel volume's GENERAL -> SHADER_READ_ONLY close comes from the
        // Fog consumer barrier, and next frame's Shadow producer opens from a
        // resting scope that names both shader stages, so this frame's compute tap
        // is ordered against it.
    }

    // Encode the volumetric-fog pass. Samples the 3D froxel volume the
    // `FogFroxel` compute pass populated this frame. Caller has already ended
    // the main HDR resolve and the projected-decal pass (if any), so
    // `depth_images[frame_idx]` holds the scene depth and
    // `hdr_resolve_images[frame_idx]` holds the resolved scene + decal color
    // in SHADER_READ_ONLY_OPTIMAL. Alpha-blends `(scattered, 1 - T)` over the
    // resolved HDR target. `FogParams` / `FogFroxelParams` were uploaded by
    // `encode_fog_froxel` for this frame's slot, so this pass only binds.
    pub(in crate::vulkan) fn encode_fog(
        &self,
        rec: &Recorder<'_>,
        frame_idx: usize,
        _vp: [[f32; 4]; 4],
        _cam_pos: [f32; 3],
    ) {
        if self.fog.settings.is_none() {
            return;
        }
        let fog = match &self.fog.resources {
            Some(f) => f,
            None => return,
        };

        let extent = self.targets.render_extent;

        // Main depth is already in SHADER_READ_ONLY for the fragment's scene-depth
        // sample: the graph declares this pass's depth read and the executor emits
        // the transition ahead of this command buffer.

        // Standard positive-height viewport: the fullscreen triangle is
        // emitted in NDC and the fragment shader's reconstruction handles
        // the Y flip against the main pass's depth (which was written with
        // a negative-height viewport).
        let vp_state = vk::Viewport {
            x: 0.0,
            y: 0.0,
            width: extent.width as f32,
            height: extent.height as f32,
            min_depth: 0.0,
            max_depth: 1.0,
        };
        let scissor = vk::Rect2D::default().extent(extent);

        rec.begin_render_pass(
            &fog.render_pass,
            &fog.framebuffers[frame_idx],
            vk::Rect2D::default().extent(extent),
            &[],
        );
        rec.set_viewport(&vp_state);
        rec.set_scissor(&scissor);
        rec.bind_pipeline(vk::PipelineBindPoint::GRAPHICS, &fog.pipeline);
        rec.bind_descriptor_sets(
            vk::PipelineBindPoint::GRAPHICS,
            &fog.pipeline_layout,
            0,
            std::slice::from_ref(&fog.view_sets[frame_idx]),
            &[],
        );
        rec.draw(3, 1, 0, 0);
        rec.end_render_pass();
    }
}

#[cfg(test)]
mod tests {
    use concinnity_core::gfx::render_types::{FogFroxelParams, FogParams};
    use std::mem::size_of;

    #[test]
    fn fog_params_ubo_size_matches_glsl() {
        // Both halves of fog.hlsl read the same 176 B std140 FogBlock.
        assert_eq!(size_of::<FogParams>(), 176);
    }

    #[test]
    fn fog_froxel_params_ubo_size_matches_glsl() {
        // The FogFroxelBlock std140 layout (mat4 + uvec3 + uint + 2 float + vec2)
        // is 96 B; the offsets are pinned by the core render_types tests.
        assert_eq!(size_of::<FogFroxelParams>(), 96);
    }

    #[test]
    fn fog_shaders_compile() {
        concinnity_shader::require_dxc!();
        // Compile the rewritten froxel-sampling fragment shader (both MSAA
        // modes) + the froxel compute kernel so a GLSL regression fails the
        // test suite without needing a GPU. Mirrors the cull-shader compile
        // guard the two-pass occlusion landing added.
        super::compile_fog_shaders(false, false).expect("fog shaders (no MSAA) compile");
        super::compile_fog_shaders(false, true).expect("fog shaders (MSAA) compile");
        super::compile_fog_froxel_shader(false).expect("fog froxel kernel compiles");
    }
}