crcbl-render 0.3.0

Crucible renderer: the 3D frame on crcbl-frame — meshes, materials, lights, effects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Topic 47's screen-space reflections (`docs/notes/rendering.md`): the two
//! full-screen passes between the forward pass and the tonemap.
//!
//! ```text
//! forward ──▶ scene-color ─────┐                  ┌─────────────┐
//!         └─▶ reflectivity ────┼──▶ ssr ──▶ reflection ──▶ ssr-blur ──▶ tonemap
//! prepass ──▶ scene-depth ─────┴──────────────────┘  (scene-reflected)
//! ```
//!
//! A module of its own rather than more of [`crate::forward`], on
//! [`crate::ssao`]'s terms exactly: what lives here is two pipelines, two caches
//! and the pass pair, and none of it is reachable from the geometry passes
//! except through [`Ssr::add_passes`].
//!
//! **The blur is the composite, and the march is not.** `ssr.slang` writes the
//! reflection by itself into an `Rgba16Float` transient; `ssr_blur.slang`
//! filters that image and writes the sum of it and the scene colour into a
//! second one, which [`ForwardRenderer::add_passes`] returns in place of the
//! scene colour. Had the march composited there would be no way to filter the
//! reflection without filtering the whole frame with it. Two passes, no blend
//! state, and no image that is both read and written.
//!
//! That is also the off-switch: a frame that does not add these passes hands the
//! scene colour on and is bit-identical, needing no placeholder because nothing
//! upstream reads the result.
//!
//! There is no device fact to gate on. Every backend has a full-screen draw, a
//! sampled `D32Float` and a sampled `Rgba8Unorm`, and the reflectivity
//! attachment is written whether or not these passes exist.
//!
//! [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes

use crcbl_hal::{
    BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
    BufferUsage, ClearValue, ColorTargetState, Device, Format, GraphicsPipelineHandle, HalError,
    ImageViewHandle, ImageViewType, LoadOp, MemoryLocation, PipelineLayoutDesc,
    PipelineLayoutHandle, QueueHandle, SampleType, ShaderStages, StoreOp,
    check_portable_storage_buffers,
};
use crcbl_shaders::{SSR, SSR_BLUR, dfg, sky_prefilter, ssr};

use crate::graph::{ImageId, RenderGraph};
use crate::ssao::cached_group;
use crate::texture::{UploadedTexture, upload_texture};

/// The binding `ssr.slang` reads [`sky_prefilter`]'s table through — after the
/// pyramid's slots, so Metal's declaration-order argument numbering stays
/// aligned with this layout.
const SKY_PREFILTER_BINDING: u32 = 5 + crate::hiz::MAX_LEVELS;

/// [`sky_prefilter::PREFILTER_SIZE`] as an image extent.
const SKY_PREFILTER_SIZE: u32 = sky_prefilter::PREFILTER_SIZE as u32;

/// The binding `ssr.slang` reads [`dfg`]'s pair through, beside the sky table.
const DFG_BINDING: u32 = SKY_PREFILTER_BINDING + 1;

/// [`dfg::DFG_SIZE`] as an image extent.
const DFG_SIZE: u32 = dfg::DFG_SIZE as u32;

/// The binding `ssr.slang` reads the irradiance probes' per-probe
/// visibility maps through — the image [`crate::forward`] binds to `mesh.slang`,
/// so that the reflection's probe fallback is weighed by the same Chebyshev
/// bound the diffuse gather is and stops reading a probe through a wall.
///
/// **Appended past [`DFG_BINDING`], never inserted**, for the reason
/// [`crate::forward`]'s own binding constants give: `crcbl-mtl` numbers a
/// resource by counting the same-table entries of the layout list and Slang
/// numbers a stage's arguments by declaration order, so the two agree only while
/// both ascend. `msl/ssr.metal` puts it at `texture(10)`, the next free index of
/// that table.
const PROBE_VISIBILITY_BINDING: u32 = DFG_BINDING + 1;

/// The binding `ssr.slang` reads the sky-view LUT through — the very buffer
/// [`crate::sky_pass`] draws the background out of, so a mirror and the sky
/// behind it cannot be reading two different skies.
///
/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for that
/// constant's own reason: `crcbl-mtl` numbers a resource by counting the
/// same-table entries in ascending binding order and Slang numbers a stage's
/// arguments by declaration order, so the two agree only while both ascend.
/// This is the pass's **second** storage buffer — [`crate::forward`]'s probe
/// table is the first — against the eight per stage a WebGPU device
/// guarantees, and `check_portable_storage_buffers` below is what says so
/// rather than this comment. `msl/ssr.metal` puts it at `buffer(2)`, the next
/// free index of that table.
const SKY_VIEW_BINDING: u32 = PROBE_VISIBILITY_BINDING + 1;

/// Vertices in the over-sized full-screen triangle `ssr.slang` and
/// `ssr_blur.slang` generate from `SV_VertexID`. No geometry is bound anywhere.
const FULLSCREEN_VERTICES: u32 = 3;

/// The graph transients [`Ssr::add_passes`] reads and writes.
///
/// **One struct rather than five positional arguments** — which is what
/// `clippy::too_many_arguments` objects to and also what makes five values of
/// one type impossible to swap at the call site. `crate::texture`'s
/// `UploadArgs` is the same shape for the same reason.
#[derive(Clone, Copy, Debug)]
pub(crate) struct SsrImages {
    /// The depth prepass's stored depth, marched by the first pass and weighed
    /// by the second.
    pub(crate) depth: ImageId,
    /// The forward pass's scene target: where a hit's colour comes from, and
    /// what the blur adds the filtered reflection to.
    pub(crate) color: ImageId,
    /// The forward pass's reflectivity attachment. Read by the march alone —
    /// the blur takes the roughness ramp out of [`SsrImages::reflection`]'s
    /// alpha instead.
    pub(crate) reflectivity: ImageId,
    /// The march's output: the reflection by itself, with its weight in the
    /// alpha.
    pub(crate) reflection: ImageId,
    /// The blur's output, and the image the caller must go on to tonemap.
    pub(crate) composited: ImageId,
    /// Levels 1 upwards of the Hi-Z pyramid the march climbs, one slot per
    /// binding and **every slot filled** — a frame with a shorter pyramid than
    /// bindings repeats its deepest level, and one with no pyramid at all
    /// repeats [`SsrImages::depth`]. See [`crate::hiz::level_slots`], which is
    /// what the caller fills this with, and `SsrParams::hiz_levels`, which is
    /// what stops the march reading a slot that is a repeat.
    pub(crate) pyramid: [ImageId; crate::hiz::MAX_LEVELS as usize],
}

/// The environment a missed ray falls back to, as the four handles the march
/// binds it through.
///
/// **One struct rather than four positional arguments**, on [`SsrImages`]'
/// terms exactly: it is what `clippy::too_many_arguments` objects to, and two
/// of these are `BufferHandle`s that would be indistinguishable at the call
/// site. They travel together because they are one idea —
/// topic 43 §8's "the environment a missed ray falls
/// back to is the term a sky provides", plus
/// the irradiance probes' grid for the bounce light around it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct SsrEnvironment {
    /// The irradiance table the forward pass binds to `mesh.slang`, so a
    /// reflection's probe fallback is the same grid the diffuse gather reads.
    pub(crate) probes: BufferHandle,
    /// [`SsrEnvironment::probes`] as the graph knows it, for the read this pass
    /// declares.
    pub(crate) probe_id: crate::graph::BufferId,
    /// The per-probe visibility maps — the caller's captured ones when it has
    /// them and the console switch is on, and its one-texel placeholder
    /// otherwise, which every probe keeps all of its weight through. Not a
    /// graph transient, so it is not realised in the pass body; it does change
    /// between frames when the switch moves, which is why it joins the bind
    /// group's cache key.
    pub(crate) probe_visibility: ImageViewHandle,
    /// [`crate::sky_pass::SkyPass::lut`] for the same frame slot — the buffer
    /// the background pass draws this frame's sky out of, holding zeroes on a
    /// frame whose sky is a gradient or which has none. One handle per slot
    /// that never moves within a slot, so it stays out of the cache key beside
    /// the uniforms and the probe table.
    pub(crate) sky_view: BufferHandle,
}

/// Everything the reflection pair owns.
///
/// Built once by [`Ssr::new`] and released by [`Ssr::destroy`], which is the
/// shape every other resource group in this crate has — see [`crate::ssao`].
#[derive(Debug)]
pub(crate) struct Ssr {
    /// `[frame]`: `ssr.slang`'s uniform block. One per frame in flight for the
    /// frame uniforms' reason exactly — the previous frame may still be reading
    /// last frame's while this one is written.
    ///
    /// **A block of its own rather than the occlusion pair's**, which carries
    /// the same two matrices and a radius and a bias besides. Sharing the buffer
    /// would make a pass that is meant to stand alone depend on that pair having
    /// been built, for 128 bytes per frame in flight.
    uniforms: Vec<BufferHandle>,
    layout: BindGroupLayoutHandle,
    pipeline_layout: PipelineLayoutHandle,
    pipeline: GraphicsPipelineHandle,
    /// `[frame]`: the group, cached against all three views together.
    ///
    /// **One per frame in flight**, because this group names [`Ssr::uniforms`]
    /// as well as three graph transients — and that is a ring. A single cache
    /// keyed on the views alone would hand the even frames' block to the odd
    /// frames.
    groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    blur_layout: BindGroupLayoutHandle,
    blur_pipeline_layout: PipelineLayoutHandle,
    blur_pipeline: GraphicsPipelineHandle,
    /// `[frame]`: the blur group, cached against its own three views together.
    ///
    /// **A ring for [`Ssr::groups`]' reason exactly**: `ssr_blur.slang` weights
    /// its kernel on view-space depth, so it binds the same [`Ssr::uniforms`]
    /// block the march does — and a single cache keyed on the views alone would
    /// hand the even frames' block to the odd frames.
    blur_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    /// `crcbl_shaders::sky_prefilter`'s table as the `Rgba8Unorm` image
    /// `ssr.slang` reads the sky through at a surface's roughness. Uploaded
    /// once here rather than by [`crate::forward`], because this pass is its
    /// only reader — the DFG table beside it in the forward pass has a reader
    /// there.
    sky_prefilter: UploadedTexture,
    /// `crcbl_shaders::dfg`'s pair as the `Rgba8Unorm` image `ssr.slang`
    /// scales its environment by — `f0 · scale + bias`, the split-sum's second
    /// half. The same table [`crate::forward`] uploads summed to one channel
    /// for energy compensation; this pass wants both channels, so it carries
    /// its own image of them.
    dfg: UploadedTexture,
}

impl Ssr {
    /// Passes [`Ssr::add_passes`] adds to a frame.
    pub(crate) const PASSES: u32 = 2;

    /// Builds both pipelines and the uniform ring.
    ///
    /// `build_fullscreen` is handed in rather than duplicated, on
    /// [`Ssao::new`](crate::ssao::Ssao::new)'s terms: it is [`crate::forward`]'s,
    /// because the shape it carries — a triangle out of `SV_VertexID`, no depth
    /// state, one colour target — is documented there.
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. **Nothing is released on the failing
    /// path**, for the reason every other builder in this crate gives: the
    /// caller holds a rollback, and this is stored in it whole.
    pub(crate) fn new(
        device: &dyn Device,
        queue: QueueHandle,
        frames: usize,
        build_fullscreen: impl Fn(
            &dyn Device,
            &str,
            &crcbl_shaders::Shader,
            PipelineLayoutHandle,
            &[ColorTargetState],
        ) -> Result<GraphicsPipelineHandle, HalError>,
    ) -> Result<Self, HalError> {
        // The committed table, fixed point in four bytes a texel — see
        // `sky_prefilter::PREFILTER_TEXEL_BYTES`. Not baked here, for the DFG
        // table's reason in `crate::forward`: the integrator is a Monte Carlo
        // sum and four backends would bake four tables.
        let sky_prefilter = upload_texture(
            device,
            queue,
            "sky prefilter table",
            Format::Rgba8Unorm,
            SKY_PREFILTER_SIZE,
            SKY_PREFILTER_SIZE,
            &sky_prefilter::texels(),
        )?;
        let dfg_pair = upload_texture(
            device,
            queue,
            "dfg pair table",
            Format::Rgba8Unorm,
            DFG_SIZE,
            DFG_SIZE,
            &dfg::pair_texels(),
        )?;

        // **No sampler**, which is the whole of what reading by `Load` buys —
        // and it buys more here than in the occlusion pass, because what a tap
        // fetches is a colour rather than a fraction a blur will average. See
        // the binding comments in `shaders/ssr.slang`.
        let entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // **`Depth`, and it is the seam's half of `DepthTexture2D`.**
                    // WebGPU will only bind a `D32Float` view through a depth
                    // sample type, and the WGSL artifact agrees — it declares
                    // `texture_depth_2d`, which `textureLoad` takes. The
                    // paragraph on `crate::ssao`'s own depth binding is this
                    // one's too: it is the same image, read the same way.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // The `Rgba16Float` scene target: an ordinary colour image,
                    // and the WGSL artifact declares `texture_2d<f32>` for it.
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 3,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // The `Rgba8Unorm` reflectivity attachment, on the scene
                    // colour's terms: `SAMPLED` is on
                    // `crate::targets::reflectivity` because *this* pass is
                    // the thing that reads it.
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 4,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::StorageBuffer {
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        // Levels 1 upwards of the depth pyramid, one binding each rather than
        // one array binding: `ssr.slang` reads them through a `switch` on the
        // level, which is what keeps the whole march inside a texture type WGSL
        // will index without a binding array — see that shader's `hiz_at`.
        // Level 0 is binding 1 above, which is the prepass itself.
        let mut entries = entries.to_vec();
        entries.push(BindGroupLayoutEntry {
            binding: SKY_PREFILTER_BINDING,
            visibility: ShaderStages::FRAGMENT,
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                // An ordinary colour image the shader `Load`s and filters
                // itself; no sampler, like every other read in the pass.
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        entries.push(BindGroupLayoutEntry {
            binding: DFG_BINDING,
            visibility: ShaderStages::FRAGMENT,
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2,
                sample_type: SampleType::Float,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // The per-probe visibility maps, at the highest binding of the set — see
        // [`PROBE_VISIBILITY_BINDING`] on why the number rather than the list
        // position is what has to ascend.
        //
        // `D2Array` and `UnfilterableFloat` are both *declared* rather than
        // merely bound, which is [`crate::forward`]'s note on the same image:
        // WebGPU compares the dimension and the sample type a layout entry
        // claims against the view handed to it, the image is `Rg32Float`, and
        // `Rg32Float` is unfilterable without the `float32-filterable` feature.
        // Reading it only with `Load` does not lift that — the check is on the
        // layout against the view's format, not on how the shader gets at it.
        entries.push(BindGroupLayoutEntry {
            binding: PROBE_VISIBILITY_BINDING,
            visibility: ShaderStages::FRAGMENT,
            kind: BindingKind::SampledImage {
                view_type: ImageViewType::D2Array,
                sample_type: SampleType::UnfilterableFloat,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        // The sky-view LUT, past it — see [`SKY_VIEW_BINDING`]. `FRAGMENT`
        // alone, like the probe table at binding 4 and unlike
        // `crate::sky_pass`'s copy of this buffer: Slang's Metal backend
        // materialises every global into both entry points there too, and
        // `msl/ssr.metal`'s `vertexMain` has taken `probes` at `buffer(1)`
        // without reading it since that binding landed.
        entries.push(BindGroupLayoutEntry {
            binding: SKY_VIEW_BINDING,
            visibility: ShaderStages::FRAGMENT,
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: crcbl_shaders::atmosphere::SKY_VIEW_ROW_BYTES as u32,
            },
            count: 1,
            flags: BindingFlags::empty(),
        });
        entries.extend(
            (0..crate::hiz::MAX_LEVELS).map(|level| BindGroupLayoutEntry {
                binding: 5 + level,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Depth`, and the paragraph on binding 1 is this one's too:
                    // every level is `D32Float`, which is the point of the pyramid
                    // being depth images rather than `R32Float` ones.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            }),
        );
        let desc = BindGroupLayoutDesc {
            label: Some("ssr"),
            entries: &entries,
        };
        check_portable_storage_buffers(Some("ssr"), &[&desc])?;
        let layout = device.create_bind_group_layout(&desc)?;
        let set_layouts = [layout];
        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("ssr"),
            bind_group_layouts: &set_layouts,
            push_constants: None,
        })?;

        // **The same shape as the march, with the raw reflection where the
        // reflectivity attachment was.** The blur reads the sharpness ramp out
        // of that image's alpha rather than reading the attachment a second
        // time, which is why this list is not one binding longer — see
        // `shaders/ssr_blur.slang`.
        let blur_entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Depth`, and the paragraph on the march's own depth
                    // binding is this one's too: it is the same image, read
                    // through the same `texture_depth_2d`.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // The `Rgba16Float` scene target, which this pass adds the
                    // filtered reflection to.
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 3,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // The march's own output, on the scene colour's terms: an
                    // ordinary `Rgba16Float` image read by `Load`.
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        let blur_desc = BindGroupLayoutDesc {
            label: Some("ssr blur"),
            entries: &blur_entries,
        };
        check_portable_storage_buffers(Some("ssr blur"), &[&blur_desc])?;
        let blur_layout = device.create_bind_group_layout(&blur_desc)?;
        let blur_set_layouts = [blur_layout];
        let blur_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("ssr blur"),
            bind_group_layouts: &blur_set_layouts,
            push_constants: None,
        })?;

        // The same format the forward pass wrote, for both: the blur's output is
        // that image plus a term, so a narrower target would tonemap a truncated
        // scene and the reflection would be blamed for it — and the march's is a
        // reflection out of that same image, which an eight-bit target would
        // clip to the tonemap's range before the tonemap ever saw it.
        let targets = [ColorTargetState::opaque(Format::Rgba16Float)];
        let pipeline = build_fullscreen(device, "ssr", &SSR, pipeline_layout, &targets)?;
        let blur_pipeline = build_fullscreen(
            device,
            "ssr blur",
            &SSR_BLUR,
            blur_pipeline_layout,
            &targets,
        )?;

        let mut uniforms = Vec::with_capacity(frames);
        for _ in 0..frames {
            uniforms.push(device.create_buffer(&BufferDesc {
                label: Some("ssr params"),
                size: ssr::PARAMS_SIZE as u64,
                usage: BufferUsage::UNIFORM,
                memory: MemoryLocation::HostUpload,
            })?);
        }

        Ok(Self {
            uniforms,
            layout,
            pipeline_layout,
            pipeline,
            groups: vec![None; frames],
            blur_layout,
            blur_pipeline_layout,
            blur_pipeline,
            blur_groups: vec![None; frames],
            sky_prefilter,
            dfg: dfg_pair,
        })
    }

    /// `frame`'s uniform block — the buffer [`Ssr::begin_frame`] writes.
    ///
    /// **Handed to [`crate::water`] rather than copied for it**, on
    /// [`crate::sky_pass::SkyPass::lut`]'s terms: the water surface reflects the
    /// probe grid and the sky exactly as this pass falls back to them, so it
    /// binds this block itself. It is written on every frame whether or not the
    /// march runs, which is what lets a frame with reflections off still have a
    /// surface that reflects.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn uniforms(&self, frame: usize) -> BufferHandle {
        self.uniforms[frame]
    }

    /// The sky prefilter table's view — see [`Ssr::uniforms`] for why
    /// [`crate::water`] reads this rather than uploading the table again.
    pub(crate) fn sky_prefilter_view(&self) -> ImageViewHandle {
        self.sky_prefilter.view
    }

    /// Writes `frame`'s uniform block.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the mapped write.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn begin_frame(
        &self,
        device: &dyn Device,
        frame: usize,
        params: ssr::SsrParams,
    ) -> Result<(), HalError> {
        device.write_buffer(self.uniforms[frame], 0, &params.to_bytes())
    }

    /// Adds the `ssr` and `ssr-blur` passes, in that order.
    ///
    /// Both reflection images are the caller's so it can declare the read on the
    /// pass that consumes the second one — a pass declares its own accesses and
    /// this one cannot declare the tonemap's.
    /// [`SsrImages::composited`] is what the caller must go on to tonemap and
    /// hand back: the reflection is *in* it, and the scene colour it was added
    /// to is not the finished picture any more.
    ///
    /// `environment` is what a ray that found nothing falls back to — see
    /// [`SsrEnvironment`], which is where each of its four handles is
    /// described.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn add_passes<'a>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        frame: usize,
        images: SsrImages,
        environment: SsrEnvironment,
    ) {
        let SsrEnvironment {
            probes,
            probe_id,
            probe_visibility,
            sky_view,
        } = environment;
        let SsrImages {
            depth,
            color,
            reflectivity,
            reflection,
            composited,
            pyramid,
        } = images;
        let pipeline = self.pipeline;
        let pipeline_layout = self.pipeline_layout;
        let layout = self.layout;
        let uniforms = self.uniforms[frame];
        let sky_prefilter_view = self.sky_prefilter.view;
        let dfg_view = self.dfg.view;
        // Split so the two closures below borrow different halves of `self`, on
        // `Ssao::add_passes`' terms: one `&mut self` shared between them is what
        // the borrow checker refuses, and it would be refusing something
        // genuinely wrong — a pass body may run at any point after it is
        // declared.
        let (groups, blur_groups) = (&mut self.groups, &mut self.blur_groups);
        let cached = &mut groups[frame];
        let blur_cached = &mut blur_groups[frame];

        // The pyramid slots, deduplicated against the depth prepass and against
        // each other: a short pyramid repeats its deepest level into the slots
        // above, and declaring one image's read twice would have the graph emit
        // a barrier for a transition that has already happened.
        let mut pyramid_reads: Vec<ImageId> = Vec::with_capacity(pyramid.len());
        for level in pyramid {
            if level != depth && !pyramid_reads.contains(&level) {
                pyramid_reads.push(level);
            }
        }

        let mut pass = graph
            .add_render_pass("ssr")
            // `DontCare`, not `Clear`: the full-screen triangle writes every
            // pixel of the target — a pixel with no reflection writes zero — so
            // loading or clearing it is pure bandwidth.
            .color(
                reflection,
                LoadOp::DontCare,
                StoreOp::Store,
                ClearValue::default(),
            )
            // The forward pass left both of these in `ColorAttachment` and the
            // prepass left the depth in `DepthStencilWrite`. Declaring the reads
            // is what moves each into a shader-readable layout, and without them
            // every backend reads whatever the last writer left behind.
            .read_image(color)
            .read_image(depth)
            .read_image(reflectivity)
            .read_buffer(probe_id);
        for level in pyramid_reads {
            // Each level was this pass's own reduction's depth attachment a
            // moment ago, so this declaration is its barrier into a
            // shader-readable layout.
            pass = pass.read_image(level);
        }
        pass.execute(move |ctx| {
            let color_view = ctx.image_view(color);
            let depth_view = ctx.image_view(depth);
            let material_view = ctx.image_view(reflectivity);
            let device = ctx.device();
            const BASE_ENTRY_COUNT: usize = 9;
            const BASE_KEY_COUNT: usize = 4;
            let base: [BindGroupEntry; BASE_ENTRY_COUNT] = [
                BindGroupEntry {
                    binding: 0,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(uniforms),
                },
                // The three below are overwritten by `cached_group` with the
                // realised views; written here so the list is a complete
                // description of the layout rather than a list with holes in
                // it.
                BindGroupEntry {
                    binding: 1,
                    array_index: 0,
                    resource: BindingResource::ImageView(depth_view),
                },
                BindGroupEntry {
                    binding: 2,
                    array_index: 0,
                    resource: BindingResource::ImageView(color_view),
                },
                BindGroupEntry {
                    binding: 3,
                    array_index: 0,
                    resource: BindingResource::ImageView(material_view),
                },
                BindGroupEntry {
                    binding: 4,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(probes),
                },
                // Static, like the uniforms and the probes: not part of the
                // cache key below, which holds the views that change.
                BindGroupEntry {
                    binding: SKY_PREFILTER_BINDING,
                    array_index: 0,
                    resource: BindingResource::ImageView(sky_prefilter_view),
                },
                BindGroupEntry {
                    binding: DFG_BINDING,
                    array_index: 0,
                    resource: BindingResource::ImageView(dfg_view),
                },
                // Overwritten by `cached_group` with the same view, which is
                // what puts it in the key: the two tables above never move and
                // this one does, whenever a capture lands or the console switch
                // is toggled.
                BindGroupEntry {
                    binding: PROBE_VISIBILITY_BINDING,
                    array_index: 0,
                    resource: BindingResource::ImageView(probe_visibility),
                },
                // Static within a frame slot, like the uniforms and the probes
                // above: the sky pass owns one buffer per slot and writes this
                // frame's LUT into it before the graph runs.
                BindGroupEntry {
                    binding: SKY_VIEW_BINDING,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(sky_view),
                },
            ];
            let pyramid_views = pyramid.map(|level| ctx.image_view(level));
            let entries: [BindGroupEntry; BASE_ENTRY_COUNT + crate::hiz::MAX_LEVELS as usize] =
                std::array::from_fn(|index| {
                    if index < base.len() {
                        base[index]
                    } else {
                        let level = index - base.len();
                        BindGroupEntry {
                            binding: 5 + u32::try_from(level)
                                .unwrap_or_else(|_| unreachable!("a pyramid of a few levels")),
                            array_index: 0,
                            resource: BindingResource::ImageView(pyramid_views[level]),
                        }
                    }
                });
            let base_key: [(u32, ImageViewHandle); BASE_KEY_COUNT] = [
                (1, depth_view),
                (2, color_view),
                (3, material_view),
                (PROBE_VISIBILITY_BINDING, probe_visibility),
            ];
            let key: [(u32, ImageViewHandle); BASE_KEY_COUNT + crate::hiz::MAX_LEVELS as usize] =
                std::array::from_fn(|index| {
                    if index < base_key.len() {
                        base_key[index]
                    } else {
                        let level = index - base_key.len();
                        (
                            5 + u32::try_from(level)
                                .unwrap_or_else(|_| unreachable!("a pyramid of a few levels")),
                            pyramid_views[level],
                        )
                    }
                });
            let Some(group) = cached_group(cached, device, &key, "ssr", layout, &entries) else {
                return;
            };
            let encoder = ctx.encoder();
            encoder.bind_graphics_pipeline(pipeline);
            encoder.bind_group(0, group, &[], pipeline_layout);
            encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
        });

        let blur_pipeline = self.blur_pipeline;
        let blur_pipeline_layout = self.blur_pipeline_layout;
        let blur_layout = self.blur_layout;
        graph
            .add_render_pass("ssr-blur")
            .color(
                composited,
                LoadOp::DontCare,
                StoreOp::Store,
                ClearValue::default(),
            )
            // **The march's own output**, which it wrote as a colour attachment
            // a moment ago, so this declaration is the barrier into a
            // shader-readable layout.
            .read_image(reflection)
            // The scene colour and the depth again: the pass above declared its
            // own reads, and a barrier the graph was never told about is one it
            // does not insert.
            .read_image(color)
            .read_image(depth)
            .execute(move |ctx| {
                let color_view = ctx.image_view(color);
                let depth_view = ctx.image_view(depth);
                let reflection_view = ctx.image_view(reflection);
                let device = ctx.device();
                let entries = [
                    BindGroupEntry {
                        binding: 0,
                        array_index: 0,
                        resource: BindingResource::whole_buffer(uniforms),
                    },
                    // The three below are overwritten by `cached_group` with the
                    // realised views; written here so the list is a complete
                    // description of the layout rather than a list with holes in
                    // it.
                    BindGroupEntry {
                        binding: 1,
                        array_index: 0,
                        resource: BindingResource::ImageView(depth_view),
                    },
                    BindGroupEntry {
                        binding: 2,
                        array_index: 0,
                        resource: BindingResource::ImageView(color_view),
                    },
                    BindGroupEntry {
                        binding: 3,
                        array_index: 0,
                        resource: BindingResource::ImageView(reflection_view),
                    },
                ];
                let Some(group) = cached_group(
                    blur_cached,
                    device,
                    &[(1, depth_view), (2, color_view), (3, reflection_view)],
                    "ssr blur",
                    blur_layout,
                    &entries,
                ) else {
                    return;
                };
                let encoder = ctx.encoder();
                encoder.bind_graphics_pipeline(blur_pipeline);
                encoder.bind_group(0, group, &[], blur_pipeline_layout);
                encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
            });
    }

    /// Releases everything, in dependency order. The device must be idle.
    pub(crate) fn destroy(self, device: &dyn Device) {
        for cached in self.groups.into_iter().chain(self.blur_groups).flatten() {
            device.destroy_bind_group(cached.1);
        }
        device.destroy_graphics_pipeline(self.blur_pipeline);
        device.destroy_pipeline_layout(self.blur_pipeline_layout);
        device.destroy_bind_group_layout(self.blur_layout);
        device.destroy_graphics_pipeline(self.pipeline);
        device.destroy_pipeline_layout(self.pipeline_layout);
        device.destroy_bind_group_layout(self.layout);
        for buffer in self.uniforms {
            device.destroy_buffer(buffer);
        }
        self.sky_prefilter.destroy(device);
        self.dfg.destroy(device);
    }
}