Skip to main content

crcbl_render/forward/
view.rs

1//! One camera's share of the forward frame.
2//!
3//! [`ForwardRenderer`] owns two kinds of state, and this module is the line
4//! between them. The **scene** is what every camera draws: the geometry and
5//! instance pools, the materials and their pages, the probes, the shadow atlas
6//! and everything that decides what it holds. A **view** is what one camera
7//! needs to turn that scene into a picture: its own cull and the survivor lists
8//! it writes, its frame block, its light clustering, its bind groups and the
9//! ring of per-frame blocks every screen-space pass keeps.
10//!
11//! # Why the line is here
12//!
13//! Everything on this side is either sized by what one camera sees or carries
14//! one camera's history from a frame to the next. Topic 25's
15//! hysteresis lives in [`DrawGen::group_state`], so two cameras sharing one
16//! generator would each undo the other's cut. Auto-exposure reads the previous
17//! slot's measurement, and [`View::previous_view_projection`] is where the
18//! motion vectors come from. Every one of those is wrong the moment a second
19//! camera writes it.
20//!
21//! Nothing on the other side is. An instance is where it is whoever looks at
22//! it, and the shadow atlas is drawn once for the frame.
23
24use super::*;
25use crate::draw_gen::OcclusionFrame;
26
27/// How many views one [`ForwardRenderer`] draws at most, the camera
28/// [`ForwardRenderer::begin_frame`] opens included.
29///
30/// The width of
31/// [`GpuInstance::HIDDEN_VIEWS_MASK`](crcbl_shaders::mesh::GpuInstance::HIDDEN_VIEWS_MASK),
32/// which is where a view's bit lives: an instance record has one bit per view
33/// to say it is hidden there, and a ninth view would have no bit to cull on.
34pub const MAX_VIEWS: usize = 8;
35
36/// Names one camera a [`ForwardRenderer`] draws.
37///
38/// [`ViewId::PRIMARY`] is the camera [`ForwardRenderer::begin_frame`] opens and
39/// always exists. Every other id comes from [`ForwardRenderer::create_view`]
40/// and stays valid until [`ForwardRenderer::destroy_view`] hands it back, after
41/// which the renderer may give the same id to the next view it creates.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct ViewId(u8);
44
45impl ViewId {
46    /// The camera [`ForwardRenderer::begin_frame`] opens, and the one
47    /// [`ForwardRenderer::add_passes`] draws into the caller's target.
48    pub const PRIMARY: Self = Self(0);
49
50    /// This view's index: `0` for [`ViewId::PRIMARY`], and below [`MAX_VIEWS`]
51    /// for every other.
52    #[must_use]
53    pub const fn index(self) -> usize {
54        self.0 as usize
55    }
56
57    /// The bit of [`GpuInstance::flags`](crcbl_shaders::mesh::GpuInstance::flags)
58    /// that hides an instance from this view.
59    pub(super) const fn hidden_bit(self) -> u32 {
60        1 << (mesh::GpuInstance::HIDDEN_VIEWS_SHIFT + self.0 as u32)
61    }
62}
63
64/// The views an instance is drawn in — see
65/// [`ForwardRenderer::set_instance_views`].
66///
67/// A set of [`ViewId`]s, one bit each. [`ViewMask::ALL`] is what every instance
68/// starts with, so a caller that never names a view draws everything in every
69/// view.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub struct ViewMask(u8);
72
73impl ViewMask {
74    /// Every view, including the ones not created yet.
75    pub const ALL: Self = Self(u8::MAX);
76    /// No view at all: the instance stays resident, and every camera's cull
77    /// rejects it before it tests a bound.
78    pub const NONE: Self = Self(0);
79
80    /// `view` alone.
81    #[must_use]
82    pub const fn only(view: ViewId) -> Self {
83        Self(1 << view.0)
84    }
85
86    /// This set with `view` added.
87    #[must_use]
88    pub const fn with(self, view: ViewId) -> Self {
89        Self(self.0 | (1 << view.0))
90    }
91
92    /// This set with `view` taken out.
93    #[must_use]
94    pub const fn without(self, view: ViewId) -> Self {
95        Self(self.0 & !(1 << view.0))
96    }
97
98    /// Whether `view` draws an instance carrying this set.
99    #[must_use]
100    pub const fn contains(self, view: ViewId) -> bool {
101        self.0 & (1 << view.0) != 0
102    }
103
104    /// The hidden-views bits an instance record carries for this set — its
105    /// complement, so [`ViewMask::ALL`] is the all-zero field every record
106    /// starts with.
107    pub(super) const fn hidden_bits(self) -> u32 {
108        ((!self.0) as u32) << mesh::GpuInstance::HIDDEN_VIEWS_SHIFT
109    }
110
111    /// The set an instance record's hidden-views bits describe.
112    pub(super) const fn from_flags(flags: u32) -> Self {
113        let hidden =
114            (flags & mesh::GpuInstance::HIDDEN_VIEWS_MASK) >> mesh::GpuInstance::HIDDEN_VIEWS_SHIFT;
115        Self(!(hidden as u8))
116    }
117}
118
119/// What a [`ViewBackground::Transparent`] view's scene colour is cleared to.
120const TRANSPARENT_CLEAR: [f32; 4] = [0.0; 4];
121
122/// What [`ForwardRenderer::create_view`] builds.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct ViewDesc {
125    /// The effects this view may draw — intersected, every frame, with what the
126    /// frame resolved (see [`ForwardRenderer::resolved_effects`]), so a view
127    /// can ask for less than the frame draws and never for more.
128    ///
129    /// [`RenderEffects::SHADOWS`] is not a view's to take away and is ignored
130    /// here: the atlas is drawn once for the frame, and every view samples it
131    /// whenever the frame drew it. A [`ViewLighting::Fixed`] view also never
132    /// draws [`ViewLighting::SCENE_EFFECTS`], whatever this asks for.
133    pub effects: RenderEffects,
134    /// What the view's picture holds where no geometry is — see
135    /// [`ViewBackground`].
136    pub background: ViewBackground,
137    /// What lights the view's surfaces — see [`ViewLighting`].
138    pub lighting: ViewLighting,
139}
140
141impl Default for ViewDesc {
142    /// Every effect the frame draws, over the frame's own background, lit by
143    /// the frame's own light.
144    fn default() -> Self {
145        Self {
146            effects: RenderEffects::all(),
147            background: ViewBackground::Scene,
148            lighting: ViewLighting::Scene,
149        }
150    }
151}
152
153impl ViewDesc {
154    /// A [`ViewBackground::Transparent`] view with every effect the frame draws
155    /// except the ones such a view cannot take, and auto-exposure.
156    ///
157    /// The two antialiasing tiers are what
158    /// [`ForwardRenderer::create_view`] refuses on a transparent view.
159    /// [`RenderEffects::AUTO_EXPOSURE`] it would accept, and it is left out
160    /// because the meter reads the whole target: the transparent background is
161    /// metered as black, so a model filling a quarter of the picture would be
162    /// exposed differently from the same model filling half of it. The view
163    /// takes the caller's exposure instead — see
164    /// [`ForwardRenderer::set_exposure`].
165    #[must_use]
166    pub const fn transparent() -> Self {
167        Self {
168            effects: RenderEffects::all().difference(
169                ViewBackground::REFUSED_ON_TRANSPARENT.union(RenderEffects::AUTO_EXPOSURE),
170            ),
171            background: ViewBackground::Transparent,
172            lighting: ViewLighting::Scene,
173        }
174    }
175}
176
177/// What lights a view's surfaces — see [`ViewDesc::lighting`].
178#[derive(Clone, Copy, Debug, Default, PartialEq)]
179pub enum ViewLighting {
180    /// The frame's own light: the sun and every light row
181    /// [`ForwardRenderer::set_lights`] handed over, the sky's irradiance, the
182    /// irradiance probes, the reflections and the fog. What the primary camera
183    /// is lit by, and what every view was lit by before this choice existed.
184    #[default]
185    Scene,
186    /// One constant light, whatever the frame is lit by: the key's direction
187    /// and colour as the only direct light, its
188    /// [`ambient`](DirectionalLight::ambient) as the only diffuse indirect one,
189    /// and `environment` as the only thing a reflection sees.
190    ///
191    /// For a picture that must not change with the world around it, such as a
192    /// model rendered into an inventory icon: the same model under the same
193    /// fixed light draws the same pixels in a sunlit level and a dark one.
194    ///
195    /// # What it ignores
196    ///
197    /// * **The frame's sun and every light row** — a point, spot or rectangle
198    ///   light near the view's camera included. The key light is the view's
199    ///   one row, which is a choice rather than a limit: an icon's model is
200    ///   placed away from the world, so a local light that did reach it would
201    ///   be lighting it by accident.
202    /// * **Every shadow.** The key light is not occluded — not by the frame's
203    ///   cascades, which were fitted to the primary camera and cover whatever
204    ///   happens to be there, and not by contact shadows. The view's frame
205    ///   block names no shadow map: every atlas rectangle in it is empty, which
206    ///   the shaders read as a map never rendered and answer lit. The frame's
207    ///   atlas is still drawn and the view's instances may still cast into it;
208    ///   see [`ForwardRenderer::set_instance_casts_shadow`].
209    /// * **The sky and the irradiance probes**: the view's frame block carries
210    ///   no sky rows and an empty probe header, and the view binds a probe
211    ///   table of one zeroed row in place of the scene's — to the forward pass,
212    ///   the reflection march and the water surface alike — so the diffuse
213    ///   ambient is the fill alone and a reflection that finds no geometry
214    ///   sees `environment` alone.
215    /// * **The air**: [`Self::SCENE_EFFECTS`] are dropped from the view's
216    ///   effects whatever [`ViewDesc::effects`] asked for, and the height fog
217    ///   is [`Fog::NONE`].
218    ///
219    /// What it keeps is everything the view's own geometry decides: its
220    /// materials and emission, its ambient occlusion, its reflections of
221    /// itself, and every effect after the forward pass. The background is
222    /// [`ViewDesc::background`]'s, so a view asking for
223    /// [`ViewBackground::Scene`] still draws the frame's sky behind a model it
224    /// does not light.
225    Fixed {
226        /// The one direct light, and in its
227        /// [`ambient`](DirectionalLight::ambient) the diffuse fill.
228        key: DirectionalLight,
229        /// The radiance a reflection sees in every direction — a uniform
230        /// environment, in linear RGB, that **may exceed 1.0** like the key's
231        /// colour. It is what gives a dark glossy surface its sheen: a
232        /// near-black dielectric scatters almost none of the key and the fill,
233        /// and still reflects this at its `F0`, rising towards grazing angles
234        /// by the split-sum Fresnel term — so what the camera sees edge-on
235        /// reads brighter than what faces it. A metal reflects it tinted by
236        /// its base colour.
237        ///
238        /// **Specular only.** A uniform environment of radiance `L` would also
239        /// reach a diffuse surface, as `π·L` — what [`Self::Scene`] adds for
240        /// a uniform [`crate::Sky`] of that radiance — but here that half
241        /// is the key's `ambient` and nothing else, so the two are never
242        /// summed and the fill means what it meant before this field existed.
243        /// A caller who wants the pair to describe one physical environment
244        /// sets `ambient` to `π` times this.
245        ///
246        /// It reaches a surface through the reflection pass, so it needs
247        /// [`RenderEffects::REFLECTIONS`] in both the frame's effects and
248        /// [`ViewDesc::effects`]; a view drawn without it reflects nothing.
249        /// Zero is a view whose reflections find nothing but its own geometry.
250        environment: Vec3,
251    },
252}
253
254impl ViewLighting {
255    /// The effects a [`ViewLighting::Fixed`] view never draws, because each
256    /// brings the frame's light into it: the froxel volume is lit by the sun
257    /// and the scene's lights, and the contact march shadows along the frame's
258    /// sun.
259    ///
260    /// Reflections are not among them. The march's fallback is the probe table
261    /// and the sky rows, and a fixed view hands it its own — the zeroed row and
262    /// a sky of `environment` in every direction — so what it reflects is the
263    /// view's own geometry and the fixed environment.
264    pub const SCENE_EFFECTS: RenderEffects =
265        RenderEffects::VOLUMETRIC_FOG.union(RenderEffects::CONTACT_SHADOWS);
266
267    /// The effects this lighting takes out of a view's frame.
268    pub(super) const fn dropped_effects(self) -> RenderEffects {
269        match self {
270            Self::Scene => RenderEffects::empty(),
271            Self::Fixed { .. } => Self::SCENE_EFFECTS,
272        }
273    }
274}
275
276/// What a view's picture holds where no geometry covers a pixel — see
277/// [`ViewDesc::background`].
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
279pub enum ViewBackground {
280    /// The frame's own background: the sky where one is set, [`SCENE_CLEAR`]
281    /// where none is, and an alpha of one at every pixel. What the primary
282    /// camera draws, and what every view drew before this choice existed.
283    #[default]
284    Scene,
285    /// Nothing: the view clears to transparent black, draws no sky, and its
286    /// target's alpha is the frame's **coverage** — one where geometry was
287    /// drawn and zero where it was not.
288    ///
289    /// For a picture composited over something else, such as a model rendered
290    /// into an icon. The colour is **straight**, not premultiplied, which is
291    /// what [`SpriteRenderer`](crate::SpriteRenderer) blends: a covered pixel
292    /// holds the colour an opaque view would have drawn there, and a
293    /// transparent one holds whatever light the air in front of the far plane
294    /// scattered — zero on a frame without volumetric fog — which a
295    /// straight-alpha blend weighs by zero.
296    ///
297    /// # What keeps the alpha, and what cannot
298    ///
299    /// The forward pass, grass and water write coverage; the volumetric
300    /// composite, the reflection composite and the bloom composite carry the
301    /// alpha they read; the tonemap writes it into the target. **The two
302    /// antialiasing tiers cannot**: each blends a pixel's colour with its
303    /// neighbours' across exactly the edges the coverage has, so an edge
304    /// pixel would come out mixed with the transparent black beside it — a
305    /// premultiplied colour under a straight-alpha consumer, which is a dark
306    /// fringe. [`ForwardRenderer::create_view`] refuses a transparent view
307    /// whose [`ViewDesc::effects`] name either of them, and
308    /// [`ViewDesc::transparent`] is a description it accepts.
309    ///
310    /// [`render_scale`](ForwardRenderer::render_scale)'s upscale filters on
311    /// the same terms and so **does not apply**: a transparent view is drawn at
312    /// its target's own extent whatever the scale is.
313    ///
314    /// Bloom and auto-exposure keep the alpha and change the colour. Bloom's
315    /// glow past a silhouette lands on pixels the coverage says are empty and
316    /// is dropped with them; auto-exposure meters the background as black —
317    /// see [`ViewDesc::transparent`].
318    Transparent,
319}
320
321impl ViewBackground {
322    /// The effects a [`ViewBackground::Transparent`] view is refused with —
323    /// see that variant.
324    pub const REFUSED_ON_TRANSPARENT: RenderEffects =
325        RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2);
326
327    /// Whether this background leaves the target's alpha as coverage.
328    pub(super) const fn is_transparent(self) -> bool {
329        matches!(self, Self::Transparent)
330    }
331}
332
333/// What one call to [`ForwardRenderer::add_passes_with_views`] draws into.
334#[derive(Clone, Copy, Debug)]
335pub struct FrameTargets<'v> {
336    /// The primary camera's target, imported into the graph the call records
337    /// into.
338    pub target: ImageId,
339    /// That target's extent.
340    pub extent: (u32, u32),
341    /// The skinning plan whose dispatch the frame records, or `None` for a
342    /// frame that skins nothing — see
343    /// [`ForwardRenderer::add_skinned_passes`].
344    pub skinning: Option<&'v Skinning>,
345    /// Every secondary view the frame draws, each into its own target.
346    pub views: &'v [ViewTarget],
347}
348
349impl<'v> FrameTargets<'v> {
350    /// The primary camera alone, into `target`.
351    #[must_use]
352    pub const fn primary(
353        target: ImageId,
354        extent: (u32, u32),
355        skinning: Option<&'v Skinning>,
356    ) -> Self {
357        Self {
358            target,
359            extent,
360            skinning,
361            views: &[],
362        }
363    }
364}
365
366/// Where one secondary view's frame goes — see
367/// [`ForwardRenderer::add_passes_with_views`].
368#[derive(Clone, Copy, Debug, PartialEq, Eq)]
369pub struct ViewTarget {
370    /// The view to draw. Never [`ViewId::PRIMARY`], whose target is the one the
371    /// call itself takes.
372    pub view: ViewId,
373    /// The image the view's frame ends in, imported into the same graph.
374    pub target: ImageId,
375    /// That image's extent, which the view's internal frame is sized from
376    /// exactly as the primary's is sized from its own.
377    pub extent: (u32, u32),
378}
379
380/// Everything [`View::build`] reads out of the scene it draws.
381///
382/// Handles and borrowed tables, and nothing a view owns: each is created and
383/// destroyed by [`ForwardRenderer`], which outlives every view built against
384/// it.
385pub(super) struct ViewInputs<'a> {
386    /// Which view this is, whose bit its cull rejects instances on.
387    pub(super) id: ViewId,
388    /// The effects it may draw — see [`ViewDesc::effects`].
389    pub(super) effects: RenderEffects,
390    /// The effects its first frame is expected to draw, whose passes are built
391    /// now rather than on that frame — see [`View::build_passes`]. A guess,
392    /// and only a cost either way: one it misses is built by the frame that
393    /// asks for it, and one it names that no frame asks for is built for
394    /// nothing.
395    pub(super) expected: RenderEffects,
396    /// What it draws where no geometry is — see [`ViewDesc::background`].
397    pub(super) background: ViewBackground,
398    /// What lights it — see [`ViewDesc::lighting`].
399    pub(super) lighting: ViewLighting,
400    /// The format the caller's target has, which the resolves and the upscale
401    /// write.
402    pub(super) target_format: Format,
403    /// Whether its first frame is expected to be drawn below its target's
404    /// extent, which builds the upscale now on [`ViewInputs::expected`]'s
405    /// terms.
406    pub(super) expected_upscale: bool,
407    /// Which call the forward pass records.
408    pub(super) emit: EmitTail,
409    /// The instance ring, one buffer per frame in flight.
410    pub(super) instances: &'a [BufferHandle],
411    /// The mesh table's buffer.
412    pub(super) mesh_table: BufferHandle,
413    /// The renderer's one set of draw-generation pipelines, which this view's
414    /// generator dispatches and does not build — see [`DrawGenPipelines`].
415    pub(super) draw_pipelines: &'a Arc<DrawGenPipelines>,
416    /// The bucket and level tables every generator of the scene is built from
417    /// — see [`DrawGenDesc`].
418    pub(super) bucket_meshes: &'a [u32],
419    pub(super) bucket_modes: &'a [u32],
420    pub(super) bucket_clusters: &'a [u32],
421    pub(super) bucket_cluster_bases: &'a [u32],
422    pub(super) mesh_levels: &'a [level_select::MeshLevels],
423    pub(super) level_groups: &'a [level_select::LevelGroup],
424    pub(super) level_meshes: &'a [u32],
425    /// [`SceneDesc::capacities`]' instance and light counts.
426    pub(super) instance_capacity: u32,
427    pub(super) light_capacity: u32,
428    /// §3.5's clusters, on the mesh path only.
429    pub(super) clusters: Option<&'a ClusterPool>,
430    /// [`DrawGenDesc::task_lanes`] for this view's generator: the task chunk
431    /// where the mesh tail runs behind the amplification stage, zero
432    /// everywhere else.
433    pub(super) task_lanes: u32,
434    /// The mesh layout every group below is built against.
435    pub(super) mesh_layout: BindGroupLayoutHandle,
436    /// The scene's half of every group — see [`SharedBindings`]. The pages
437    /// and their sampler are per slot, because [`ForwardRenderer::adopt_pages`]
438    /// moves each slot to new ones on that slot's own frame.
439    pub(super) vertices: BufferHandle,
440    pub(super) draw_constants: BufferHandle,
441    pub(super) materials: BufferHandle,
442    pub(super) pages: &'a [PageBindings],
443    pub(super) probes: &'a [BufferHandle],
444    pub(super) specular_dfg: ImageViewHandle,
445    pub(super) ltc_table: ImageViewHandle,
446    /// The renderer's sky prefilter table, which the view's [`Ssr`] borrows —
447    /// see [`crate::ssr::Ssr::sky_prefilter_view`].
448    pub(super) sky_prefilter: ImageViewHandle,
449    /// The shadow atlas and the sampler that compares against it.
450    pub(super) shadow_map: ImageViewHandle,
451    pub(super) shadow_sampler: SamplerHandle,
452    /// The stand-ins a group names until the forward pass rebuilds it against
453    /// the frame's own images.
454    pub(super) ambient_occlusion: ImageViewHandle,
455    pub(super) contact_shadow: ImageViewHandle,
456    pub(super) probe_visibility: ImageViewHandle,
457}
458
459/// What the frame [`View::begin_frame`] opens already knows, handed to every
460/// view it begins.
461///
462/// Copies and borrows of the renderer's own fields, assembled once per view by
463/// [`ForwardRenderer`] so a view's blocks are written from exactly the numbers
464/// the primary camera's were.
465pub(super) struct ViewFrame<'a> {
466    /// The frame-in-flight slot every block is written into.
467    pub(super) slot: usize,
468    /// [`ForwardRenderer::frame_serial`] for the frame being opened.
469    pub(super) serial: u64,
470    /// The target's aspect, and the internal extent the frame is drawn at.
471    pub(super) aspect: f32,
472    pub(super) extent: (u32, u32),
473    /// The target's own extent: where it differs from
474    /// [`extent`](Self::extent) the frame ends in the upscale, on
475    /// [`View::add_passes`]' terms.
476    pub(super) target_extent: (u32, u32),
477    /// The frame's resolved effects, before this view's own mask.
478    pub(super) effects: RenderEffects,
479    /// Every element the instance pool has handed out — see
480    /// [`InstancePool::slot_count`].
481    pub(super) instance_count: u32,
482    /// The eye detail is selected from.
483    pub(super) selection_eye: Vec3,
484    pub(super) lod_error_budget: f32,
485    pub(super) lod_hold_ratio: f32,
486    /// The sun, the light rows and the shadow matrices the frame fitted.
487    pub(super) scene: &'a FrameScene,
488    /// Whether the frame draws any body of water, which builds the water
489    /// passes on the first frame that does — see [`View::build_content`].
490    pub(super) water: bool,
491    /// What the frame's grass field holds, for the generation block this view
492    /// writes — see [`crate::grass`].
493    pub(super) grass: Option<crate::grass::GrassFrame>,
494    /// The wind's block, as the renderer was last handed it.
495    pub(super) wind: crcbl_shaders::wind::WindParams,
496    pub(super) fog: Fog,
497    pub(super) probe_volume: crcbl_shaders::probe::ProbeVolume,
498    pub(super) attribute_base: u32,
499    /// The frame's sky, resolved once — see `ForwardRenderer::refresh_sky_view`.
500    pub(super) gradient: crcbl_shaders::sky::SkyGradient,
501    pub(super) sky_irradiance: crcbl_shaders::probe::GpuProbe,
502    pub(super) debug_view_lane: f32,
503    pub(super) exposure: f32,
504    pub(super) exposure_adaptation: Option<ExposureAdaptation>,
505    pub(super) tonemap_curve: tonemap::TonemapCurve,
506    /// The occlusion and small-feature culls this frame asks for — see
507    /// [`ForwardRenderer::occlusion_culling`], resolved against the frame.
508    pub(super) occlusion: OcclusionCulling,
509}
510
511/// Where [`View::add_passes`] ends a view's frame, and the two extents it is
512/// drawn between.
513#[derive(Clone, Copy, Debug)]
514pub(super) struct ViewOutput {
515    /// The image the frame ends in.
516    pub(super) target: ImageId,
517    /// That image's extent.
518    pub(super) target_extent: (u32, u32),
519    /// The internal extent the frame is drawn at — see
520    /// [`ForwardRenderer::frame_extents`].
521    pub(super) extent: (u32, u32),
522}
523
524/// What [`View::add_cull`] recorded, for [`View::add_passes`] to draw from.
525#[derive(Clone, Debug)]
526pub(super) struct ViewCull {
527    /// The cull and draw-argument pair's outputs.
528    pub(super) generated: GeneratedDraws,
529    /// The view's record of the cut, on the mesh path.
530    pub(super) selection: Option<BufferId>,
531    /// The froxel grid the clustering pass filled.
532    pub(super) light_grid: BufferId,
533    /// The farthest-depth pyramid a two-phase occlusion frame reads and
534    /// rewrites, or `None` for a frame that culls in one phase.
535    pub(super) pyramid: Option<ViewPyramid>,
536    /// Instances the cull tested, which the second phase tests again.
537    pub(super) instance_count: u32,
538}
539
540/// [`ViewCull::pyramid`]: the pyramid's levels as this frame's graph knows them,
541/// and the cull's group naming them.
542#[derive(Clone, Debug)]
543pub(super) struct ViewPyramid {
544    pub(super) levels: Vec<ImageId>,
545    pub(super) group: BindGroupHandle,
546}
547
548/// The tonemap's pipeline and what its group names besides the frame.
549#[derive(Clone, Copy, Debug)]
550pub(super) struct TonemapPipeline {
551    pub(super) sampler: SamplerHandle,
552    pub(super) layout: BindGroupLayoutHandle,
553    pub(super) pipeline_layout: PipelineLayoutHandle,
554    pub(super) pipeline: GraphicsPipelineHandle,
555}
556
557/// What the frame's scene passes left in the graph, and the scene's own
558/// handles, for every view's [`View::add_passes`] to read.
559pub(super) struct FramePasses {
560    /// The frame-in-flight slot.
561    pub(super) slot: usize,
562    pub(super) emit: EmitTail,
563    pub(super) target_format: Format,
564    /// How many occlusion blurs this frame runs — see
565    /// `ForwardRenderer::frame_ssao_blurs`.
566    pub(super) ssao_blurs: u32,
567    /// Whether the background pass draws.
568    pub(super) draws_sky: bool,
569    /// What the frame's water draws, or `None` for a frame with none — see
570    /// [`crate::water`].
571    pub(super) water: Option<WaterFrame>,
572    /// What the frame's grass field holds, or `None` for a frame with none —
573    /// see [`crate::grass`].
574    pub(super) grass: Option<crate::grass::GrassFrame>,
575    /// The skinning dispatch's vertex pool, when the frame skins.
576    pub(super) skinned: Option<BufferId>,
577    /// This frame's slot of the probe ring, as a handle and as the graph's id.
578    pub(super) probe_buffer: BufferHandle,
579    pub(super) probe_table: BufferId,
580    /// The two 1×1 stand-ins a group names when an effect is off.
581    pub(super) occlusion_placeholder: ImageId,
582    pub(super) contact_placeholder: ImageId,
583    /// The material pages, imported once for the frame.
584    pub(super) pages: MaterialPages,
585    /// The atlas the shadow pass drew, or its import where it was cached.
586    pub(super) shadow_atlas: ImageId,
587    /// The probe-visibility maps, or their placeholder.
588    pub(super) probe_visibility: ImageViewHandle,
589    pub(super) mesh_layout: BindGroupLayoutHandle,
590    /// The wireframe twin pair, where a caller switched the view on.
591    pub(super) wireframe: Option<SidedPipelines>,
592    /// The two passes' call lists, split by pipeline — see
593    /// `ForwardRenderer::depth_partitions` and `ForwardRenderer::sided_partitions`.
594    /// The same for every view: a bucket's offsets are a function of the bucket
595    /// alone.
596    pub(super) prepass_partitions: Vec<BucketDraws>,
597    pub(super) color_partitions: Vec<BucketDraws>,
598    pub(super) tonemap: TonemapPipeline,
599}
600
601/// What both depth prepasses declare and do not write, as the graph knows it —
602/// see [`declare_prepass_reads`].
603#[derive(Clone, Copy, Debug)]
604struct PrepassReads {
605    shadow_atlas: ImageId,
606    occlusion_placeholder: ImageId,
607    pages: MaterialPages,
608    probe_table: BufferId,
609    skinned: Option<BufferId>,
610    selection: Option<BufferId>,
611    prepass_stats: BufferId,
612}
613
614/// Declares everything a depth prepass binds — the early one and, with the
615/// occlusion cull on, the late one, which bind the same group and draw from the
616/// same generator.
617/// [`DrawGenDesc::task_lanes`] for a renderer whose mesh pipeline does or does
618/// not carry the amplification stage — see
619/// [`ForwardRenderer::culls_clusters`]. Every generator of one renderer takes
620/// the same answer, because every pass draws through the same pipeline kind.
621pub(super) fn task_lanes(culls_clusters: bool) -> u32 {
622    if culls_clusters {
623        crcbl_shaders::meshlet::TASK_LANES
624    } else {
625        0
626    }
627}
628
629fn declare_prepass_reads<'g, 'a>(
630    pass: PassBuilder<'g, 'a>,
631    reads: &PrepassReads,
632    generated: &GeneratedDraws,
633    emit: EmitTail,
634) -> PassBuilder<'g, 'a> {
635    let pass = pass
636        // Both are in this pass's bind group and neither is sampled by
637        // either depth-only pipeline — but a bound descriptor whose image is
638        // in the wrong layout is what
639        // `VUID-vkCmdDrawIndexedIndirectCount-imageLayout-00344` names, and
640        // the other backends read whatever the last writer left behind.
641        .read_image(reads.shadow_atlas)
642        .read_image(reads.occlusion_placeholder)
643        // And the page, which the **cutout** pipeline does sample: the alpha
644        // it cuts against is a texel of it. Declared on every frame rather
645        // than on the masked ones, because a declaration is also what lets
646        // the graph order a copy into a page layer against this pass — see
647        // `base_color_page_import`.
648        .read_image(reads.pages.base_color)
649        // And §2's other three pages, which are in the same groups for the
650        // same reason and are sampled here just as little.
651        .read_image(reads.pages.normal)
652        .read_image(reads.pages.mro)
653        .read_image(reads.pages.emissive)
654        // And the probe rows, which `mesh_layout` names in this group too
655        // and which the depth-only pipeline reads not at all — declared for
656        // the colour pass's reason exactly: they are device-local and
657        // writable-by-copy so a gather can fill them, and the graph orders a
658        // write against a pass only if that pass declared the read.
659        .read_buffer(reads.probe_table);
660    // `read_draw_sources` declares the *camera's* statistics buffer, because
661    // that is the one the arguments came out of; the prepass writes its own
662    // instead, so both are declared and the graph barriers both.
663    let pass = read_draw_sources(pass, generated, emit)
664        .use_buffer(reads.prepass_stats, ResourceState::ShaderReadWrite);
665    // The skinned vertices, on the shadow pass's terms. This pass writes the
666    // depth the occlusion pair samples and the forward pass tests against,
667    // so a prepass reading the region before the dispatch is visible lays
668    // down the previous pose's silhouette and the frame is rejected against
669    // it.
670    let pass = match reads.skinned {
671        Some(vertices) => pass.read_buffer(vertices),
672        None => pass,
673    };
674    // The camera's own cut, written here and again by the forward pass with
675    // the same camera and the same budget. Shared rather than a buffer of its
676    // own — unlike a cascade's, which a *later* pass would overwrite before
677    // anything could read it — because the second write is the one that stands
678    // and it writes the same words.
679    match reads.selection {
680        Some(selection) if emit.is_mesh() => {
681            pass.use_buffer(selection, ResourceState::ShaderReadWrite)
682        }
683        _ => pass,
684    }
685}
686
687/// Why [`View::add_passes`] may take a settings-driven pass as built: the
688/// [`View::begin_frame`] that froze [`View::frame_effects`] built every pass
689/// those effects record — see [`View::build_passes`].
690const BUILT_BY_BEGIN_FRAME: &str =
691    "`View::begin_frame` builds every pass the effects and extents it froze record";
692
693/// Why [`View::add_passes`] may take the water or grass passes as built: the
694/// [`View::begin_frame`] that opened this frame was handed the same bodies and
695/// field — see [`View::build_content`].
696const CONTENT_BUILT_BY_BEGIN_FRAME: &str =
697    "`View::begin_frame` builds the water and grass passes for the frame it froze";
698
699/// The primary camera's overlays — nothing for a secondary view.
700#[derive(Default)]
701pub(super) struct Overlays<'a> {
702    /// The debug draw layer, drawn into the HDR frame before the tonemap.
703    pub(super) debug_draw: Option<&'a DebugDraw>,
704    /// The ground grid, where a caller switched it on.
705    pub(super) ground_grid: Option<&'a GroundGrid>,
706    /// The shadow atlas viewer, on the frame the debug view shows it.
707    pub(super) atlas_viewer: Option<&'a mut AtlasView>,
708}
709
710/// One camera's resources and history — see the [module docs](self).
711#[derive(Debug)]
712pub(super) struct View {
713    /// The effects this view may draw, as [`ViewDesc::effects`] asked for them.
714    pub(super) effects: RenderEffects,
715    /// What this view draws where no geometry is, as
716    /// [`ViewDesc::background`] asked for it.
717    pub(super) background: ViewBackground,
718    /// What lights this view, as [`ViewDesc::lighting`] asked for it.
719    pub(super) lighting: ViewLighting,
720    /// The format the caller's target has, which the resolves and the upscale
721    /// are built against when [`View::build_passes`] first needs them.
722    pub(super) target_format: Format,
723    /// What this frame draws in this view: the frame's resolved effects under
724    /// [`View::effects`], frozen by [`View::begin_frame`] so that the frame's
725    /// two halves agree on it.
726    pub(super) frame_effects: RenderEffects,
727    /// Whether this frame puts the atmosphere's air in front of this view's
728    /// surfaces — an atmosphere under [`ViewLighting::Scene`] — frozen by
729    /// [`View::begin_frame`] beside [`View::frame_effects`] and for its
730    /// reason: the block that switch writes and the composite
731    /// [`View::add_passes`] adds for it have to agree.
732    pub(super) frame_aerial: bool,
733    /// The internal extent this frame is drawn at in this view, and its
734    /// target's, frozen by [`View::begin_frame`] beside
735    /// [`View::frame_effects`] and for its reason: that call wrote the blocks
736    /// for these extents and built the upscale where they differ, so the
737    /// frame's passes are recorded at them and a target of any other extent is
738    /// refused — see [`ForwardRenderer::add_passes`].
739    pub(super) frame_extent: (u32, u32),
740    pub(super) frame_target_extent: (u32, u32),
741    /// The extent of the image the reflection march writes this frame —
742    /// [`crate::ssr::march_extent`] of the frame's extent at
743    /// `crate::ssr::r_ssr_resolution` — frozen by [`View::begin_frame`] beside
744    /// [`View::frame_effects`] and for its reason: the block that tells
745    /// `ssr.slang` this extent and the image [`View::add_passes`] creates at it
746    /// have to agree, and the console can move the variable between the two.
747    pub(super) frame_ssr_extent: (u32, u32),
748    /// The frame serial [`View::begin_frame`] last ran for — see
749    /// [`ForwardRenderer::frame_serial`]. A secondary view records passes only
750    /// in the frame it was begun for.
751    pub(super) begun: u64,
752    /// The cull and draw-argument passes, and the indirect arguments they
753    /// produce.
754    pub(super) draws: DrawGen,
755    /// One buffer per frame in flight holding the cut the descent chose, or
756    /// empty where there is no amplification stage to choose one. See
757    /// [`ForwardRenderer::cluster_selection`].
758    pub(super) cluster_selection: Vec<BufferHandle>,
759    /// The one zeroed probe row a [`ViewLighting::Fixed`] view's groups, its
760    /// reflection march and its water surface bind in place of the scene's
761    /// table, or `None` for a view lit by the scene — see [`View::build`].
762    pub(super) fixed_probes: Option<BufferHandle>,
763    /// What [`begin_frame`](ForwardRenderer::begin_frame) last handed
764    /// [`DrawGen::begin_frame`], kept so a reader can compute the same cut
765    /// host-side without re-deriving it from the camera.
766    ///
767    /// Pixels per unit, the budget a group starts expanding over, and the budget
768    /// it is held down to — topic 25's hysteresis, and
769    /// [`LOD_HOLD_RATIO`] is what puts the third below the second.
770    pub(super) lod_params: [f32; 3],
771    /// Topic 18's light list and froxel grid, and the compute pass between them.
772    pub(super) lights: LightGrid,
773    /// This frame's froxel grid, as [`begin_frame`](ForwardRenderer::begin_frame)
774    /// decided it from the viewport and the camera.
775    ///
776    /// Held rather than recomputed at [`ForwardRenderer::add_passes`], because
777    /// the number of froxels the dispatch covers and the number the frame block
778    /// tells the fragment stage about have to be the same one.
779    pub(super) grid: Grid,
780    /// `[frame]`: the frame block, one per frame in flight — see the
781    /// [forward module docs](super) on why it is a ring.
782    pub(super) uniforms: Vec<BufferHandle>,
783    /// `[frame]`: the camera's group of the mesh layout, naming this view's
784    /// frame block and survivors.
785    pub(super) mesh_groups: Vec<BindGroupHandle>,
786    /// `[frame]`: `tonemap.slang`'s exposure block, written by
787    /// [`begin_frame`](ForwardRenderer::begin_frame).
788    ///
789    /// One per frame in flight for the frame uniforms' reason exactly — the
790    /// previous frame may still be reading last frame's while this one is
791    /// written.
792    pub(super) tonemap_uniforms: Vec<BufferHandle>,
793    /// `[frame]`: the tonemap group, cached against the scene target's view.
794    ///
795    /// Rebuilt only when that view changes, which is only on a resize. The graph
796    /// hands the view to the pass body; caching against it is what keeps a
797    /// steady-state frame free of descriptor writes.
798    ///
799    /// **One per frame in flight**, for [`crate::ssao`]'s reason: this group
800    /// names [`View::tonemap_uniforms`] as well as the scene transient, and that
801    /// is a ring — a single cache keyed on the view alone would hand the even
802    /// frames' block to the odd frames.
803    pub(super) tonemap_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
804    /// `[frame]`: the entries [`View::mesh_groups`] was built from.
805    ///
806    /// Kept because the occlusion image is a graph transient: its view is known
807    /// only at execute time, so the camera's group has to be rebuilt inside the
808    /// forward pass, and re-deriving twenty bindings there would mean carrying
809    /// half of `build`'s locals into the frame. Exactly two entries —
810    /// [`AMBIENT_OCCLUSION_BINDING`]'s and [`CONTACT_SHADOW_BINDING`]'s — differ
811    /// between the stored list and what the rebuild writes.
812    pub(super) mesh_group_entries: Vec<Vec<BindGroupEntry>>,
813    /// `[frame]`: the entries [`View::prepass_groups`] was built from.
814    ///
815    /// Kept for one rebuild only: the pages' and their sampler's, which
816    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
817    /// layout a slot holds. Handles, so the cost is a few words a group.
818    pub(super) prepass_group_entries: Vec<Vec<BindGroupEntry>>,
819    /// `[frame]`: the camera's group rebuilt against the two screen-space
820    /// channels the forward pass reads — the blurred occlusion and the contact
821    /// shadow — cached against both views together.
822    ///
823    /// [`View::tonemap_groups`]' shape, one per frame in flight because the
824    /// group it replaces is per frame in flight. Rebuilt only when a view
825    /// changes, which is only on a resize or a toggle.
826    ///
827    /// **One cache for both channels rather than one each**, because they are
828    /// two bindings of *one* group: rebuilding it twice a frame would be a
829    /// descriptor write per pass per frame, which is what
830    /// [`crate::ssao::cached_group`] exists to avoid. Its key is every view, so
831    /// either one moving is a miss.
832    ///
833    /// [`View::mesh_groups`] is the fallback and is *not* dead weight: it is
834    /// what the depth prepass binds, because that pass runs before there is any
835    /// occlusion to name.
836    pub(super) screen_channel_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
837    /// `[frame]`: the depth prepass's group — the camera's, with the occlusion
838    /// placeholder and **a culling-statistics buffer of its own**.
839    ///
840    /// The second half is the whole reason this is a group rather than
841    /// [`View::mesh_groups`] reused. On the mesh-shader path the prepass runs
842    /// the same amplification stage the forward pass does, and that stage counts
843    /// every surviving cluster into the buffer bound at CLUSTER_CULL_STATS_BINDING — so sharing
844    /// the camera's would make
845    /// [`CullStats::clusters`](crate::cull_stats::CullStats::clusters) report
846    /// every cluster of the frame twice, which is a plausible number and a wrong
847    /// one.
848    ///
849    /// **Nothing reads what this counts and nothing clears it.** It is a sink: a
850    /// wrapping `u32` whose value is never looked at, which is the honest price
851    /// of a prepass that shares a pipeline with the pass it precedes.
852    pub(super) prepass_groups: Vec<BindGroupHandle>,
853    /// `[frame]`: the sink [`View::prepass_groups`] counts into.
854    ///
855    /// Held so the prepass can declare it and the graph can barrier it. A ring
856    /// rather than one buffer for every other per-frame resource's reason: the
857    /// previous frame's submission may still be writing last frame's.
858    pub(super) prepass_stats: Vec<BufferHandle>,
859    /// This frame's camera view-projection, as
860    /// [`begin_frame`](ForwardRenderer::begin_frame) computed it.
861    ///
862    /// Kept because the ground grid's pass needs it and `add_passes` has no
863    /// camera: recomputing it there would be a second `aspect` to get wrong, and
864    /// a grid drawn through a camera the frame is not drawn with lands on the
865    /// wrong pixels while still looking like a grid.
866    pub(super) camera_view_proj: Mat4,
867    /// The view-projection the **previous** frame was drawn with, or [`None`]
868    /// before there was one.
869    ///
870    /// The camera-side twin of
871    /// [`GpuInstance::previous_transform`](crcbl_shaders::mesh::GpuInstance::previous_transform):
872    /// the pool says where each object was and this says where the viewer was,
873    /// and `mesh.slang`'s `motion_vector` is what turns the pair into a screen
874    /// offset. It reaches the shader as
875    /// [`FrameUniforms::previous_view_proj`](crcbl_shaders::mesh::FrameUniforms::previous_view_proj).
876    ///
877    /// **Advanced once per frame, in
878    /// [`begin_frame_body`](ForwardRenderer::begin_frame_body)** — which runs
879    /// exactly once per [`InstancePool::rotate`], so the camera's history and
880    /// the instances' settle on the same boundary. Advancing it anywhere a
881    /// frame can reach twice would report a camera that moved half as far as it
882    /// did, and a still scene would never come back to rest.
883    ///
884    /// [`None`] means the first frame, which is drawn with its own matrix in
885    /// both slots: a camera that has not moved yet has not moved, and an
886    /// identity or a zero here would put every pixel of the first frame in
887    /// motion.
888    pub(super) previous_view_projection: Option<Mat4>,
889    /// Topic 46's occlusion pair — see [`crate::ssao`]. Built with the view
890    /// where [`ViewInputs::expected`] holds [`RenderEffects::AMBIENT_OCCLUSION`]
891    /// — the default stack does — and otherwise by the first frame that draws
892    /// it; kept either way — see [`View::build_passes`].
893    pub(super) ssao: Option<Ssao>,
894    /// Topic 45's contact-shadow march — see
895    /// [`crate::contact_shadows`]. Built on [`View::ssao`]'s terms for
896    /// [`RenderEffects::CONTACT_SHADOWS`]: with the view where the expected
897    /// stack holds it — the default does not — and otherwise by the first
898    /// frame that draws it.
899    pub(super) contact_shadows: Option<ContactShadows>,
900    /// Topic 47's depth pyramid, which the reflection
901    /// march climbs — see [`crate::hiz`]. Built on [`View::ssao`]'s terms for
902    /// [`RenderEffects::REFLECTIONS`] — the default stack holds it — because
903    /// the march is its only reader, unlike [`View::ssr`]'s, which water
904    /// reads too.
905    pub(super) hiz: Option<Hiz>,
906    /// Topic 03 §3.3's farthest-depth pyramid,
907    /// which the occlusion cull reads — see [`crate::occlusion_cull`].
908    pub(super) occlusion_pyramid: OcclusionPyramid,
909    /// Topic 47's reflection march — see
910    /// [`crate::ssr`].
911    pub(super) ssr: Ssr,
912    /// The froxel volume and its composite — see
913    /// [`crate::volumetric`].
914    pub(super) volumetric: Volumetric,
915    /// Topic 43 §6's auto-exposure — see
916    /// [`crate::exposure`]. Named for what it owns rather than for the value:
917    /// [`ForwardRenderer::exposure`] is the number a caller set.
918    pub(super) auto_exposure: Exposure,
919    /// Topic 48's bloom chain — see [`crate::bloom`]. Built on
920    /// [`View::ssao`]'s terms for [`RenderEffects::BLOOM`], which the default
921    /// stack leaves out.
922    pub(super) bloom: Option<Bloom>,
923    /// The cheap antialiasing tier — see
924    /// [`crate::fxaa`]. Built on [`View::ssao`]'s terms for the frames that
925    /// resolve through it — [`RenderEffects::ANTIALIASING`] without
926    /// [`RenderEffects::CMAA2`], which the default stack is not.
927    pub(super) fxaa: Option<Fxaa>,
928    /// The higher antialiasing tier — see
929    /// [`crate::cmaa2`]. It takes the resolve slot from [`View::fxaa`] on the
930    /// frames [`RenderEffects::CMAA2`] is set for, so at most one of the two
931    /// records; each is built on [`View::ssao`]'s terms for the frames that
932    /// record it — this one with the view under the default stack, which
933    /// carries [`RenderEffects::CMAA2`].
934    pub(super) cmaa2: Option<Cmaa2>,
935    /// [`crate::upscale`]. Built with the view where
936    /// [`ViewInputs::expected_upscale`] says its first frame is drawn below
937    /// its target, and otherwise by the first frame that is — none at a
938    /// [`render_scale`](ForwardRenderer::render_scale) of `1.0`.
939    pub(super) upscale: Option<Upscale>,
940    /// Topic 43 §8's background pass — see
941    /// [`crate::sky_pass`]. It draws on no frame whose sky is [`Sky::NONE`],
942    /// which is every frame until a caller calls
943    /// [`set_sky`](ForwardRenderer::set_sky).
944    pub(super) sky_pass: SkyPass,
945    /// `docs/plan/55-water.md`'s surface passes — see [`crate::water`]. They
946    /// draw on no frame with no bodies, which is every frame until a caller
947    /// calls [`set_water`](ForwardRenderer::set_water), so they are built by
948    /// the first frame that has a body and kept from then on — see
949    /// [`View::build_content`].
950    pub(super) water: Option<Water>,
951    /// `docs/plan/57-grass.md`'s three passes — see [`crate::grass`]. They run
952    /// on no frame with no field, which is every frame until a caller calls
953    /// [`set_grass`](ForwardRenderer::set_grass), and are built on
954    /// [`View::water`]'s terms.
955    pub(super) grass: Option<crate::grass::Grass>,
956    /// The atlas's comparison sampler, which the renderer owns for its life
957    /// and [`View::build_content`] hands the water and grass passes.
958    pub(super) shadow_sampler: SamplerHandle,
959}
960
961/// The layouts and pipelines a view's froxel volume and reflection march are
962/// built against, compiled before [`View::build`] and handed to it.
963///
964/// **Apart from the passes** so the camera's can be compiled in the renderer's
965/// mesh-pass batch, beside the compiles they would otherwise follow — see
966/// `ForwardRenderer::build`. A view made later builds its own with
967/// [`ViewPipelines::new`]. Both list their members out of
968/// [`ViewPipelineLayouts`].
969pub(super) struct ViewPipelines {
970    pub(super) volumetric: VolumetricPipelines,
971    pub(super) ssr: SsrPipelines,
972}
973
974impl ViewPipelines {
975    /// Both sets, out of a [`pipeline_batch`] of their own, for a view built
976    /// after the renderer: there is no build's batch left for it to join. The
977    /// members are [`ViewPipelineLayouts`]', in the order the build lists
978    /// them.
979    ///
980    /// `service` runs before each round of the batch, or before each pipeline
981    /// where the batch is serial — see `crate::pipeline_batch`.
982    ///
983    /// # Errors
984    ///
985    /// [`HalError`] from any seam call, having released whatever it created.
986    pub(super) fn new(device: &dyn Device, service: &mut dyn FnMut()) -> Result<Self, HalError> {
987        let mut pending = Partial::new(device);
988        let layouts = ViewPipelineLayouts::new(device, &mut pending)?;
989        let leading = layouts.leading(device);
990        let trailing = layouts.trailing(device);
991        let jobs: Vec<&pipeline_batch::Job<'_, _>> = leading
992            .iter()
993            .map(|job| job as &pipeline_batch::Job<'_, _>)
994            .chain(
995                trailing
996                    .iter()
997                    .map(|job| job as &pipeline_batch::Job<'_, _>),
998            )
999            .collect();
1000        let mut made = pipeline_batch::create_listed(device, service, &jobs).into_iter();
1001        let mut next = || {
1002            made.next()
1003                .unwrap_or_else(|| unreachable!("one result per job"))
1004        };
1005        let leading = leading.each_ref().map(|_| next());
1006        let trailing = trailing.each_ref().map(|_| next());
1007        layouts.finish(pending, leading, trailing)
1008    }
1009}
1010
1011/// One member of [`ViewPipelineLayouts`]' share of a batch.
1012type ViewMember = fn(ViewPipelineLayouts, &dyn Device) -> Result<Pipeline, HalError>;
1013
1014/// [`ViewPipelines`]' layouts, created ahead of the pipelines so each pipeline
1015/// can be one member of a [`pipeline_batch`]: the renderer's mesh batch for the
1016/// camera's sets, a batch of their own for a view made later.
1017///
1018/// **The one list of the sets' members and of how they are read back** —
1019/// [`leading`](Self::leading), [`trailing`](Self::trailing) and
1020/// [`finish`](Self::finish) — so the two batches cannot drift apart from each
1021/// other. Within it, `finish` names the results in [`Self::LEADING`]'s and
1022/// [`Self::TRAILING`]'s order, so a member moved in a list moves in `finish`'s
1023/// patterns too: a compute and a graphics member swapped panics there, but two
1024/// graphics members swapped would hand each set the other's pipeline.
1025///
1026/// Handles only, and `Copy` so each job can take them: nothing here owns them
1027/// until [`finish`](Self::finish) hands them to the sets.
1028#[derive(Clone, Copy, Debug)]
1029pub(super) struct ViewPipelineLayouts {
1030    volumetric: VolumetricLayouts,
1031    ssr: SsrLayouts,
1032}
1033
1034impl ViewPipelineLayouts {
1035    /// Each set's costly compile — the volume's scatter pass and the march —
1036    /// which a batch lists first, so both are in its first round whatever a
1037    /// round's size.
1038    const LEADING: [ViewMember; 2] = [
1039        |layouts, device| layouts.volumetric.scatter(device).map(Pipeline::Compute),
1040        |layouts, device| {
1041            layouts
1042                .ssr
1043                .march(device, ForwardRenderer::build_fullscreen)
1044                .map(Pipeline::Graphics)
1045        },
1046    ];
1047
1048    /// The sets' other members, never timed alone and taken to be cheap, which
1049    /// a batch lists after everything else in it.
1050    const TRAILING: [ViewMember; 3] = [
1051        |layouts, device| layouts.volumetric.integrate(device).map(Pipeline::Compute),
1052        |layouts, device| {
1053            layouts
1054                .volumetric
1055                .composite(device, ForwardRenderer::build_fullscreen)
1056                .map(Pipeline::Graphics)
1057        },
1058        |layouts, device| {
1059            layouts
1060                .ssr
1061                .blur(device, ForwardRenderer::build_fullscreen)
1062                .map(Pipeline::Graphics)
1063        },
1064    ];
1065
1066    /// Creates the volume's layouts and the march's, each held in `pending` —
1067    /// so the caller's guard releases them if anything after fails.
1068    ///
1069    /// # Errors
1070    ///
1071    /// [`HalError`] from any layout.
1072    pub(super) fn new(device: &dyn Device, pending: &mut Partial<'_>) -> Result<Self, HalError> {
1073        Ok(Self {
1074            volumetric: VolumetricLayouts::new(device, pending)?,
1075            ssr: SsrLayouts::new(device, pending)?,
1076        })
1077    }
1078
1079    /// The jobs a batch lists first — see [`Self::LEADING`].
1080    pub(super) fn leading<'a>(
1081        self,
1082        device: &'a dyn Device,
1083    ) -> [impl Fn() -> Result<Pipeline, HalError> + 'a; Self::LEADING.len()] {
1084        Self::LEADING.map(|member| move || member(self, device))
1085    }
1086
1087    /// The jobs a batch lists last — see [`Self::TRAILING`].
1088    pub(super) fn trailing<'a>(
1089        self,
1090        device: &'a dyn Device,
1091    ) -> [impl Fn() -> Result<Pipeline, HalError> + 'a; Self::TRAILING.len()] {
1092        Self::TRAILING.map(|member| move || member(self, device))
1093    }
1094
1095    /// Both sets, out of these layouts and the batch's results for
1096    /// [`leading`](Self::leading) and [`trailing`](Self::trailing), each in its
1097    /// jobs' order.
1098    ///
1099    /// **All or nothing**: every success is held in `pending`, which holds the
1100    /// layouts already, before any error propagates — the batch ran each member
1101    /// whatever the others returned, and dropping an unvisited result does not
1102    /// release its handle. On an error `pending` releases everything it holds;
1103    /// on success the sets own it all and `pending` lets go.
1104    ///
1105    /// # Errors
1106    ///
1107    /// The first failed member's [`HalError`].
1108    pub(super) fn finish(
1109        self,
1110        mut pending: Partial<'_>,
1111        [scatter, march]: [Result<Pipeline, HalError>; Self::LEADING.len()],
1112        [integrate, composite, blur]: [Result<Pipeline, HalError>; Self::TRAILING.len()],
1113    ) -> Result<ViewPipelines, HalError> {
1114        for pipeline in [&scatter, &march, &integrate, &composite, &blur]
1115            .into_iter()
1116            .flatten()
1117        {
1118            pending.add(*pipeline);
1119        }
1120        let volumetric = self.volumetric.finish(
1121            scatter?.compute(),
1122            integrate?.compute(),
1123            composite?.graphics(),
1124        );
1125        let ssr = self.ssr.finish(march?.graphics(), blur?.graphics());
1126        pending.keep();
1127        Ok(ViewPipelines { volumetric, ssr })
1128    }
1129}
1130
1131/// The water and grass passes one [`View::build_content`] call builds — each
1132/// [`None`] where the call was not asked for it.
1133///
1134/// **Their pipelines are one [`pipeline_batch`]**, compiled side by side where
1135/// the device allows it: on a cold driver cache each is a shader compilation,
1136/// none needs another, and a frame that first has both a body and a field
1137/// would otherwise pay the water passes' compiles and then the grass passes'.
1138/// A backend that cannot take pipelines from several threads creates them one
1139/// after another, as `crate::pipeline_batch` decides.
1140pub(super) struct ContentPasses {
1141    pub(super) water: Option<Water>,
1142    pub(super) grass: Option<Grass>,
1143}
1144
1145impl ContentPasses {
1146    /// Builds the water passes where `water` and the grass passes where
1147    /// `grass`, for `frames` frames in flight, lit through `shadow_sampler`.
1148    ///
1149    /// **All or nothing**: a failure part-way releases everything this call
1150    /// created — the batch's other members included, since every member runs
1151    /// whatever the others return — so the caller has nothing to clean up.
1152    ///
1153    /// `service` runs before each round of the batch, or before each pipeline
1154    /// where the batch is serial — see `crate::pipeline_batch`.
1155    ///
1156    /// # Errors
1157    ///
1158    /// [`HalError`] from any seam call.
1159    pub(super) fn new(
1160        device: &dyn Device,
1161        frames: usize,
1162        shadow_sampler: SamplerHandle,
1163        water: bool,
1164        grass: bool,
1165        service: &mut dyn FnMut(),
1166    ) -> Result<Self, HalError> {
1167        let (water, grass) = Self::pipelines(device, water, grass, service)?;
1168        // Each pass releases its own set on its failure; the grass set, which
1169        // nothing owns yet while the water passes are built, is released here.
1170        let water = match water.map(|set| Water::new(device, set, frames, shadow_sampler)) {
1171            None => None,
1172            Some(Ok(pass)) => Some(pass),
1173            Some(Err(error)) => {
1174                if let Some(set) = grass {
1175                    set.destroy(device);
1176                }
1177                return Err(error);
1178            }
1179        };
1180        let grass = match grass.map(|set| Grass::new(device, set, frames, shadow_sampler)) {
1181            None => None,
1182            Some(Ok(pass)) => Some(pass),
1183            Some(Err(error)) => {
1184                if let Some(pass) = water {
1185                    pass.destroy(device);
1186                }
1187                return Err(error);
1188            }
1189        };
1190        Ok(Self { water, grass })
1191    }
1192
1193    /// The water and grass passes' pipeline sets, out of one batch.
1194    ///
1195    /// **The water surface and every grass draw lead**, so each is in the
1196    /// earliest round its place allows whatever a round's size: the surface was
1197    /// the water passes' costly compile when they were timed apart, and each
1198    /// grass draw is a compile on the order of the forward pass's. The water
1199    /// copy and the grass dispatches, never timed alone and taken to be cheap,
1200    /// trail them.
1201    fn pipelines(
1202        device: &dyn Device,
1203        water: bool,
1204        grass: bool,
1205        service: &mut dyn FnMut(),
1206    ) -> Result<(Option<WaterPipelines>, Option<GrassPipelines>), HalError> {
1207        // Every layout and, once the batch is back, every pipeline it made, held
1208        // until both sets are whole.
1209        let mut pending = Partial::new(device);
1210        let water = if water {
1211            Some(WaterLayouts::new(device, &mut pending)?)
1212        } else {
1213            None
1214        };
1215        let grass = if grass {
1216            Some(GrassLayouts::new(device, &mut pending)?)
1217        } else {
1218            None
1219        };
1220        let surface = water.map(|layouts| move || layouts.surface(device).map(Pipeline::Graphics));
1221        let draws = grass.map(|layouts| {
1222            GrassLayouts::DRAWS
1223                .map(|draw| move || layouts.draw(device, draw).map(Pipeline::Graphics))
1224        });
1225        let copy = water.map(|layouts| {
1226            move || {
1227                layouts
1228                    .copy(device, ForwardRenderer::build_fullscreen_with)
1229                    .map(Pipeline::Graphics)
1230            }
1231        });
1232        let clear = grass.map(|layouts| move || layouts.clear(device).map(Pipeline::Compute));
1233        let generate = grass.map(|layouts| move || layouts.generate(device).map(Pipeline::Compute));
1234        // In the order the results are read back out of below.
1235        let mut jobs: Vec<&pipeline_batch::Job<'_, _>> = Vec::new();
1236        if let Some(job) = &surface {
1237            jobs.push(job);
1238        }
1239        for job in draws.iter().flatten() {
1240            jobs.push(job);
1241        }
1242        if let Some(job) = &copy {
1243            jobs.push(job);
1244        }
1245        if let Some(job) = &clear {
1246            jobs.push(job);
1247        }
1248        if let Some(job) = &generate {
1249            jobs.push(job);
1250        }
1251        let made = pipeline_batch::create_listed(device, service, &jobs);
1252        // Every success is held before any error propagates: the batch ran each
1253        // member whatever the others returned, and dropping an unvisited result
1254        // does not release its handle.
1255        for pipeline in made.iter().flatten() {
1256            pending.add(*pipeline);
1257        }
1258        let mut made = made.into_iter();
1259        let mut next = || {
1260            made.next()
1261                .unwrap_or_else(|| unreachable!("one result per job"))
1262        };
1263        let surface = water.map(|_| next());
1264        let draws = grass.map(|_| GrassLayouts::DRAWS.map(|_| next()));
1265        let copy = water.map(|_| next());
1266        let clear = grass.map(|_| next());
1267        let generate = grass.map(|_| next());
1268        let water = match (water, surface, copy) {
1269            (Some(layouts), Some(surface), Some(copy)) => {
1270                Some(layouts.finish(copy?.graphics(), surface?.graphics()))
1271            }
1272            _ => None,
1273        };
1274        let grass = match (grass, draws, clear, generate) {
1275            (Some(layouts), Some(draws), Some(clear), Some(generate)) => {
1276                let [raster, shell, fin, blade_near, blade_far] = draws;
1277                Some(layouts.finish(
1278                    clear?.compute(),
1279                    generate?.compute(),
1280                    [
1281                        raster?.graphics(),
1282                        shell?.graphics(),
1283                        fin?.graphics(),
1284                        blade_near?.graphics(),
1285                        blade_far?.graphics(),
1286                    ],
1287                ))
1288            }
1289            _ => None,
1290        };
1291        pending.keep();
1292        Ok((water, grass))
1293    }
1294}
1295
1296impl View {
1297    /// Creates one camera's resources against the scene `inputs` describes.
1298    ///
1299    /// **All or nothing**: a failure part-way releases what this call had
1300    /// created, so the caller has nothing of the view to clean up, and a success
1301    /// hands every handle to the returned [`View`] — none of them is left in a
1302    /// rollback the caller might run later.
1303    ///
1304    /// Its start-up uploads and fills are recorded into `uploads` rather than
1305    /// submitted one by one, so **the view draws nothing until the caller has
1306    /// submitted that batch** — with
1307    /// [`UploadBatch::submit_deferred`], to the queue its frames go to; a failure
1308    /// [abandons](UploadBatch::abandon) the batch, because the rollback has
1309    /// destroyed what it recorded into.
1310    ///
1311    /// `pipelines` are the froxel volume's and the reflection march's, which
1312    /// the view owns from here — released with the rest on a failure.
1313    ///
1314    /// `service` is called after each subsystem is built — see
1315    /// [`ForwardRenderer::with_scene_serviced`], which is where the reason and
1316    /// the measurement are.
1317    ///
1318    /// # Errors
1319    ///
1320    /// [`HalError`] if any buffer, group or pipeline could not be created.
1321    pub(super) fn build(
1322        device: &dyn Device,
1323        uploads: &mut UploadBatch<'_>,
1324        inputs: &ViewInputs<'_>,
1325        pipelines: ViewPipelines,
1326        service: &mut dyn FnMut(),
1327    ) -> Result<Self, HalError> {
1328        let mut rollback = Rollback {
1329            volumetric_pipelines: Some(pipelines.volumetric),
1330            ssr_pipelines: Some(pipelines.ssr),
1331            ..Rollback::default()
1332        };
1333        let built = Self::build_into(device, uploads, inputs, &mut rollback, service);
1334        if built.is_err() {
1335            uploads.abandon();
1336            rollback.run(device);
1337        }
1338        built
1339    }
1340
1341    /// [`View::build`]'s body, with every handle it creates placed in
1342    /// `rollback` until the view is whole.
1343    fn build_into(
1344        device: &dyn Device,
1345        uploads: &mut UploadBatch<'_>,
1346        inputs: &ViewInputs<'_>,
1347        rollback: &mut Rollback,
1348        service: &mut dyn FnMut(),
1349    ) -> Result<Self, HalError> {
1350        let frames = inputs.instances.len();
1351        let draws = DrawGen::new(
1352            device,
1353            uploads,
1354            inputs.draw_pipelines,
1355            &DrawGenDesc {
1356                label: Some("forward"),
1357                instances: inputs.instances,
1358                mesh_table: inputs.mesh_table,
1359                bucket_meshes: inputs.bucket_meshes,
1360                bucket_modes: inputs.bucket_modes,
1361                bucket_clusters: inputs.bucket_clusters,
1362                bucket_cluster_bases: inputs.bucket_cluster_bases,
1363                mesh_levels: inputs.mesh_levels,
1364                level_groups: inputs.level_groups,
1365                level_meshes: inputs.level_meshes,
1366                instance_capacity: inputs.instance_capacity,
1367                hidden_view: inputs.id.hidden_bit(),
1368                // Every camera can cull by occlusion: the regions it adds are a
1369                // few words a bucket, and the switch is per frame.
1370                mode: crcbl_shaders::draw_gen::DrawMode::Occlusion,
1371                task_lanes: inputs.task_lanes,
1372            },
1373        )?;
1374        let runs: Vec<BufferHandle> = (0..frames).map(|frame| draws.runs(frame)).collect();
1375        let args: Vec<BufferHandle> = (0..frames).map(|frame| draws.args(frame)).collect();
1376        // What the amplification stage reads and writes, and nothing else does:
1377        // this frame's frustum, and the culling statistics its surviving
1378        // clusters are counted into.
1379        let cull_params: Vec<BufferHandle> =
1380            (0..frames).map(|frame| draws.cull_params(frame)).collect();
1381        let cull_stats: Vec<BufferHandle> = (0..frames)
1382            .map(|frame| draws.visible_count(frame))
1383            .collect();
1384        rollback.draws = Some(draws);
1385        service();
1386
1387        // Topic 25's observable: one word per resident cluster,
1388        // holding the cut the descent chose. Empty where there is no
1389        // amplification stage, which is the same condition CLUSTER_SELECTION_BINDING exists
1390        // under — and the two cannot disagree, because this vector is what
1391        // decides whether the entry is written.
1392        //
1393        // **One buffer per frame in flight**, on `cull_stats`' terms exactly: a
1394        // frame still in flight is a frame still writing, and one buffer shared
1395        // across the ring would have the next frame's dispatch overwriting what
1396        // this one recorded. `TRANSFER_SRC` because reading it is the point.
1397        //
1398        // Allocated on the whole mesh path rather than only where there is an
1399        // amplification stage to write them, because the layout declares
1400        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued. On
1401        // a device with no task stage nothing writes them and
1402        // `ForwardRenderer::cluster_selection` still answers `None`, so the
1403        // cost is the allocation and nothing else.
1404        let mut cluster_selection: Vec<BufferHandle> = Vec::new();
1405        if inputs.emit.is_mesh() {
1406            let count = inputs
1407                .clusters
1408                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
1409                .count();
1410            for frame in 0..frames {
1411                let buffer = device.create_buffer(&BufferDesc {
1412                    label: Some(&format!("cluster selection {frame}")),
1413                    size: u64::from(count) * 4,
1414                    usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
1415                    memory: MemoryLocation::DeviceLocal,
1416                })?;
1417                rollback.buffers.push(buffer);
1418                cluster_selection.push(buffer);
1419            }
1420        }
1421
1422        // Topic 18's light list and the froxel grid its compute pass fills.
1423        //
1424        // Built after the cull because it needs the culling-statistics ring:
1425        // its overflow counter is a word of that buffer, which is what keeps
1426        // topic 03 §3.6's readback at one.
1427        rollback.lights = Some(LightGrid::new(
1428            device,
1429            &LightGridDesc {
1430                label: Some("lights"),
1431                frames,
1432                lights: inputs.light_capacity,
1433                froxels: FROXEL_CAPACITY,
1434                stats: &cull_stats,
1435            },
1436        )?);
1437        service();
1438        let lights = rollback.lights.as_ref().expect("just stored");
1439        let draws = rollback.draws.as_ref().expect("stored above");
1440
1441        // **A fixed view's probe table is one zeroed row**, bound in place of
1442        // the scene's. Its frame block carries the empty probe header, and
1443        // `mesh.slang` evaluates that header as row 0 of whatever table is
1444        // bound — which is zero for a scene with no probes only because that
1445        // scene's table is. Host-uploaded and read-only, on the light list's
1446        // terms, and written once: nothing ever changes a zero.
1447        //
1448        // **Zero even when the view has an environment**, which reaches the
1449        // reflection march as its sky rows instead. A probe row is weighed by
1450        // the frame's per-probe visibility map before it is divided back out,
1451        // and `(a * w) / w` is not always `a` in floating point — so a lit row
1452        // here could come back rounded differently from one level to the next.
1453        // A zero comes back zero whatever it is weighed by.
1454        let fixed_probes = match inputs.lighting {
1455            ViewLighting::Scene => None,
1456            ViewLighting::Fixed { .. } => {
1457                let buffer = device.create_buffer(&BufferDesc {
1458                    label: Some("fixed view probes"),
1459                    size: crcbl_shaders::probe::PROBE_STRIDE as u64,
1460                    usage: BufferUsage::STORAGE,
1461                    memory: MemoryLocation::HostUpload,
1462                })?;
1463                rollback.buffers.push(buffer);
1464                device.write_buffer(buffer, 0, &crcbl_shaders::probe::GpuProbe::ZERO.to_bytes())?;
1465                Some(buffer)
1466            }
1467        };
1468
1469        let mut uniforms = Vec::with_capacity(frames);
1470        let mut mesh_groups = Vec::with_capacity(frames);
1471        let mut mesh_group_entries = Vec::with_capacity(frames);
1472        let mut prepass_groups = Vec::with_capacity(frames);
1473        let mut prepass_stats = Vec::with_capacity(frames);
1474        let mut prepass_group_entries = Vec::with_capacity(frames);
1475        for (frame, &slot_instances) in inputs.instances.iter().enumerate() {
1476            // Everything a group of this layout names that is the same in all of
1477            // this frame's. The per-group half is what `MeshGroup` below varies,
1478            // and the two exist so the colour pass's group and the shadow pass's
1479            // are one description rather than two that agree today.
1480            let shared = SharedBindings {
1481                vertices: inputs.vertices,
1482                draw_constants: inputs.draw_constants,
1483                mesh_table: inputs.mesh_table,
1484                materials: inputs.materials,
1485                pages: inputs.pages[frame],
1486                clusters: inputs.clusters,
1487                shadow_sampler: inputs.shadow_sampler,
1488                lights: lights.lights(frame),
1489                light_grid: lights.grid(frame),
1490                probes: fixed_probes.unwrap_or(inputs.probes[frame]),
1491                tables: draws.tables(),
1492                specular_dfg: inputs.specular_dfg,
1493                ltc_table: inputs.ltc_table,
1494            };
1495            let buffer = device.create_buffer(&BufferDesc {
1496                label: Some("mesh frame uniforms"),
1497                size: mesh::FRAME_UNIFORMS_SIZE as u64,
1498                usage: BufferUsage::UNIFORM,
1499                memory: MemoryLocation::HostUpload,
1500            })?;
1501            rollback.buffers.push(buffer);
1502            let entries = MeshGroup {
1503                uniforms: buffer,
1504                instances: slot_instances,
1505                runs: runs[frame],
1506                args: args[frame],
1507                cull_params: cull_params[frame],
1508                cull_stats: cull_stats[frame],
1509                cluster_selection: cluster_selection.get(frame).copied(),
1510                group_state: inputs.emit.is_mesh().then(|| draws.group_state()),
1511                // The colour pass reads the finished atlas. Its own pass writes
1512                // nothing to it, so there is no conflict to avoid here.
1513                shadow_map: inputs.shadow_map,
1514                // The placeholder even for the camera's group: the occlusion
1515                // image is a graph transient and its view does not exist until
1516                // execute time. `add_passes` rebuilds this group against the real
1517                // one and caches it, and *this* group is what the depth prepass
1518                // binds — which runs before there is any occlusion to name.
1519                ambient_occlusion: inputs.ambient_occlusion,
1520                // The same, one binding along, and for the same reason.
1521                contact_shadow: inputs.contact_shadow,
1522                probe_visibility: inputs.probe_visibility,
1523            }
1524            .entries(&shared);
1525            let group = device.create_bind_group(&BindGroupDesc {
1526                label: Some("mesh frame"),
1527                layout: inputs.mesh_layout,
1528                entries: &entries,
1529                variable_count: None,
1530            })?;
1531            rollback.bind_groups.push(group);
1532            uniforms.push(buffer);
1533            mesh_groups.push(group);
1534            // Kept so the forward pass can rebuild this group against the
1535            // occlusion image the graph realised, without re-deriving twenty
1536            // bindings out of fields that no longer exist by then. Only the
1537            // screen-space channels and the probe visibility maps differ — see
1538            // [`View::screen_channel_groups`].
1539            mesh_group_entries.push(entries);
1540
1541            // The depth prepass's group: this one again, counting its clusters
1542            // somewhere the camera's counter cannot see. See
1543            // [`View::prepass_groups`] for why that matters, and note that only
1544            // the amplification stage writes this binding, although both mesh
1545            // layouts retain it to preserve native argument indices.
1546            //
1547            // `DeviceLocal`, because a shader writes it: D3D12 has no unordered
1548            // access view of a host-visible resource, and `create_bind_group`
1549            // enforces it.
1550            let stats = device.create_buffer(&BufferDesc {
1551                label: Some("depth prepass cluster survivors"),
1552                size: u64::from(crcbl_shaders::cull::STATS_WORDS) * 4,
1553                usage: BufferUsage::STORAGE,
1554                memory: MemoryLocation::DeviceLocal,
1555            })?;
1556            rollback.buffers.push(stats);
1557            let entries = MeshGroup {
1558                uniforms: buffer,
1559                instances: slot_instances,
1560                runs: runs[frame],
1561                args: args[frame],
1562                cull_params: cull_params[frame],
1563                cull_stats: stats,
1564                cluster_selection: cluster_selection.get(frame).copied(),
1565                group_state: inputs.emit.is_mesh().then(|| draws.group_state()),
1566                shadow_map: inputs.shadow_map,
1567                ambient_occlusion: inputs.ambient_occlusion,
1568                contact_shadow: inputs.contact_shadow,
1569                probe_visibility: inputs.probe_visibility,
1570            }
1571            .entries(&shared);
1572            let group = device.create_bind_group(&BindGroupDesc {
1573                label: Some("depth prepass"),
1574                layout: inputs.mesh_layout,
1575                entries: &entries,
1576                variable_count: None,
1577            })?;
1578            rollback.bind_groups.push(group);
1579            prepass_groups.push(group);
1580            prepass_stats.push(stats);
1581            // For the page sampler's rebuild — see [`View::prepass_group_entries`].
1582            prepass_group_entries.push(entries);
1583        }
1584
1585        // The exposure block, one per frame in flight for the frame uniforms'
1586        // reason exactly — the previous frame may still be reading last frame's
1587        // while this one is written. See the forward module docs on the ring.
1588        let mut tonemap_uniforms = Vec::with_capacity(frames);
1589        for _ in 0..frames {
1590            let buffer = device.create_buffer(&BufferDesc {
1591                label: Some("tonemap params"),
1592                size: tonemap::PARAMS_SIZE as u64,
1593                usage: BufferUsage::UNIFORM,
1594                memory: MemoryLocation::HostUpload,
1595            })?;
1596            rollback.buffers.push(buffer);
1597            tonemap_uniforms.push(buffer);
1598        }
1599
1600        // --- the screen-space reflection march ---
1601        //
1602        // Stored in the rollback whole, like the light grid: it owns a
1603        // pipeline and a ring of buffers, and `Ssr::destroy` is the one place
1604        // their release order lives.
1605        //
1606        // **Built here whatever the effects say**, unlike the occlusion pair:
1607        // the water surface binds this pass's block on every frame it draws —
1608        // see [`crate::water`]. Its pipelines were
1609        // compiled before this — see [`ViewPipelines`].
1610        //
1611        // The Hi-Z pyramid the march climbs is not: nothing else reads it, so
1612        // it is built with the passes the effects ask for — see
1613        // [`View::build_passes`].
1614        rollback.ssr = Some(Ssr::new(
1615            device,
1616            rollback
1617                .ssr_pipelines
1618                .take()
1619                .unwrap_or_else(|| unreachable!("`View::build` placed the march's set above")),
1620            inputs.sky_prefilter,
1621            inputs.specular_dfg,
1622            frames,
1623        )?);
1624        service();
1625        // The occlusion cull's farthest pyramid, built from the Hi-Z pyramid's
1626        // reduction. Its images wait for a frame's extent.
1627        rollback.occlusion_pyramid = Some(OcclusionPyramid::new(
1628            device,
1629            frames,
1630            ForwardRenderer::build_depth_fullscreen,
1631        )?);
1632        service();
1633
1634        // --- the froxel volume ---
1635        //
1636        // Stored whole for the reason the march is, and after it because
1637        // `Rollback::run` releases in the reverse order of construction. It sits
1638        // between the march and the chain in the frame as well: the medium is
1639        // scene content and the chain is a lens. Its volume holds the same
1640        // [`FROXEL_CAPACITY`] the clustering pass's grid does, because it is
1641        // subdivided by the same [`Grid`] — see [`crate::volumetric`].
1642        //
1643        // **Built whatever the effects say**: its composite also puts an
1644        // atmosphere's air in front of the scene with the fog bit off, and the
1645        // water surface binds its buffers on every frame it draws.
1646        rollback.volumetric = Some(Volumetric::new(
1647            device,
1648            rollback
1649                .volumetric_pipelines
1650                .take()
1651                .unwrap_or_else(|| unreachable!("`View::build` placed the volume's set above")),
1652            frames,
1653            FROXEL_CAPACITY,
1654            inputs.shadow_map,
1655            inputs.shadow_sampler,
1656            lights,
1657        )?);
1658        service();
1659
1660        // --- auto-exposure ---
1661        //
1662        // Stored whole for the volume's reason, and after it because
1663        // `Rollback::run` releases in the reverse order of construction. It runs
1664        // between the chain and the tonemap in the frame as well: it bins the
1665        // picture the tonemap is about to read, which is the one with the lens
1666        // already on it — see [`crate::exposure`].
1667        //
1668        // **Built whatever the effects say**: the tonemap binds its measured
1669        // exposure on every frame, measuring or not.
1670        rollback.exposure = Some(Exposure::new(device, uploads, frames)?);
1671        service();
1672
1673        // --- the background ---
1674        //
1675        // Built last, so `Rollback::run` releases it first. It writes the scene
1676        // target rather than the caller's — it is scene content, drawn before
1677        // the operator, unlike the ground grid — and takes the depth format as
1678        // well, because it is the one full-screen pass in this frame that tests
1679        // against an attachment. See [`crate::sky_pass`].
1680        rollback.sky_pass = Some(SkyPass::new(
1681            device,
1682            frames,
1683            Format::Rgba16Float,
1684            Format::D32Float,
1685            ForwardRenderer::build_tested_fullscreen,
1686        )?);
1687        service();
1688
1689        // The water surface and the grass field are not built here: no body or
1690        // field exists until a caller sets one, which only a frame can see —
1691        // see [`View::build_content`].
1692
1693        // Whole, so the rollback lets go of every handle: the view owns them
1694        // from here, and a rollback still naming one would release it twice.
1695        let mut view =
1696            Self {
1697                effects: inputs.effects,
1698                background: inputs.background,
1699                lighting: inputs.lighting,
1700                target_format: inputs.target_format,
1701                // Replaced by every `begin_frame`, on `lod_params`' terms —
1702                // and the effects whose passes are built below, so a frame
1703                // recorded before one began asks for none that is missing.
1704                frame_effects: inputs.expected,
1705                // Replaced by every `begin_frame`, on `frame_effects`' terms.
1706                frame_aerial: false,
1707                // Replaced by every `begin_frame`, on `frame_effects`' terms.
1708                frame_ssr_extent: (1, 1),
1709                // Replaced by every `begin_frame`; no frame has a target yet.
1710                frame_extent: (0, 0),
1711                frame_target_extent: (0, 0),
1712                // No frame has begun it.
1713                begun: 0,
1714                draws: rollback.draws.take().unwrap_or_else(|| {
1715                    unreachable!("draw generation was placed in the rollback above")
1716                }),
1717                cluster_selection,
1718                fixed_probes,
1719                // Overwritten by the first `begin_frame`, which is the only thing
1720                // that can know the viewport. A zero scale with a budget of zero
1721                // selects nothing at all, and there is no frame yet to select for.
1722                lod_params: [0.0, 0.0, 0.0],
1723                lights: rollback.lights.take().unwrap_or_else(|| {
1724                    unreachable!("the light grid was placed in the rollback above")
1725                }),
1726                // Overwritten by the first `begin_frame` on `lod_params`' terms: a
1727                // one-froxel grid is the smallest legal one, and there is no
1728                // viewport yet to size a real one against.
1729                grid: Grid {
1730                    x: 1,
1731                    y: 1,
1732                    slices: 1,
1733                    tile_pixels: 1,
1734                },
1735                uniforms,
1736                mesh_groups,
1737                tonemap_uniforms,
1738                tonemap_groups: vec![None; frames],
1739                mesh_group_entries,
1740                prepass_group_entries,
1741                screen_channel_groups: vec![None; frames],
1742                prepass_groups,
1743                prepass_stats,
1744                // Replaced by every `begin_frame`, which `add_passes` documents as
1745                // having to run first.
1746                camera_view_proj: Mat4::IDENTITY,
1747                // No frame has been drawn, so there is no previous camera — see the
1748                // field, which says why that is not the identity.
1749                previous_view_projection: None,
1750                // Built below, for the effects the first frame is expected to
1751                // draw — see [`View::build_passes`].
1752                ssao: None,
1753                contact_shadows: None,
1754                hiz: None,
1755                occlusion_pyramid: rollback.occlusion_pyramid.take().unwrap_or_else(|| {
1756                    unreachable!("the occlusion pyramid was placed in the rollback above")
1757                }),
1758                ssr: rollback.ssr.take().unwrap_or_else(|| {
1759                    unreachable!("the reflection march was placed in the rollback above")
1760                }),
1761                volumetric: rollback.volumetric.take().unwrap_or_else(|| {
1762                    unreachable!("the froxel volume was placed in the rollback above")
1763                }),
1764                auto_exposure: rollback.exposure.take().unwrap_or_else(|| {
1765                    unreachable!("the histogram was placed in the rollback above")
1766                }),
1767                bloom: None,
1768                fxaa: None,
1769                cmaa2: None,
1770                upscale: None,
1771                sky_pass: rollback
1772                    .sky_pass
1773                    .take()
1774                    .unwrap_or_else(|| unreachable!("the sky was placed in the rollback above")),
1775                // Built by the first frame with a body or a field — see
1776                // [`View::build_content`].
1777                water: None,
1778                grass: None,
1779                shadow_sampler: inputs.shadow_sampler,
1780            };
1781        rollback.buffers.clear();
1782        rollback.bind_groups.clear();
1783        // The view owns every handle from here, so a failure releases the
1784        // view whole rather than through the rollback.
1785        if let Err(error) =
1786            view.build_passes(device, inputs.expected, inputs.expected_upscale, service)
1787        {
1788            view.destroy(device);
1789            return Err(error);
1790        }
1791        Ok(view)
1792    }
1793
1794    /// What a frame that resolved `frame` draws in a view that asked for
1795    /// `asked` and is lit by `lighting`.
1796    ///
1797    /// The shadow bit is the frame's whatever the view asked for — see
1798    /// [`ViewDesc::effects`] — and the effects that bring the frame's light in
1799    /// are the view's lighting's to take away — see
1800    /// [`ViewLighting::SCENE_EFFECTS`].
1801    pub(super) fn drawn_effects(
1802        frame: RenderEffects,
1803        asked: RenderEffects,
1804        lighting: ViewLighting,
1805    ) -> RenderEffects {
1806        frame
1807            .intersection(asked.union(RenderEffects::SHADOWS))
1808            .difference(lighting.dropped_effects())
1809    }
1810
1811    /// Builds every settings-driven pass a frame drawing `effects` records and
1812    /// this view does not hold yet, and the upscale where `upscaling` — and
1813    /// keeps them: a pass a later frame switches off stays built for the frame
1814    /// that switches it back on.
1815    ///
1816    /// **Between frames, never inside one**: [`View::begin_frame`] calls this
1817    /// before it writes a block, so a pass built here has its block written by
1818    /// the same call and is whole before [`View::add_passes`] records it. None
1819    /// of these passes uploads anything at creation — each constructor takes
1820    /// no [`UploadBatch`], which is what lets this run without one — and every
1821    /// per-frame resource each owns is a ring of `frames` blocks and groups;
1822    /// nothing is sized by the extent, which the graph's transients and the
1823    /// per-frame blocks carry instead, so a pass built late is the pass an
1824    /// early build would have made.
1825    ///
1826    /// The first frame that asks for a pass pays its pipeline creation —
1827    /// a hitch, cold, on the frame a setting switches it on.
1828    ///
1829    /// # Errors
1830    ///
1831    /// [`HalError`] from the pass's constructor. The passes already held stay
1832    /// held; one that failed part-way has released what it had created — see
1833    /// [`crate::partial`].
1834    pub(super) fn build_passes(
1835        &mut self,
1836        device: &dyn Device,
1837        effects: RenderEffects,
1838        upscaling: bool,
1839        service: &mut dyn FnMut(),
1840    ) -> Result<(), HalError> {
1841        let frames = self.uniforms.len();
1842        let fullscreen = ForwardRenderer::build_fullscreen;
1843        if effects.contains(RenderEffects::AMBIENT_OCCLUSION) && self.ssao.is_none() {
1844            self.ssao = Some(Ssao::new(device, frames, fullscreen)?);
1845            service();
1846        }
1847        if effects.contains(RenderEffects::CONTACT_SHADOWS) && self.contact_shadows.is_none() {
1848            self.contact_shadows = Some(ContactShadows::new(device, frames, fullscreen)?);
1849            service();
1850        }
1851        // Its pipeline is the only one here with a depth attachment and no
1852        // colour one — see [`ForwardRenderer::build_depth_fullscreen`].
1853        if effects.contains(RenderEffects::REFLECTIONS) && self.hiz.is_none() {
1854            self.hiz = Some(Hiz::new(
1855                device,
1856                frames,
1857                ForwardRenderer::build_depth_fullscreen,
1858            )?);
1859            service();
1860        }
1861        if effects.contains(RenderEffects::BLOOM) && self.bloom.is_none() {
1862            self.bloom = Some(Bloom::new(device, frames, fullscreen)?);
1863            service();
1864        }
1865        // **One tier, never both** — the one `add_passes` resolves through.
1866        if effects.contains(RenderEffects::CMAA2) {
1867            if self.cmaa2.is_none() {
1868                self.cmaa2 = Some(Cmaa2::new(device, frames, self.target_format, fullscreen)?);
1869                service();
1870            }
1871        } else if effects.contains(RenderEffects::ANTIALIASING) && self.fxaa.is_none() {
1872            self.fxaa = Some(Fxaa::new(device, frames, self.target_format, fullscreen)?);
1873            service();
1874        }
1875        if upscaling && self.upscale.is_none() {
1876            self.upscale = Some(Upscale::new(
1877                device,
1878                frames,
1879                self.target_format,
1880                fullscreen,
1881            )?);
1882            service();
1883        }
1884        Ok(())
1885    }
1886
1887    /// Builds the water passes where `water` and the grass passes where
1888    /// `grass`, unless this view holds them already — and keeps them: a frame
1889    /// whose bodies or field were removed leaves them built for the frame a
1890    /// caller sets some again.
1891    ///
1892    /// Content rather than a setting, so no build can know it: bodies and a
1893    /// field exist only once [`ForwardRenderer::set_water`] and
1894    /// [`ForwardRenderer::set_grass`] are called, which is after the renderer
1895    /// is built. **Between frames, never inside one**, on
1896    /// [`View::build_passes`]' terms exactly: [`View::begin_frame`] calls this
1897    /// before it writes either block, neither constructor uploads anything,
1898    /// and everything each owns per frame is a ring of `frames` blocks and
1899    /// groups.
1900    ///
1901    /// The first frame with water pays the surface's pipelines, and the first
1902    /// frame with grass its dispatches and the draw batch — a hitch, cold, on
1903    /// the frame a body or a field first appears. A call that builds both
1904    /// compiles them in one batch — see [`ContentPasses`] — and a caller that
1905    /// knows its content early can pay it under a loading screen instead — see
1906    /// [`ForwardRenderer::prepare_content`].
1907    ///
1908    /// `service` runs between the batch's rounds — see [`ContentPasses::new`].
1909    ///
1910    /// # Errors
1911    ///
1912    /// [`HalError`] from a constructor, and then this view holds what it held
1913    /// before the call: [`ContentPasses::new`] releases whatever it had
1914    /// created — see [`crate::partial`].
1915    pub(super) fn build_content(
1916        &mut self,
1917        device: &dyn Device,
1918        water: bool,
1919        grass: bool,
1920        service: &mut dyn FnMut(),
1921    ) -> Result<(), HalError> {
1922        let water = water && self.water.is_none();
1923        let grass = grass && self.grass.is_none();
1924        if !water && !grass {
1925            return Ok(());
1926        }
1927        // The atlas's comparison sampler, which both passes bind.
1928        let built = ContentPasses::new(
1929            device,
1930            self.uniforms.len(),
1931            self.shadow_sampler,
1932            water,
1933            grass,
1934            service,
1935        )?;
1936        if let Some(pass) = built.water {
1937            self.water = Some(pass);
1938        }
1939        if let Some(pass) = built.grass {
1940            self.grass = Some(pass);
1941        }
1942        Ok(())
1943    }
1944
1945    /// Writes every per-frame block this view reads, for `camera`, into the
1946    /// slot `frame` names — the camera's half of
1947    /// [`ForwardRenderer::begin_frame`].
1948    ///
1949    /// Returns the frame block it wrote, which the shadow views of the primary
1950    /// camera are spread from.
1951    ///
1952    /// # Errors
1953    ///
1954    /// [`HalError`] if any of the view's blocks could not be written.
1955    pub(super) fn begin_frame(
1956        &mut self,
1957        device: &dyn Device,
1958        camera: &Camera,
1959        frame: &ViewFrame<'_>,
1960        sky_view: Option<&PresentedSky>,
1961    ) -> Result<mesh::FrameUniforms, HalError> {
1962        let scene = frame.scene;
1963        let slot = frame.slot;
1964        let extent = frame.extent;
1965        // Read before this call advances it below: the first occlusion phase
1966        // reprojects through the matrix the pyramid it reads was drawn with.
1967        let previous_view_projection = self.previous_view_projection;
1968        // One matrix, used twice. Recomputing it for the frustum below would be
1969        // two chances to pass a different aspect ratio, and the failure that
1970        // produces — geometry culled against a camera the frame does not draw
1971        // with — is invisible until something at the edge of the screen
1972        // disappears.
1973        let view_projection = camera.view_projection(frame.aspect);
1974        // What this frame draws here, frozen for the reason the frame's own
1975        // effects are: this call and the passes have to agree.
1976        let effects = Self::drawn_effects(frame.effects, self.effects, self.lighting);
1977        // Every pass that set records and this view has not built yet, built
1978        // before any block below is written — see [`View::build_passes`]. Frozen
1979        // only once they exist, so a failed build leaves no frame asking for a
1980        // pass that is not there.
1981        self.build_passes(device, effects, extent != frame.target_extent, &mut || {})?;
1982        // The occlusion filters without the bent direction, on the first frame
1983        // no gather writes one — see `Ssao::prepare`. Here and not in the build,
1984        // so a renderer's construction does not depend on the console.
1985        if let Some(pass) = self
1986            .ssao
1987            .as_mut()
1988            .filter(|_| effects.contains(RenderEffects::AMBIENT_OCCLUSION))
1989        {
1990            let wanted = !crate::ssao::writes_bent(
1991                crate::ssao::technique(),
1992                crate::ssao::bent_normals(),
1993                crate::ssao::split_at().is_some(),
1994            );
1995            pass.prepare(device, ForwardRenderer::build_fullscreen, wanted)?;
1996        }
1997        // And the water and grass passes for the bodies and field this frame
1998        // draws, on the same terms — see [`View::build_content`].
1999        self.build_content(device, frame.water, frame.grass.is_some(), &mut || {})?;
2000        self.frame_effects = effects;
2001        self.frame_extent = extent;
2002        self.frame_target_extent = frame.target_extent;
2003        // What lights this view: the frame's sun, rows, probes, sky, fog and
2004        // shadow maps, or the one constant light its description fixed and
2005        // nothing of the frame's. Resolved once here so every block below reads
2006        // the same answer — a sun taken from one and a fill from the other
2007        // would be a view lit by half of each.
2008        //
2009        // **A fixed view's atlas rectangles are all empty**, which is how its
2010        // key light goes unshadowed with no shader of its own: every sampler of
2011        // the atlas answers lit for an empty rectangle before it reads a texel
2012        // (`mesh.slang`'s `atlas_rect_is_empty`), and the key is the view's only
2013        // row, so nothing else could name a tile.
2014        //
2015        // **A fixed view's environment is the sky its reflections see**, and
2016        // only its reflections: the gradient the march falls back to, with all
2017        // three bands the one radiance and no atmosphere, while the frame
2018        // block's L1 sky — the diffuse half — stays zero, so the fill is the
2019        // whole diffuse ambient. A uniform gradient is that radiance along
2020        // every direction and, to rounding, under every lobe the march
2021        // prefilters. The background pass keeps the frame's gradient: the
2022        // view's background is [`ViewDesc::background`]'s, not its lighting's.
2023        let key_row;
2024        let (light, rows, probe_volume, sky, fog, atlas_rects, reflected, reflected_air) =
2025            match self.lighting {
2026                ViewLighting::Scene => (
2027                    scene.light,
2028                    &scene.rows[..],
2029                    frame.probe_volume,
2030                    frame.sky_irradiance,
2031                    frame.fog,
2032                    scene.atlas_rects,
2033                    frame.gradient,
2034                    sky_view,
2035                ),
2036                ViewLighting::Fixed { key, environment } => {
2037                    key_row = [sun_row(&key)];
2038                    let band = environment.to_array();
2039                    (
2040                        key,
2041                        &key_row[..],
2042                        crcbl_shaders::probe::ProbeVolume::default(),
2043                        crcbl_shaders::probe::GpuProbe::ZERO,
2044                        Fog::NONE,
2045                        [[0.0; 4]; shadow::TILES],
2046                        crcbl_shaders::sky::SkyGradient {
2047                            zenith: band,
2048                            horizon: band,
2049                            ground: band,
2050                        },
2051                        None,
2052                    )
2053                }
2054            };
2055        self.begun = frame.serial;
2056        // The same matrix again for the ground grid, whose pass `add_passes`
2057        // records and which has no camera to ask.
2058        self.camera_view_proj = view_projection;
2059        // Topic 25's two selection numbers, from this frame's
2060        // viewport and this frame's camera. An orthographic projection has no
2061        // distance falloff for the metric to divide by, so it selects under a
2062        // budget nothing satisfies and draws the base level whole — see
2063        // [`LOD_BUDGET_NONE`].
2064        let lod_scale = camera.projection.pixels_per_unit(extent.1 as f32);
2065        let lod_budget = if camera.projection.is_orthographic() {
2066            LOD_BUDGET_NONE
2067        } else {
2068            frame.lod_error_budget
2069        };
2070        self.lod_params = [lod_scale, lod_budget, lod_budget * frame.lod_hold_ratio];
2071
2072        // The grid this frame's viewport and camera get. An orthographic camera
2073        // has no view depth to slice by — its `clip.w` is 1 everywhere — so it
2074        // runs with one slice, which `light_cluster.slang` builds a different
2075        // way rather than pretending it is a perspective frustum.
2076        let perspective = !camera.projection.is_orthographic();
2077        self.grid = Grid::for_frame(extent, perspective, self.lights.froxel_capacity());
2078        self.lights.begin_frame(
2079            device,
2080            slot,
2081            rows,
2082            self.grid,
2083            FrameView {
2084                extent,
2085                view_projection,
2086                eye: camera.eye,
2087                perspective,
2088            },
2089        )?;
2090        // The froxel volume's block: the same grid, the same camera and the
2091        // medium. **The same `Grid` value the clustering pass was just given**,
2092        // not a second `Grid::for_frame` — the composite converts a pixel to a
2093        // froxel index with these numbers, and two grids would have it read a
2094        // column built for somewhere else.
2095        //
2096        // Written whether or not this frame adds the passes, on every other
2097        // block's terms: one written only on the frames that draw is stale on
2098        // the frame a caller first switches the effect on.
2099        self.volumetric.begin_frame(
2100            device,
2101            slot,
2102            self.grid,
2103            FrameView {
2104                extent,
2105                view_projection,
2106                eye: camera.eye,
2107                perspective,
2108            },
2109            Medium {
2110                fog: frame.fog,
2111                sun: &scene.light,
2112                cascades: &scene.cascades,
2113                light_view_proj: &scene.light_view_proj,
2114                atlas_rects: &scene.atlas_rects,
2115                local: self.frame_effects.contains(RenderEffects::VOLUMETRIC_FOG),
2116                // The air follows the view's lighting, as the reflected sky
2117                // does: a fixed view is lit by nothing of the frame's, and the
2118                // atmosphere is the frame's.
2119                aerial: reflected_air.map(|presented| presented.view.sun_direction()),
2120            },
2121        )?;
2122        self.frame_aerial = reflected_air.is_some();
2123        self.frame_ssr_extent = crate::ssr::march_extent(extent, crate::ssr::resolution_scale());
2124
2125        let gradient = frame.gradient;
2126        let uniforms = mesh::FrameUniforms {
2127            view_proj: view_projection.to_cols_array(),
2128            camera_position: camera.eye.extend(1.0).to_array(),
2129            // The ambient's `w` is the normals view's switch — see
2130            // `set_normals_view` and the constants it names. A renderer nobody
2131            // has called that on writes the `0.0` this line has always written,
2132            // which is what makes every golden image untouched by the feature.
2133            ambient: light.ambient.extend(frame.debug_view_lane).to_array(),
2134            // **The frame's cascades, whichever camera this is.** They were
2135            // fitted to the primary camera and drawn once; a secondary view
2136            // samples the same maps through the same matrices, which is
2137            // `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
2138            shadow_view_proj: scene.shadow_view_proj,
2139            cascade_far: scene.cascades.far,
2140            shadow_params: Cascades::params(),
2141            cluster_grid: self.grid.to_frame_block(),
2142            light_view_proj: scene.light_view_proj,
2143            // The scene's grid, unchanged since `with_scene` read it: the
2144            // probes are static and nothing here varies them per frame. A
2145            // description with no probes leaves the default, which evaluates to
2146            // exactly zero in the shader.
2147            probes: probe_volume,
2148            // The very numbers the draw-argument pass selected under, carried
2149            // into the geometry stage so the screen-error heatmap shades by the
2150            // metric the cut was chosen with rather than by a second derivation
2151            // of it. `w` is padding — the block's rows are sixteen bytes wide
2152            // whatever is in them.
2153            lod_params: [
2154                self.lod_params[0],
2155                self.lod_params[1],
2156                self.lod_params[2],
2157                0.0,
2158            ],
2159            // `w` is padding on both rows — the block's rows are sixteen bytes
2160            // wide whatever is in them. A renderer nobody called `set_fog` on
2161            // writes a zero density here, which the fragment stage composites
2162            // as the identity.
2163            //
2164            // **Zeroed on a frame that runs the froxel volume**, which
2165            // integrates the same medium along the same rays: leaving it would
2166            // charge the air twice, once here and once in
2167            // `volumetric_composite.slang`, and the frame would be plausibly
2168            // over-fogged rather than wrong in a way anything reports. See
2169            // [`RenderEffects::VOLUMETRIC_FOG`].
2170            fog_params: [
2171                if self.frame_effects.contains(RenderEffects::VOLUMETRIC_FOG) {
2172                    0.0
2173                } else {
2174                    fog.density
2175                },
2176                fog.falloff,
2177                fog.reference_height,
2178                0.0,
2179            ],
2180            fog_color: fog.color.extend(0.0).to_array(),
2181            sky_sh_r: sky.sh_r,
2182            sky_sh_g: sky.sh_g,
2183            sky_sh_b: sky.sh_b,
2184            // **Last frame's camera, and this frame's on the first frame** —
2185            // see the field, which says why the fallback is this matrix rather
2186            // than the identity.
2187            previous_view_proj: self
2188                .previous_view_projection
2189                .unwrap_or(view_projection)
2190                .to_cols_array(),
2191            // Where the pool's attribute region begins, which is the one thing
2192            // about topic 43 §2's two streams that a
2193            // shader cannot derive: it is the pool's *capacity*, and a shader
2194            // has never been told that. Fixed for the life of the pool and
2195            // written every frame anyway, because this is the block that
2196            // carries it and there is no cheaper place. `yzw` are padding.
2197            vertex_pool: [frame.attribute_base, 0, 0, 0],
2198            // Where each atlas slot's map went, out of the allocator
2199            // `shadow::Selection::update` just spent — the *whole* of what the
2200            // sampling side knows about the atlas's shape, so a map is read
2201            // from the rectangle it was rendered into whatever size that was.
2202            // None at all on a fixed view — see `atlas_rects` above.
2203            shadow_atlas_rect: atlas_rects,
2204            // Which filter each side of the comparison seam samples through,
2205            // and where the seam falls — see `crate::split`, whose header
2206            // carries why a scene pass selects per pixel where a full-screen
2207            // effect records itself twice.
2208            //
2209            // **The column comes from `split::halves`' left rectangle** rather
2210            // than from a second multiplication here, so the seam module stays
2211            // the one place a fraction becomes a column: a frame comparing
2212            // nothing carries the console's own filter in both lanes and a zero
2213            // column, which is a row of zeroes at the default and therefore the
2214            // frame every golden was blessed as.
2215            shadow_filter: {
2216                let near = shadow::filter().mode();
2217                let seam = shadow::split_at().and_then(|at| crate::split::halves(extent, at));
2218                let (far, column) = seam.map_or((near, 0), |(left, _)| {
2219                    (shadow::shipped_filter().mode(), left.width)
2220                });
2221                [near, far, column, 0]
2222            },
2223        };
2224        // Advanced here, between writing the block that reads it and anything
2225        // else that could look at it: this runs exactly once per
2226        // `InstancePool::rotate` for a view that is drawn every frame, so the
2227        // camera's history moves on the same frame boundary the instances' does.
2228        // See the field.
2229        self.previous_view_projection = Some(view_projection);
2230        device.write_buffer(self.uniforms[slot], 0, &uniforms.to_bytes())?;
2231
2232        // The extent auto-exposure bins, which is the internal one — the
2233        // histogram reads the scene target, not the caller's window.
2234        //
2235        // Written whether or not this frame adds the passes, on every other
2236        // block's terms: one written only on the frames that measure is stale on
2237        // the frame a caller first switches the effect on.
2238        self.auto_exposure
2239            .begin_frame(device, slot, extent, frame.exposure_adaptation)?;
2240
2241        // The tonemap's one number, written here rather than in `add_passes` for
2242        // every other block's reason: a pass body runs at execute time, and the
2243        // buffer it reads has to have been written before the frame was
2244        // submitted.
2245        device.write_buffer(
2246            self.tonemap_uniforms[slot],
2247            0,
2248            &tonemap::TonemapParams {
2249                exposure: frame.exposure,
2250                // **Resolved rather than requested**, on `resolved_effects`'
2251                // terms: a readout view runs the clamp whatever the caller set,
2252                // because its pixels are data — see `resolved_tonemap_curve`.
2253                curve: frame.tonemap_curve,
2254                // **The switch, and it is this view's effects rather than the
2255                // caller's request**: a device that refused the effect draws the
2256                // frame with the number a caller set, and reading a buffer no
2257                // pass wrote would be reading whatever the last frame in this
2258                // slot left there.
2259                auto_exposure: self.frame_effects.contains(RenderEffects::AUTO_EXPOSURE),
2260                // The frame's coverage into the target's alpha on a transparent
2261                // view, and the opaque one every other view writes — see
2262                // [`ViewBackground::Transparent`].
2263                coverage_alpha: self.background.is_transparent(),
2264            }
2265            .to_bytes(),
2266        )?;
2267
2268        // Topic 46's occlusion block. **The projection
2269        // alone, not the view-projection**: the occlusion integral asks what is
2270        // near a surface, and view space is where "near" is isotropic and the eye
2271        // is at the origin — a world-space reconstruction would put the camera
2272        // somewhere else every frame and the hemisphere would have to be rotated
2273        // into it for no gain.
2274        //
2275        // `inverse` here rather than a hand-derived unprojection: an infinite
2276        // reversed-Z perspective and a reversed orthographic box do not share a
2277        // closed form, and the two matrices this pass needs are then provably
2278        // each other's inverse rather than two derivations that agree today.
2279        let projection = camera.projection.matrix(frame.aspect);
2280        let inv_projection = projection.inverse();
2281        // Written on every frame the pass exists for, whether or not this one
2282        // adds it, on every other block's terms.
2283        if let Some(pass) = &mut self.ssao {
2284            pass.begin_frame(
2285                device,
2286                slot,
2287                ssao::SsaoParams {
2288                    inv_proj: inv_projection.to_cols_array(),
2289                    proj: projection.to_cols_array(),
2290                    // View → world, for the bent direction alone: the gather works
2291                    // in view space and its one output has to reach `mesh.slang`'s
2292                    // world-space ambient term. The same expression the reflection
2293                    // pass's block carries, a few lines below.
2294                    inv_view: camera.view().inverse().to_cols_array(),
2295                    radius: crate::ssao::radius(),
2296                    slices: crate::ssao::slice_count(),
2297                    intensity: crate::ssao::intensity(),
2298                    bent_normals: crate::ssao::bent_normals(),
2299                },
2300            )?;
2301        }
2302        // The contact march's block: the same two matrices, and the sun in view
2303        // space.
2304        //
2305        // **Rotated here rather than in the shader**, because the shader has no
2306        // view matrix and no world-space anything: it walks a view-space ray in
2307        // screen space, so the one rotation the frame needs happens once on the
2308        // host instead of once per covered pixel. `Mat4::transform_vector3`
2309        // takes the direction through the rotation and drops the translation,
2310        // which is what a direction wants.
2311        //
2312        // `normalize_or_zero` for `sun_row`'s reason: a caller may hand this a
2313        // zero direction, and the march reads a zero as "the sun is along the
2314        // view axis at every pixel" and reports lit — which is the frame a
2315        // scene with no sun should draw.
2316        let to_light = camera
2317            .view()
2318            .transform_vector3(light.direction.normalize_or_zero())
2319            .normalize_or_zero();
2320        if let Some(pass) = &self.contact_shadows {
2321            pass.begin_frame(
2322                device,
2323                slot,
2324                contact_shadows::ContactShadowParams {
2325                    inv_proj: inv_projection.to_cols_array(),
2326                    proj: projection.to_cols_array(),
2327                    to_light: to_light.to_array(),
2328                },
2329            )?;
2330        }
2331        // The reflection march's block: the same two matrices and nothing else.
2332        // Its own buffer rather than the pair's — see [`crate::ssr::Ssr`] — and
2333        // the same pair of `glam` values, so a march and an occlusion sample can
2334        // never be looking at two different cameras.
2335        self.ssr.begin_frame(
2336            device,
2337            slot,
2338            ssr::SsrParams {
2339                inv_proj: inv_projection.to_cols_array(),
2340                proj: projection.to_cols_array(),
2341                inv_view: camera.view().inverse().to_cols_array(),
2342                probe_volume,
2343                // How far up the pyramid the march may climb, which is the
2344                // pyramid this extent has — `add_passes` records the reduction
2345                // whenever it records the march, so the two never disagree. A
2346                // frame too small to halve gets zero, and the march walks the
2347                // prepass at full resolution.
2348                hiz_levels: crate::hiz::levels_for(extent),
2349                // The image the march writes, which `add_passes` creates at
2350                // this same frozen extent.
2351                march_extent: [self.frame_ssr_extent.0, self.frame_ssr_extent.1],
2352                // The gradient itself rather than the projection the frame
2353                // block carries: this pass wants the radiance along one
2354                // direction and `Sky::gradient` is what has it exactly. A
2355                // renderer nobody called `set_sky` on writes three zero rows,
2356                // which the march adds to its probe fallback and changes
2357                // nothing. A fixed view's is its environment — see `reflected`
2358                // above.
2359                sky: reflected.rows(),
2360                // And the arm, on the background pass's terms below: an
2361                // atmosphere frame hands the march the sun its LUT was built
2362                // around, and every other frame — a fixed view's included —
2363                // the exactly-zero `w` that leaves `ssr.slang` evaluating the
2364                // gradient it always did.
2365                atmosphere: match reflected_air {
2366                    Some(presented) => {
2367                        let sun = presented.view.sun_direction();
2368                        [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON]
2369                    }
2370                    None => [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
2371                },
2372            },
2373        )?;
2374        // The background pass's block: the same two inverses `SsrParams` above
2375        // carries and the same three gradient rows, so a reflection that missed
2376        // and the sky behind it cannot be looking at two different skies.
2377        // Written whether or not this frame adds the pass, on the blocks below's
2378        // terms — a block written only on the frames that draw one is stale on
2379        // the frame a caller first calls `set_sky`.
2380        self.sky_pass.begin_frame(
2381            device,
2382            slot,
2383            inv_projection.to_cols_array(),
2384            camera.view().inverse().to_cols_array(),
2385            &gradient,
2386            sky_view.map(|presented| &presented.view),
2387        )?;
2388        // The water surface's own block: the sun its scattering is lit by and
2389        // whether this frame's air is the froxel column's. Written once the
2390        // passes are built whether or not the frame has water, on the blocks
2391        // above's terms — and the frame that builds them writes it, because
2392        // `build_content` ran above. The sun is normalised on `sun_row`'s
2393        // terms — a caller may hand the renderer any vector, and the shader
2394        // reads this as a unit direction.
2395        if let Some(water) = &self.water {
2396            water.begin_frame(
2397                device,
2398                slot,
2399                crcbl_shaders::water::WaterParams {
2400                    sun_direction: light.direction.normalize_or_zero().extend(0.0).to_array(),
2401                    sun_color: light.color.extend(0.0).to_array(),
2402                    froxels: self.frame_effects.contains(RenderEffects::VOLUMETRIC_FOG),
2403                },
2404            )?;
2405        }
2406        // The grass field's two blocks: the generation pass's, whose camera is
2407        // this view's, and the wind's, which the renderer holds for the whole
2408        // frame. Written on the water block's terms.
2409        if let Some(grass) = &self.grass {
2410            grass.begin_frame(
2411                device,
2412                slot,
2413                frame
2414                    .grass
2415                    .as_ref()
2416                    .map_or_else(Default::default, |grass| grass.gen_params(camera.eye)),
2417                frame.wind,
2418                crcbl_shaders::grass::Params {
2419                    limits: [
2420                        crate::grass::SLOT_CAPACITY,
2421                        frame
2422                            .grass
2423                            .as_ref()
2424                            .map_or(1, crate::grass::GrassFrame::rows),
2425                        0,
2426                        0,
2427                    ],
2428                    // **How many pixels a metre spans at one unit of view depth.**
2429                    // The projection's own `x` scale is `1 / (aspect · tan(fov/2))`
2430                    // for a perspective camera and `1 / half-width` for an
2431                    // orthographic one, and half the viewport's width takes a
2432                    // normalised-device length to pixels — so a card of `w` metres
2433                    // at a view depth of `d` is `w · this / d` pixels across, which
2434                    // is exactly what `grassCardLevel` reads. Taken off the very
2435                    // matrix this frame draws with rather than from the camera's
2436                    // own fields, so a projection this view resolved differently
2437                    // cannot disagree with it.
2438                    screen: [
2439                        view_projection.x_axis.x * 0.5 * extent.0 as f32,
2440                        0.0,
2441                        0.0,
2442                        0.0,
2443                    ],
2444                },
2445            )?;
2446        }
2447        // The bloom chain's blocks, one row per step: each step needs the texel
2448        // size of the image it reads, and the chain's shape is a function of the
2449        // extent alone. Written whether or not the chain is in this frame, on
2450        // the two blocks above's terms — a row nobody reads costs sixteen bytes.
2451        if let Some(pass) = &self.bloom {
2452            pass.begin_frame(device, slot, extent)?;
2453        }
2454        // The resolve's block: the reciprocal of the extent and three constants.
2455        // Written on the chain's terms above — a frame that adds no resolve pays
2456        // for twenty bytes nobody reads, and a block written only on the frames
2457        // that use it is a block that is stale on the frame a caller switches
2458        // the effect on.
2459        if let Some(pass) = &self.fxaa {
2460            pass.begin_frame(device, slot, extent)?;
2461        }
2462        // The higher tier's block: the extent and the two list capacities it
2463        // implies, written on the resolve's terms above. Sixteen bytes, and a
2464        // frame that resolves through the other tier pays for them and reads
2465        // none.
2466        if let Some(pass) = &mut self.cmaa2 {
2467            pass.begin_frame(device, slot, extent)?;
2468        }
2469        // The upscale's block: the internal extent and its reciprocal. Written
2470        // on the two above's terms — a frame at full scale adds no upscale pass
2471        // and pays for sixteen bytes nobody reads, and a block written only on
2472        // the frames that use it is stale on the frame a caller moves the knob.
2473        if let Some(pass) = &self.upscale {
2474            pass.begin_frame(device, slot, extent)?;
2475        }
2476
2477        // The camera and the two selection numbers go to the cull/draw-argument
2478        // pair as well as into the block above, and they are handed over rather
2479        // than re-derived: topic 25's uniform cut runs there, the
2480        // mesh path's per-cluster descent runs off the block, and a frame that
2481        // selected detail against one camera while drawing with another is a
2482        // difference nothing in the frame can see.
2483        //
2484        // **The eye is the selection's**, which is the camera's unless a caller
2485        // pinned the primary camera's — `set_frozen_selection_eye`, and the
2486        // whole of what that feature is. It reaches this parameter block and
2487        // nothing else: the frustum handed over with it is extracted from this
2488        // frame's own view-projection, and the frame block written above carries
2489        // `camera.eye`, so a pinned selection changes which cut is chosen and
2490        // nothing about what is culled, faced or drawn.
2491        //
2492        // **And what the cull does beyond the frustum.** The pyramid is made to
2493        // match this frame's extent first — a resize replaces it and forgets
2494        // its history — and a frame with no pyramid to read culls by the
2495        // frustum alone, which is what a one-texel target gets.
2496        let history = self.occlusion_pyramid.take_history(extent);
2497        let cull = match self.draws.occlusion_layout() {
2498            Some(layout) if frame.occlusion.any() => {
2499                self.occlusion_pyramid.prepare(device, extent, layout)?;
2500                if self.occlusion_pyramid.cull_group().is_some() {
2501                    FrameCull::Occlusion(OcclusionFrame {
2502                        view_projection,
2503                        previous_view_projection: previous_view_projection
2504                            .unwrap_or(view_projection),
2505                        target: extent,
2506                        pyramid_levels: self.occlusion_pyramid.levels(),
2507                        occlusion: frame.occlusion.occlusion,
2508                        // A first frame has no previous camera, and a chain
2509                        // just rebuilt holds nothing.
2510                        history: history && previous_view_projection.is_some(),
2511                        small_feature_pixels: frame.occlusion.small_feature_pixels,
2512                    })
2513                } else {
2514                    FrameCull::Plain
2515                }
2516            }
2517            _ => FrameCull::Plain,
2518        };
2519        self.draws.begin_frame_with(
2520            device,
2521            slot,
2522            &Frustum::from_view_projection(view_projection),
2523            frame.instance_count,
2524            crate::draw_gen::Selection {
2525                camera_position: [
2526                    frame.selection_eye.x,
2527                    frame.selection_eye.y,
2528                    frame.selection_eye.z,
2529                ],
2530                lod_params: self.lod_params,
2531            },
2532            &cull,
2533        )?;
2534        Ok(uniforms)
2535    }
2536
2537    /// Records this view's cull and draw-argument dispatches and the light
2538    /// clustering after them — the passes every other pass of the view reads.
2539    ///
2540    /// Separate from [`View::add_passes`] because the primary camera records
2541    /// these before the shadow atlas, which is where they always ran, and a
2542    /// secondary view records them straight before the rest of its frame.
2543    pub(super) fn add_cull(
2544        &self,
2545        graph: &mut RenderGraph<'_>,
2546        pool: &TransientPool,
2547        slot: usize,
2548        instance_count: u32,
2549    ) -> ViewCull {
2550        // The cull dispatch and the draw-argument dispatch, before anything
2551        // draws. Every barrier between them and the passes that draw — including
2552        // the one into `IndirectArgument` — is the graph's, computed from what
2553        // each pass declares.
2554        //
2555        // **Through the occlusion entry point** on a frame `begin_frame` began
2556        // with occlusion or small-feature culling, reading the pyramid the last
2557        // frame left: `DrawGen::begin_frame_with` recorded which.
2558        let occlusion_group = self
2559            .occlusion_pyramid
2560            .cull_group()
2561            .filter(|_| self.draws.uses_occlusion_entry(slot));
2562        let (generated, pyramid) = match occlusion_group {
2563            Some(group) => {
2564                let levels = self.occlusion_pyramid.import(graph, pool);
2565                let generated = self.draws.add_occlusion_passes(
2566                    graph,
2567                    slot,
2568                    instance_count,
2569                    &crate::draw_gen::PyramidInputs {
2570                        levels: &levels,
2571                        group,
2572                    },
2573                );
2574                let two_phase =
2575                    self.draws.frame_mode(slot) == crcbl_shaders::draw_gen::DrawMode::Occlusion;
2576                (
2577                    generated,
2578                    two_phase.then_some(ViewPyramid { levels, group }),
2579                )
2580            }
2581            None => (self.draws.add_passes(graph, slot, instance_count), None),
2582        };
2583        // Topic 25's record of the view's cut. Written by exactly
2584        // one mesh pass of this view, so what the graph orders here is this
2585        // frame's write against the next frame's use of the same slot.
2586        let selection = self
2587            .cluster_selection
2588            .get(slot)
2589            .map(|&buffer| import_read_write(graph, "cluster-selection", buffer));
2590        // Topic 18's clustering, **after the pair above and before anything
2591        // draws**. After, because the clearing dispatch is what zeroes the
2592        // overflow counter this pass adds to, and the two are ordered by the
2593        // graph out of the one id they both declare — which is why `stats` is
2594        // the id the draw generator handed back rather than a second import of
2595        // the same buffer. It has no other dependency on the cull: lights are
2596        // assigned to froxels, and a froxel is a property of the camera.
2597        let light_grid = self
2598            .lights
2599            .add_pass(graph, slot, generated.visible_count_id, self.grid);
2600        ViewCull {
2601            generated,
2602            selection,
2603            light_grid,
2604            pyramid,
2605            instance_count,
2606        }
2607    }
2608
2609    /// Records this view's frame: its prepass, the screen-space passes, the
2610    /// forward pass and every pass after it, ending in `target`.
2611    ///
2612    /// `output` is where the frame ends and how large it is drawn; `cull` is
2613    /// what [`View::add_cull`] recorded for this frame. The scene's passes — the
2614    /// skinning dispatch, the shadow atlas and the probe gather — are already
2615    /// in `graph`, and `passes` names what they left behind.
2616    ///
2617    /// Returns the image the tonemap read, which is the HDR frame before the
2618    /// operator.
2619    pub(super) fn add_passes<'a, F>(
2620        &'a mut self,
2621        graph: &mut RenderGraph<'a>,
2622        passes: &FramePasses,
2623        cull: ViewCull,
2624        output: ViewOutput,
2625        overlays: Overlays<'a>,
2626        overlay: F,
2627    ) -> ImageId
2628    where
2629        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
2630    {
2631        let ViewOutput {
2632            target,
2633            target_extent,
2634            extent,
2635        } = output;
2636        let frame = passes.slot;
2637        // What this frame draws in this view, frozen by `begin_frame` — see
2638        // [`View::frame_effects`]. Read once here so every conditional below is
2639        // about one value rather than about a read of a field each.
2640        let effects = self.frame_effects;
2641        let upscaling = extent != target_extent;
2642        let ViewCull {
2643            generated,
2644            selection,
2645            light_grid,
2646            pyramid: culled_pyramid,
2647            instance_count,
2648        } = cull;
2649        let emit = passes.emit;
2650        let skinned = passes.skinned;
2651        // The frame's sky, on every view but a transparent one — whose
2652        // background is the empty one it clears to. See
2653        // [`ViewBackground::Transparent`].
2654        let transparent = self.background.is_transparent();
2655        let draws_sky = passes.draws_sky && !transparent;
2656        // The table the reflection march and the water surface fall back to:
2657        // the scene's, or a fixed view's zeroed row — the one its forward
2658        // groups were built naming, see [`View::fixed_probes`]. The graph read
2659        // stays the scene's slot, which the frame wrote either way.
2660        let probe_buffer = self.fixed_probes.unwrap_or(passes.probe_buffer);
2661        let probe_table = passes.probe_table;
2662        let occlusion_placeholder = passes.occlusion_placeholder;
2663        let contact_placeholder = passes.contact_placeholder;
2664        let shadow_atlas = passes.shadow_atlas;
2665        let MaterialPages {
2666            base_color: base_color_page,
2667            normal: normal_page,
2668            mro: mro_page,
2669            emissive: emissive_page,
2670        } = passes.pages;
2671        let wireframe = passes.wireframe;
2672        let prepass_partitions = passes.prepass_partitions.clone();
2673        let color_partitions = passes.color_partitions.clone();
2674        let group = self.mesh_groups[frame];
2675
2676        let scene_color = graph.create_image("scene-color", crate::targets::scene_color(extent));
2677        let scene_depth = graph.create_image("scene-depth", crate::targets::scene_depth(extent));
2678        // The occlusion chain's transients, and **every one of them is
2679        // conditional**: a transient nothing reads or writes is a physical image
2680        // taken out of the pool for a pass that does not exist. What the forward
2681        // pass binds when they are absent is the 1×1 placeholder — see the pair
2682        // below.
2683        //
2684        // **Three of the four are at [`crate::ssao::half_extent`]**, which is
2685        // where the march and the blurs run — see that module's header. Only the
2686        // reconstruction's target is the scene's own size, because it is the
2687        // image `mesh.slang` reads at `SV_Position`.
2688        //
2689        // The blur's target is requested first, which is the order the two were
2690        // requested in when only one of them was conditional. The pool hands out
2691        // physical images in request order, and an AO-on frame has to be the
2692        // frame it was before this became a chain.
2693        let occlusion_chain = effects.contains(RenderEffects::AMBIENT_OCCLUSION).then(|| {
2694            let gathered = crate::ssao::half_extent(extent);
2695            let blurred =
2696                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
2697            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
2698            // The second blur's target, and requested **last of the small ones**
2699            // so the two above keep the physical images they had before this one
2700            // could be asked for — the pool hands them out in request order, and
2701            // a frame at the default switch has to be the frame it was.
2702            let again = (passes.ssao_blurs > 1).then(|| {
2703                graph.create_image(
2704                    "ssao-blurred-2",
2705                    crate::targets::ambient_occlusion(gathered),
2706                )
2707            });
2708            // The reconstruction's target, and the only one of these at the
2709            // scene's extent. Requested after the small ones for their reason
2710            // inverted: it is a different description, so it could not have
2711            // aliased them whatever the order, and asking for it last leaves
2712            // every request before it where it was.
2713            let upsampled =
2714                graph.create_image("ssao-upsampled", crate::targets::ambient_occlusion(extent));
2715            crate::ssao::OcclusionImages {
2716                raw,
2717                blurred,
2718                again,
2719                upsampled,
2720            }
2721        });
2722        // The contact march's one transient, conditional for the occlusion
2723        // pair's reason: an image nothing reads or writes is a physical image
2724        // out of the pool for a pass that does not exist. Requested **after**
2725        // the pair so that a frame with contact shadows off keeps the physical
2726        // images it had before this rung existed — the pool hands them out in
2727        // request order.
2728        let contact_mask = effects.contains(RenderEffects::CONTACT_SHADOWS).then(|| {
2729            graph.create_image("contact-shadows", crate::targets::contact_shadows(extent))
2730        });
2731        // **Created whatever the reflections are doing**, unlike the pair above.
2732        // It is one of the forward pass's colour attachments, which is in that
2733        // pipeline whether or not anything reads what it wrote — see the
2734        // `clear_color` on it below.
2735        let reflectivity = graph.create_image("reflectivity", crate::targets::reflectivity(extent));
2736        // **Created whatever else the frame is doing**, on the reflectivity
2737        // attachment's terms exactly: it is the forward pass's third colour
2738        // attachment, which is in that pipeline whether or not anything reads
2739        // what it wrote. Nothing does yet — TAA (`docs/backlog.md`) is the
2740        // first pass that will, and until then `DebugView::Motion`
2741        // is what observes the subtraction.
2742        let motion = graph.create_image("motion", crate::targets::motion(extent));
2743        // The march's output and the blur's, both in the scene target's format:
2744        // the blur writes the scene colour plus a term, so a narrower image
2745        // there would tonemap a truncated frame, and the march writes a
2746        // reflection *out of* that same colour, so an eight-bit image here would
2747        // clip the frame's bright end before the tonemap saw it. The march runs
2748        // at the extent `begin_frame` froze (`crate::ssr::march_extent`), which
2749        // is the scene's own at full resolution — and then three live requests
2750        // for one description are three physical images, see
2751        // `TransientPool::image`. The composite stays at the scene extent
2752        // because it replaces the scene colour from here on.
2753        let reflected = effects.contains(RenderEffects::REFLECTIONS).then(|| {
2754            (
2755                graph.create_image(
2756                    "reflection",
2757                    crate::targets::scene_color(self.frame_ssr_extent),
2758                ),
2759                graph.create_image("scene-reflected", crate::targets::scene_color(extent)),
2760            )
2761        });
2762        // Where the froxel volume's composite writes, conditional on the effect
2763        // for the reflection pair's reason exactly: an image nobody reads or
2764        // writes is a physical image taken out of the pool for a pass that does
2765        // not exist. It is the scene target's description, because it stands in
2766        // for that image from here on.
2767        //
2768        // **The fog effect or an atmosphere**: the composite is also what puts
2769        // the air in front of the scene — see [`crate::volumetric`] — so a
2770        // frame with an atmosphere composites whether or not its fog does.
2771        let fogged = (effects.contains(RenderEffects::VOLUMETRIC_FOG) || self.frame_aerial)
2772            .then(|| graph.create_image("scene-fogged", crate::targets::scene_color(extent)));
2773        // The Hi-Z pyramid's levels, **conditional on the march** that is the
2774        // only thing that reads them: an image nobody samples is a physical
2775        // image out of the pool for a pass that does not exist. Level 0 is the
2776        // prepass itself and is not in this list.
2777        //
2778        // Empty on a target too small to halve, which is a frame the march walks
2779        // at full resolution — `crate::hiz::levels_for` carries that floor, and
2780        // `SsrParams::hiz_levels` is what tells the shader about it.
2781        let pyramid: Vec<ImageId> = if reflected.is_some() {
2782            (1..=crate::hiz::levels_for(extent))
2783                .map(|level| {
2784                    graph.create_image(
2785                        format!("hiz-{level}"),
2786                        crate::targets::hiz_level(crate::hiz::level_extent(extent, level)),
2787                    )
2788                })
2789                .collect()
2790        } else {
2791            Vec::new()
2792        };
2793        // The bloom chain's levels and the image its composite writes, and
2794        // **all of them are conditional** on the pair above's terms exactly: a
2795        // transient nothing reads or writes is a physical image taken out of the
2796        // pool for a pass that does not exist.
2797        //
2798        // `None` covers two cases that are one case downstream — the toggle is
2799        // off, or the target is too small for even one level of chain (see
2800        // [`crate::bloom`]) — and in both the tonemap reads whatever it would
2801        // have read before, which is what makes this effect's off-switch
2802        // bit-identical.
2803        //
2804        // The levels are requested largest first, which is the order the
2805        // downsample chain writes them in. The composite's target is the scene
2806        // target's description exactly — it stands in for that image from here
2807        // on, so a narrower one would tonemap a truncated frame — which makes it
2808        // a fourth live request for that description on a frame that also
2809        // reflects, and therefore a fourth distinct physical image out of the
2810        // pool. See `TransientPool::image`.
2811        let bloomed = effects
2812            .contains(RenderEffects::BLOOM)
2813            .then(|| crate::bloom::mips_for(extent))
2814            .filter(|levels| *levels > 0)
2815            .map(|levels| {
2816                let mips: Vec<ImageId> = (1..=levels)
2817                    .map(|level| {
2818                        graph.create_image(
2819                            format!("bloom-mip-{level}"),
2820                            crate::targets::bloom_mip(crate::bloom::mip_extent(extent, level)),
2821                        )
2822                    })
2823                    .collect();
2824                (
2825                    mips,
2826                    graph.create_image("bloom-color", crate::targets::scene_color(extent)),
2827                )
2828            });
2829        // Where the tonemap writes, and it is the caller's `target` on every
2830        // frame that adds no resolve.
2831        //
2832        // **This is the one effect that changes the shape of the frame rather
2833        // than adding a pass to it** — see [`crate::fxaa`]. The resolve reads
2834        // what the tonemap wrote, so the tonemap has to write something the
2835        // resolve can sample, and a swapchain image is not that. So with the bit
2836        // on the tonemap writes a transient of the target's own description and
2837        // the resolve writes the target; with it off the tonemap writes the
2838        // target and there is no second image at all, which is what makes this
2839        // effect's off-switch bit-identical on the three above's terms.
2840        // Where the last pass of the internal frame writes, and it is the
2841        // caller's `target` on every frame drawn at full render scale.
2842        //
2843        // **This is the second effect in the frame that changes its shape rather
2844        // than adding a pass to it** — see [`crate::upscale`], and the resolve
2845        // below for the first. The upscale reads what the internal frame ended
2846        // with, so that last write has to go somewhere it can sample, and a
2847        // swapchain image at the caller's own extent is not it. So with the
2848        // scale below one the chain ends in a transient at the *internal*
2849        // extent and the upscale writes the target; at full scale there is no
2850        // second image at all, which is what makes the knob's off position
2851        // bit-identical.
2852        let present = if upscaling {
2853            graph.create_image(
2854                "render-scale-color",
2855                crate::targets::display_color(extent, passes.target_format),
2856            )
2857        } else {
2858            target
2859        };
2860        //
2861        // **Two tiers share that slot and at most one fills it** — see
2862        // [`RenderEffects::CMAA2`], which is where "never both" is written down.
2863        // The shape above is the same either way; what differs is what the
2864        // resolve reads besides the tonemap's image. CMAA2's two working
2865        // buffers are declared inside its own pass group rather than here,
2866        // where the tier it replaced declared two images: they are buffers,
2867        // and [`crate::cmaa2`]'s header says why the graph owns them all the
2868        // same.
2869        let resolving = effects.intersects(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2));
2870        let display = if resolving {
2871            graph.create_image(
2872                "display-color",
2873                crate::targets::display_color(extent, passes.target_format),
2874            )
2875        } else {
2876            present
2877        };
2878        // --- the depth prepass ---
2879        //
2880        // Topic 46's prepass, and it is unusually cheap:
2881        // the depth-only pipeline is already the shadow cascades' own, built from
2882        // the same modules and the same layout as the colour pipeline, so driven
2883        // with the camera's draws and a copy of the camera's bind group it *is* a
2884        // scene depth prepass — no new pipeline and no new shader. On a frame
2885        // whose material table masks nothing it is `depthVertexMain` and no
2886        // fragment stage, which is why the split-stream vertex pool pays for this
2887        // pass as well as for the atlas; a scene that masks something records its
2888        // masked buckets under the cutout twin and its opaque ones under this
2889        // one, and `depth_partitions` is where that split and its price are
2890        // argued.
2891        //
2892        // **Stored, unlike the depth the forward pass writes.** This is what the
2893        // occlusion pass samples, and it is the only reason
2894        // `crate::targets::scene_depth` carries `SAMPLED`.
2895        //
2896        // # The overdraw win, and what it rests on
2897        //
2898        // With this depth in the buffer the colour pass tests `GreaterOrEqual`
2899        // with writes off — `PassBuilder::depth_read` and
2900        // `DepthStencilState::equal_depth_read_only` — so every hidden fragment's
2901        // clustered-forward shading goes away. See
2902        // `MeshModules::color_depth_stencil`.
2903        //
2904        // **It rests on `SV_Position.z` invariance between the two pipelines**,
2905        // which the engine does not decorate for: a fragment the colour pass
2906        // places a hair farther than this pass did is *rejected*, and that
2907        // arrives as holes in the frame rather than as an error. Two things make
2908        // it hold rather than hope. On the mesh path the two passes run the
2909        // **same** geometry stage — `depth_pipeline`'s doc says so — so there is
2910        // nothing to diverge. On the vertex path `depthVertexMain` is the same
2911        // clip position written the same way as `vertexMain`'s, out of the same
2912        // module compiled in one invocation — and the cutout pipeline runs
2913        // `vertexMain` itself, so a masked frame's prepass is not merely the same
2914        // arithmetic as the colour pass's but the same code. The observable is a screenshot:
2915        // holes are not subtle, and the render-e2e goldens are what would catch
2916        // them on a rasteriser this machine does not have.
2917        let depth_group = self.prepass_groups[frame];
2918        // The prepass's own cluster counter — see
2919        // [`View::prepass_stats`]. Imported in the state the last frame
2920        // on this slot left it in, on `cluster-selection`'s terms exactly: a
2921        // barrier naming `Undefined` as its source carries no source scope, so it
2922        // would order this frame's write against nothing.
2923        let prepass_stats = import_read_write(graph, "prepass-stats", self.prepass_stats[frame]);
2924        let prepass_reads = PrepassReads {
2925            shadow_atlas,
2926            occlusion_placeholder,
2927            pages: passes.pages,
2928            probe_table,
2929            skinned,
2930            selection,
2931            prepass_stats,
2932        };
2933        // **Which of the generator's draw regions the prepass draws.** With the
2934        // occlusion cull on it is the survivors the first phase passed — the
2935        // late prepass below draws the ones the second phase rescued, and the
2936        // forward pass region 0, which is both. Off, it is region 0, which is
2937        // every survivor, exactly as before the cull existed.
2938        let two_phase = culled_pyramid.is_some();
2939        let early_region = if two_phase {
2940            crcbl_shaders::draw_gen::EARLY_REGION
2941        } else {
2942            0
2943        };
2944        let prepass = graph.add_render_pass("depth-prepass").depth(
2945            scene_depth,
2946            LoadOp::Clear,
2947            StoreOp::Store,
2948            crcbl_hal::ClearValue {
2949                depth: crcbl_hal::depth::CLEAR,
2950                ..crcbl_hal::ClearValue::default()
2951            },
2952        );
2953        let prepass = declare_prepass_reads(prepass, &prepass_reads, &generated, emit);
2954        let early_partitions = if two_phase {
2955            prepass_partitions.clone()
2956        } else {
2957            Vec::new()
2958        };
2959        prepass.execute(move |ctx| {
2960            let encoder = ctx.encoder();
2961            // One `open` per partition and its own buckets under it: the whole
2962            // pass is still one indirect call per bucket, drawn under the
2963            // pipeline that bucket's mode asked for.
2964            for partition in &prepass_partitions {
2965                partition.open(encoder);
2966                partition.record_region(encoder, depth_group, &generated, early_region);
2967            }
2968        });
2969
2970        // --- the occlusion cull's second phase ---
2971        //
2972        // Topic 03 §3.3: this frame's farthest
2973        // pyramid out of the early depth, every survivor the first phase marked
2974        // tested against it, and the ones it rescues drawn into the same depth
2975        // before anything reads it. See [`crate::occlusion_cull`].
2976        if let Some(culled) = &culled_pyramid {
2977            let levels = culled.levels.clone();
2978            let group = culled.group;
2979            self.occlusion_pyramid
2980                .add_passes(graph, frame, scene_depth, &levels);
2981            self.draws.add_late_passes(
2982                graph,
2983                frame,
2984                instance_count,
2985                &generated,
2986                &crate::draw_gen::PyramidInputs {
2987                    levels: &levels,
2988                    group,
2989                },
2990            );
2991            // **Loaded, not cleared**: the early prepass's depth is what the
2992            // rescued survivors are drawn into, and what everything after reads
2993            // is the two together.
2994            let late = graph.add_render_pass("depth-prepass-late").depth(
2995                scene_depth,
2996                LoadOp::Load,
2997                StoreOp::Store,
2998                crcbl_hal::ClearValue::default(),
2999            );
3000            let late = declare_prepass_reads(late, &prepass_reads, &generated, emit);
3001            late.execute(move |ctx| {
3002                let encoder = ctx.encoder();
3003                for partition in &early_partitions {
3004                    partition.open(encoder);
3005                    partition.record_region(
3006                        encoder,
3007                        depth_group,
3008                        &generated,
3009                        crcbl_shaders::draw_gen::LATE_REGION,
3010                    );
3011                }
3012            });
3013        }
3014
3015        // Topic 46's occlusion pair, or the one texel
3016        // that stands for "no occlusion was computed" where it is switched off.
3017        //
3018        // # The switched-off arm is the 1×1 placeholder, and the shader is what
3019        // makes that work
3020        //
3021        // Topic 18 sanctions the placeholder — "a renderer-owned 1×1 `R8Unorm`
3022        // cleared to 1.0, bound when the AO passes are not added" — and it is
3023        // what this binds. The property it rests on is not free: `mesh.slang`
3024        // reads this channel with a `Load` at `SV_Position.xy`, and a `Load`
3025        // outside a texture's extent yields **zero** rather than the nearest
3026        // texel, so the fetch has to be clamped against the image's own extent
3027        // or a one-texel image occludes everything but the origin. That clamp is
3028        // in `mesh.slang` and `crcbl`'s `forward_e2e::depth_probe` is what asks
3029        // whether it is; a frame drawn without it is black wherever ambient is the whole of
3030        // the light, on real hardware, with nothing reporting an error.
3031        //
3032        // So an AO-off frame records **no occlusion pass at all** and takes no
3033        // frame-sized image out of the transient pool: no shader permutation, no
3034        // uniform branch, one pipeline, and a bound value that occludes nothing.
3035        //
3036        // The placeholder's other job is unchanged — filling the binding for the
3037        // two depth-only passes, neither of which has a fragment stage and so
3038        // neither of which ever samples it.
3039        let occlusion = match occlusion_chain {
3040            Some(images) => self.ssao.as_mut().expect(BUILT_BY_BEGIN_FRAME).add_passes(
3041                graph,
3042                frame,
3043                extent,
3044                scene_depth,
3045                images,
3046            ),
3047            None => occlusion_placeholder,
3048        };
3049        // Topic 45's contact march, or the one texel that
3050        // stands for "the sun reaches this surface" where it is switched off.
3051        //
3052        // The occlusion pair's arms exactly, and the clamp the off-arm rests on
3053        // is `mesh.slang`'s `contact_at`. What differs is what it costs to get
3054        // wrong: an unclamped `Load` past this placeholder's one texel would
3055        // report *total* shadow at every pixel but one, so a frame with the
3056        // effect off would lose its sun rather than its ambient.
3057        //
3058        // Recorded here, after the occlusion pair and before the forward pass,
3059        // because the forward pass is what binds it — and the prepass it reads
3060        // has already run.
3061        let contact = match contact_mask {
3062            Some(mask) => self
3063                .contact_shadows
3064                .as_mut()
3065                .expect(BUILT_BY_BEGIN_FRAME)
3066                .add_passes(graph, frame, scene_depth, mask),
3067            None => contact_placeholder,
3068        };
3069
3070        let pass = graph
3071            .add_render_pass("forward")
3072            // Transparent black on a transparent view: zero coverage where no
3073            // geometry lands, and no colour for the air in front of the far
3074            // plane to add to but its own.
3075            .clear_color(
3076                scene_color,
3077                if transparent {
3078                    TRANSPARENT_CLEAR
3079                } else {
3080                    SCENE_CLEAR
3081                },
3082            )
3083            // `mesh.slang`'s second target, and **cleared rather than loaded or
3084            // discarded**. A pixel no geometry covered has no material, and the
3085            // pass that will read this marches a ray from whatever it finds
3086            // there — so the value that has to be in it is the one that says
3087            // "nothing reflects here", not the last frame's or an undefined
3088            // one. `NO_REFLECTION` is that value: no `F0`, and fully rough —
3089            // the alpha is a roughness, so a zero there would read as a
3090            // mirror. No picture tells the two apart, because a zero `F0`
3091            // leaves the reflection nothing to scale but Schlick's grazing
3092            // tail; what the alpha buys is that `ssr.slang` takes its early
3093            // return on every uncovered pixel instead of marching the sky.
3094            .clear_color(reflectivity, ssr::NO_REFLECTION)
3095            // `mesh.slang`'s third target, **cleared to zero** on the
3096            // reflectivity attachment's terms: a pixel no geometry covered has
3097            // no motion of its own, and zero is what a consumer reading its
3098            // history at `uv - motion` needs there — it reads the same pixel
3099            // back. It is not the *right* answer for the sky, whose motion is
3100            // the camera's and is owed to the pass that first wants it; it is
3101            // the answer that reprojects onto itself rather than onto
3102            // somewhere undefined. `docs/backlog.md` carries what is owed.
3103            .clear_color(motion, [0.0; 4]);
3104        // **Loaded and stored rather than cleared, and read-only**, which is the
3105        // half of the depth prepass that pays for the pass itself:
3106        // `MeshModules::color_depth_stencil` tests `GreaterOrEqual` with writes
3107        // off, so a fragment survives only where the prepass already put its
3108        // surface — and the clustered-forward shading of everything a nearer
3109        // surface goes on to cover is never run. It is stored because the
3110        // reflection march is downstream and reads exactly this image; the
3111        // values are the prepass's, which are this pass's own answer written by
3112        // the same transform.
3113        //
3114        // **The wireframe frame keeps the old shape**, because
3115        // `PolygonMode::Line` does not reproduce the prepass's depths — see
3116        // `color_depth_stencil`. It must *clear*: loading the prepass's depth
3117        // under the default `Greater` test rejects every fragment of the same
3118        // geometry, and the frame goes black.
3119        let pass = match wireframe {
3120            Some(_) => pass.depth(
3121                scene_depth,
3122                LoadOp::Clear,
3123                StoreOp::Store,
3124                crcbl_hal::ClearValue {
3125                    depth: crcbl_hal::depth::CLEAR,
3126                    ..crcbl_hal::ClearValue::default()
3127                },
3128            ),
3129            None => pass.depth_read(scene_depth),
3130        };
3131        let pass = pass
3132            // The occlusion channel this frame's ambient term is scaled by. On
3133            // an AO-on frame the blur pass wrote it as a colour attachment a
3134            // moment ago, so this declaration is the barrier into a
3135            // shader-readable layout; on an AO-off frame it is the imported
3136            // placeholder, which is in that layout already and has nothing to
3137            // transition.
3138            .read_image(occlusion)
3139            // The contact-shadow channel this frame's sun is scaled by, declared
3140            // on the occlusion channel's terms exactly: the march wrote it as a
3141            // colour attachment a moment ago and this is the barrier into a
3142            // shader-readable layout, or it is the imported placeholder and there
3143            // is nothing to transition.
3144            .read_image(contact)
3145            // **The page this pass's materials actually sample**, and the one
3146            // pass of the three where that is literally true. Declared so the
3147            // graph can order a caller's copy into a page layer against these
3148            // draws — see `base_color_page_import`.
3149            .read_image(base_color_page)
3150            // **And §2's other three pages, every one of which this pass's
3151            // fragment stage literally samples** — the normal map it perturbs
3152            // through, the packed roughness and metalness its lobe takes, and
3153            // the emissive radiance it adds. See `normal_page_import`.
3154            .read_image(normal_page)
3155            .read_image(mro_page)
3156            .read_image(emissive_page)
3157            // **The barrier out of the shadow pass's depth attachment.** The
3158            // atlas is in this pass's bind group at `SHADOW_ATLAS_BINDING`, and
3159            // without this declaration the graph leaves it in
3160            // `DepthStencilWrite` — which Vulkan reports as
3161            // `VUID-vkCmdDrawIndexedIndirectCount-imageLayout-00344` naming the
3162            // binding, and which every other backend reads as whatever the
3163            // depth writes left behind.
3164            .read_image(shadow_atlas)
3165            // The froxel grid, on the shadow atlas's terms exactly: the
3166            // clustering pass left it in `ShaderReadWrite` and the fragment
3167            // stage has it bound, so declaring the read is what moves it — and
3168            // without the declaration the fragment stage reads a buffer the
3169            // compute pass may still be writing.
3170            .read_buffer(light_grid)
3171            // The probe rows, on the froxel grid's terms and for a hazard that
3172            // does not exist yet: nothing writes a probe on the GPU today, so
3173            // this frame's slot is already in `ShaderRead` and the graph has
3174            // nothing to transition. It is declared anyway, because the rows are
3175            // device-local and `TRANSFER_DST` precisely so
3176            // the irradiance probes' gather can write them — and
3177            // a pass that binds a buffer without declaring it is a pass the
3178            // graph cannot barrier the day something does.
3179            .read_buffer(probe_table);
3180        // And the skinned vertices, which is the declaration this whole entry
3181        // point exists for: without it the vertex stage pulls a region the
3182        // compute dispatch may still be writing, and the graph — which is told
3183        // about every other hazard in the frame — has not been told about this
3184        // one.
3185        let pass = match skinned {
3186            Some(vertices) => pass.read_buffer(vertices),
3187            None => pass,
3188        };
3189        let pass = read_draw_sources(pass, &generated, emit);
3190        let pass = match selection {
3191            // The colour pass's own, which no cascade writes — the cascades
3192            // record into buffers of their own, so what survives a frame here is
3193            // the camera's cut and what survives there is each cascade's. The
3194            // depth prepass above writes this one too, with the same camera and
3195            // the same budget, and is ordered before this pass by the graph.
3196            Some(selection) if emit.is_mesh() => {
3197                pass.use_buffer(selection, ResourceState::ShaderReadWrite)
3198            }
3199            _ => pass,
3200        };
3201
3202        // The camera's group rebuilt against the two screen-space channels the
3203        // graph just realised, cached against both views and the probe
3204        // visibility maps — the shape the tonemap group below has, and for the
3205        // same reason: a graph transient's view is not known until execute time.
3206        // Three entries of the stored list differ; see
3207        // `View::mesh_group_entries`.
3208        //
3209        //
3210        // The rebuild is unconditional, so there is one shape of forward pass
3211        // rather than two: the group is cached against the views it was built
3212        // from, so an AO-off frame naming the placeholder's view and an AO-on
3213        // frame naming the blur's target are the same code and one cache miss
3214        // apiece when a toggle moves. **The key is both views**, because a group
3215        // naming two transients is stale as soon as either one moves.
3216        let entries = self.mesh_group_entries[frame].as_slice();
3217        let mesh_layout = passes.mesh_layout;
3218        // The captured probe-visibility maps, or the one-texel placeholder when
3219        // nothing has been captured or the console switch is off. It rides
3220        // through the same cache as the two channels beside it — it is not a
3221        // graph transient, but it does change between frames when the switch
3222        // moves, and a group cached against a view it no longer names is the
3223        // failure that cache exists to stop.
3224        let probe_visibility_view = passes.probe_visibility;
3225        let cached_mesh = &mut self.screen_channel_groups[frame];
3226        pass.execute(move |ctx| {
3227            let view = ctx.image_view(occlusion);
3228            let contact_view = ctx.image_view(contact);
3229            let device = ctx.device();
3230            let group = cached_group(
3231                cached_mesh,
3232                device,
3233                &[
3234                    (AMBIENT_OCCLUSION_BINDING, view),
3235                    (CONTACT_SHADOW_BINDING, contact_view),
3236                    (PROBE_VISIBILITY_BINDING, probe_visibility_view),
3237                ],
3238                "mesh frame",
3239                mesh_layout,
3240                entries,
3241            )
3242            // Falling back to the group built at `build` rather than dropping
3243            // the frame, and **the fallback costs the occlusion and the contact
3244            // shadow and nothing else**: that group names the two 1×1 white
3245            // placeholders, which `mesh.slang` clamps its `Load`s into and reads
3246            // as "nothing occludes" and "the sun reaches here". A descriptor
3247            // failure therefore draws the frame this scene would have drawn with
3248            // both effects switched off, rather than one with no ambient term
3249            // and no sun in it.
3250            .unwrap_or(group);
3251            let encoder = ctx.encoder();
3252            // One `open` per partition and its own buckets under it, on the
3253            // depth prepass's terms: the pass is still one indirect call per
3254            // bucket, drawn under the pipeline that bucket's side asked for.
3255            for partition in &color_partitions {
3256                partition.open(encoder);
3257                partition.record(encoder, group, &generated);
3258            }
3259        });
3260
3261        // `docs/plan/57-grass.md`'s field, **after the forward pass and before
3262        // the background**. Grass is opaque scene content with a cutout: the
3263        // depth its cards write has to be in the buffer before the sky decides
3264        // which pixels it covers, before the Hi-Z pyramid is built and before
3265        // the reflection march reads the frame. A frame with no field adds
3266        // nothing here and takes no transient — see [`crate::grass`].
3267        if let Some(field) = passes.grass {
3268            let frame_block = self.uniforms[frame];
3269            self.grass
3270                .as_mut()
3271                .expect(CONTENT_BUILT_BY_BEGIN_FRAME)
3272                .add_passes(
3273                    graph,
3274                    frame,
3275                    crate::grass::GrassImages {
3276                        color: scene_color,
3277                        depth: scene_depth,
3278                        shadow_atlas,
3279                    },
3280                    crate::grass::GrassInputs {
3281                        frame_block,
3282                        lights: self.lights.lights(frame),
3283                        cluster_lights: self.lights.grid(frame),
3284                        light_grid,
3285                        field,
3286                    },
3287                );
3288        }
3289
3290        // --- the background ---
3291        //
3292        // **After the forward pass and before everything that reads the scene
3293        // colour**, which is what makes the sky the background of the frame the
3294        // reflection composite, the bloom chain and the tonemap all work on
3295        // rather than a colour added at the end.
3296        //
3297        // It does not disturb the reflection itself. The march reads the scene
3298        // colour only at a crossing it found in the depth prepass, and the far
3299        // plane has no surface to cross to — `ssr.slang` returns before it
3300        // marches on a pixel whose depth is the clear value — so nothing this
3301        // pass writes is ever tapped as a reflected colour. A ray that leaves
3302        // the frame still falls back to the analytic gradient rather than to
3303        // these texels, which is the same sky evaluated exactly.
3304        //
3305        // Conditional on the sky and not on [`RenderEffects`], on the ground
3306        // grid's terms: see [`crate::sky_pass`] for why the off position has to
3307        // be no pass at all.
3308        if draws_sky {
3309            self.sky_pass
3310                .add_pass(graph, frame, scene_color, scene_depth);
3311        }
3312
3313        // What the water surface reads out of three other passes' state, read
3314        // before those passes take their mutable borrows below — see
3315        // [`crate::water`] for why it binds their handles rather than copies.
3316        let water_reads = (
3317            self.uniforms[frame],
3318            self.ssr.uniforms(frame),
3319            self.ssr.sky_prefilter_view(),
3320            self.volumetric.buffers(frame),
3321            self.sky_pass.lut(frame),
3322        );
3323
3324        // The froxel volume, and it composites over
3325        // the sky as well as over the geometry — a pixel at the far plane is a
3326        // whole column of air, which is exactly what makes a distant horizon
3327        // read as distant.
3328        //
3329        // **Before the reflection march**, where `mesh.slang`'s closed form also
3330        // ran: the march reads the scene colour as reflected radiance, and fog
3331        // it can see is fog the surface it bounced off could see. The reflection
3332        // the blur adds afterwards is still unfogged, which is the same gap the
3333        // analytic path has and `docs/backlog.md` carries.
3334        //
3335        // The atmosphere's air is composed in the same pass, and on the same
3336        // side of the reflection march, for the same reason: the march reads
3337        // what the surface it bounced off could see.
3338        let (scene_color, froxel_ids) = match fogged {
3339            Some(composited) => {
3340                // Read before the split borrow below, on `sky_view_lut`'s
3341                // terms: `self.volumetric` is taken mutably.
3342                let aerial = self.sky_pass.aerial(frame);
3343                let ids = self.volumetric.add_passes(
3344                    graph,
3345                    frame,
3346                    self.grid,
3347                    VolumetricImages {
3348                        depth: scene_depth,
3349                        color: scene_color,
3350                        composited,
3351                        shadow_atlas,
3352                    },
3353                    VolumetricReads {
3354                        light_grid,
3355                        local: effects.contains(RenderEffects::VOLUMETRIC_FOG),
3356                        aerial,
3357                    },
3358                );
3359                (composited, Some(ids))
3360            }
3361            None => (scene_color, None),
3362        };
3363
3364        // Topic 47's reflection march and its blur, and
3365        // **the second of them is the composite**: the march reads the scene
3366        // colour, the depth prepass and the reflectivity attachment and writes
3367        // the reflection alone, and the blur filters that and adds it to the
3368        // scene colour — so everything below this line works on `tonemapped`
3369        // rather than on `scene_color`. A frame that does not add the pair hands
3370        // `scene_color` on and is bit-identical, which is this effect's whole
3371        // off-switch.
3372        let tonemapped = match reflected {
3373            Some((reflection, composited)) => {
3374                // Read before the split borrow below: `self.ssr` is taken
3375                // mutably by `add_passes` and this names a different field.
3376                let sky_view_lut = self.sky_pass.lut(frame);
3377                // The pyramid first: the march climbs it, so every level has to
3378                // be written before the pass that reads it is recorded. Skipped
3379                // outright on a frame whose extent has no levels, which
3380                // `Hiz::add_passes` would record zero passes for anyway.
3381                self.hiz.as_mut().expect(BUILT_BY_BEGIN_FRAME).add_passes(
3382                    graph,
3383                    frame,
3384                    extent,
3385                    scene_depth,
3386                    &pyramid,
3387                );
3388                self.ssr.add_passes(
3389                    graph,
3390                    frame,
3391                    SsrImages {
3392                        depth: scene_depth,
3393                        color: scene_color,
3394                        reflectivity,
3395                        reflection,
3396                        composited,
3397                        pyramid: crate::hiz::level_slots(scene_depth, &pyramid),
3398                    },
3399                    SsrEnvironment {
3400                        probes: probe_buffer,
3401                        probe_id: probe_table,
3402                        // The same view the forward pass's own group named, so
3403                        // the reflection's probe fallback is weighed by the
3404                        // maps the diffuse gather was weighed by — or by the
3405                        // placeholder, when there are none and every probe
3406                        // keeps all of its weight.
3407                        probe_visibility: probe_visibility_view,
3408                        // The background pass's own LUT slot, not a copy of it
3409                        // — see [`crate::sky_pass::SkyPass::lut`]. A frame with
3410                        // no atmosphere binds the zeroes that buffer was
3411                        // created holding, and `ssr.slang` returns before
3412                        // reading it.
3413                        sky_view: sky_view_lut,
3414                    },
3415                );
3416                composited
3417            }
3418            None => scene_color,
3419        };
3420
3421        // `docs/plan/55-water.md`'s surface, **after the reflection composite
3422        // and before the bloom chain**. After, because the surface computes its
3423        // own reflection and is not a receiver of the shared march, which has
3424        // already run; before, because water is scene content and the chain is
3425        // a lens. It draws into the image the chain would have read and into the
3426        // scene depth, in place, so every pass below reads the same two images
3427        // it always did. A frame with no bodies adds nothing here and takes no
3428        // transient — see [`crate::water`] — and requests its two after every
3429        // other image this view asks for, so the pool hands each of those the
3430        // physical image it had before water existed.
3431        if let Some(mesh) = passes.water.clone() {
3432            let color_copy = graph.create_image("water-color", crate::targets::scene_color(extent));
3433            let depth_copy = graph.create_image("water-depth", crate::targets::hiz_level(extent));
3434            let (frame_block, reflection_block, sky_prefilter, froxels, sky_view) = water_reads;
3435            let inputs = WaterInputs {
3436                frame_block,
3437                reflection_block,
3438                froxels,
3439                froxel_ids,
3440                probes: probe_buffer,
3441                probe_id: probe_table,
3442                probe_visibility: passes.probe_visibility,
3443                sky_prefilter,
3444                sky_view,
3445                mesh,
3446            };
3447            self.water
3448                .as_mut()
3449                .expect(CONTENT_BUILT_BY_BEGIN_FRAME)
3450                .add_passes(
3451                    graph,
3452                    frame,
3453                    WaterImages {
3454                        color: tonemapped,
3455                        depth: scene_depth,
3456                        color_copy,
3457                        depth_copy,
3458                        shadow_atlas,
3459                    },
3460                    inputs,
3461                );
3462        }
3463
3464        // Topic 48's bloom chain, and it slots in
3465        // exactly where the reflection composite left off: it reads whatever the
3466        // tonemap was about to read, writes a new full-resolution image, and the
3467        // tonemap reads that instead. A frame that does not add it hands the
3468        // image on untouched and is bit-identical, which is this effect's whole
3469        // off-switch — and the group the tonemap builds below is cached against
3470        // its source view, so a toggle costs one cache miss and nothing else.
3471        let tonemapped = match &bloomed {
3472            Some((mips, composited)) => {
3473                self.bloom.as_mut().expect(BUILT_BY_BEGIN_FRAME).add_passes(
3474                    graph,
3475                    frame,
3476                    extent,
3477                    tonemapped,
3478                    mips,
3479                    *composited,
3480                );
3481                *composited
3482            }
3483            None => tonemapped,
3484        };
3485
3486        // Topic 43 §6's auto-exposure, and it reads
3487        // the image the tonemap is about to read: the frame with the medium, the
3488        // reflection and the chain already in it, which is the picture a viewer
3489        // sees and therefore the one to expose for. Binning `scene_color`
3490        // instead would expose the frame for a picture nobody looks at.
3491        //
3492        // Read first because the passes borrow the ring for the rest of this
3493        // function, and the tonemap below needs the handle out of it.
3494        let measured = self.auto_exposure.measured(frame);
3495        if effects.contains(RenderEffects::AUTO_EXPOSURE) {
3496            self.auto_exposure
3497                .add_passes(graph, frame, extent, tonemapped);
3498        }
3499
3500        // --- the debug draw layer ---
3501        //
3502        // **Before the tonemap, into the HDR image the tonemap is about to
3503        // read**, which is `docs/plan/18-render-features.md`'s interaction rule:
3504        // "Debug overlays (debug draw, gizmos) render pre-tonemap in HDR
3505        // (they're in the world) except UI-space panels." A segment is therefore
3506        // exposed and tonemapped like the geometry it annotates, which is the
3507        // opposite of the ground grid below — and [`crate::grid`]'s header and
3508        // [`crate::debug_draw`]'s carry the two halves of that argument.
3509        //
3510        // **And after everything that reads the scene colour.** The reflection
3511        // march, the bloom chain and the auto-exposure histogram have all
3512        // already been recorded against this image, so a debug line does not
3513        // reflect in a surface, does not bloom, and does not move the exposure
3514        // the scene is metered at. Each of those would be an overlay changing
3515        // the picture it is drawn over, which is the one thing an overlay must
3516        // not do.
3517        //
3518        // Nothing here is conditional on [`RenderEffects`], on the ground
3519        // grid's terms: a frame that appended no segment is the frame this
3520        // renderer recorded before [`crate::debug_draw`] existed — no pass, no
3521        // pipeline, no block.
3522        if let Some(debug_draw) = overlays.debug_draw {
3523            debug_draw.add_pass(graph, frame, tonemapped, scene_depth);
3524        }
3525
3526        // **None of the display work under the shadow atlas viewer.** It fills
3527        // every display pixel with a `DontCare` load, so a tonemapped frame or a
3528        // grid recorded first would be stored and immediately discarded. The HDR
3529        // scene passes above stay: callers still read their output.
3530        if overlays.atlas_viewer.is_none() {
3531            // The tonemap group names a *graph-owned* view, so it can only be built
3532            // once the graph has realised one. It is cached against the view handle
3533            // and therefore rebuilt only on a resize.
3534            let TonemapPipeline {
3535                sampler,
3536                layout,
3537                pipeline_layout,
3538                pipeline: tonemap_pipeline,
3539            } = passes.tonemap;
3540            let exposure_block = self.tonemap_uniforms[frame];
3541            let cached = &mut self.tonemap_groups[frame];
3542
3543            graph
3544                .add_render_pass("tonemap")
3545                // `DontCare`, not `Clear`: the full-screen triangle writes every
3546                // pixel of the target, so loading or clearing it is pure bandwidth.
3547                .color(
3548                    display,
3549                    LoadOp::DontCare,
3550                    StoreOp::Store,
3551                    crcbl_hal::ClearValue::default(),
3552                )
3553                // **The reflection pass's output where there is one, and the forward
3554                // pass's where there is not.** The two are the same description and
3555                // different images, and tonemapping the first one on a frame that
3556                // reflected would compile, draw a picture, and silently be the frame
3557                // without reflections in it.
3558                .read_image(tonemapped)
3559                .execute(move |ctx| {
3560                    let view = ctx.image_view(tonemapped);
3561                    let device = ctx.device();
3562                    let entries = [
3563                        BindGroupEntry {
3564                            binding: 0,
3565                            array_index: 0,
3566                            resource: BindingResource::ImageView(view),
3567                        },
3568                        BindGroupEntry {
3569                            binding: 1,
3570                            array_index: 0,
3571                            resource: BindingResource::Sampler(sampler),
3572                        },
3573                        BindGroupEntry {
3574                            binding: 2,
3575                            array_index: 0,
3576                            resource: BindingResource::whole_buffer(exposure_block),
3577                        },
3578                        BindGroupEntry {
3579                            binding: 3,
3580                            array_index: 0,
3581                            resource: BindingResource::whole_buffer(measured),
3582                        },
3583                    ];
3584                    let Some(group) = cached_group(
3585                        cached,
3586                        device,
3587                        &[(0, view)],
3588                        "tonemap scene",
3589                        layout,
3590                        &entries,
3591                    ) else {
3592                        return;
3593                    };
3594                    let encoder = ctx.encoder();
3595                    encoder.bind_graphics_pipeline(tonemap_pipeline);
3596                    encoder.bind_group(0, group, &[], pipeline_layout);
3597                    // Three vertices, no geometry bound, no vertex buffer anywhere.
3598                    encoder.draw(0..3, 0..1);
3599                });
3600
3601            // --- the ground grid ---
3602            //
3603            // **After the tonemap, into the target the tonemap just wrote**, and
3604            // that placement is the decision rather than an accident of ordering.
3605            // The grid is reference chrome, not scene content: drawn into
3606            // `scene_color` it would be exposed and tonemapped like geometry, so its
3607            // colour would shift with how bright the scene happens to be — and a
3608            // grid whose lines change with the exposure is no longer a reference.
3609            // Blender draws its overlays the same way, in display space after the
3610            // render.
3611            //
3612            // It still takes `scene_depth`, read-only, so geometry in front of the
3613            // ground occludes it. That the depth survives this far is not luck: the
3614            // forward pass stores it (`StoreOp::Store`) because the reflection march
3615            // reads it, and the graph moves it from whatever state that left it in
3616            // into `DepthStencilRead` for this pass.
3617            //
3618            // Nothing here is conditional on [`RenderEffects`]: the grid is a
3619            // caller's opt-in, and a frame that never asked for one is the frame
3620            // this renderer recorded before [`crate::grid`] existed — no pass, no
3621            // pipeline, no block.
3622            if let Some(grid) = overlays.ground_grid {
3623                let view_proj = self.camera_view_proj;
3624                grid.add_pass(
3625                    graph,
3626                    frame,
3627                    display,
3628                    scene_depth,
3629                    view_proj,
3630                    // The one inversion in the frame, and it is here rather than in
3631                    // the pass: `begin_frame` has no reason to compute it for a grid
3632                    // that is usually off.
3633                    view_proj.inverse(),
3634                );
3635            }
3636        }
3637
3638        // --- the shadow atlas viewer ---
3639        //
3640        // **After the grid and before the resolve, and it replaces what both of
3641        // them were about.** Sundial's atlas viewer:
3642        // the `D32Float` image the shadow pass filled, drawn over the finished
3643        // frame so that which slot holds which map is something a reviewer can
3644        // look at. [`crate::atlas_view`] carries why it draws here — in display
3645        // space, after the operator — rather than into the scene colour.
3646        //
3647        // After the grid because a grid over a readout is noise; before the
3648        // resolve because there is nothing to resolve, and nothing to resolve
3649        // *with*: [`Self::resolved_effects`] takes both antialiasing tiers off
3650        // for every debug view, so `display` and `present` are one image on
3651        // every frame this branch runs on.
3652        //
3653        // Nothing here is conditional on [`RenderEffects`], on the ground
3654        // grid's terms: a frame that resolved any other view is the frame this
3655        // renderer recorded before this module existed — no pass, no pipeline,
3656        // no block read.
3657        if let Some(atlas_viewer) = overlays.atlas_viewer {
3658            atlas_viewer.add_pass(graph, frame, shadow_atlas, display);
3659        }
3660
3661        overlay(
3662            graph,
3663            ForwardOverlayTargets {
3664                display,
3665                depth: scene_depth,
3666                internal_extent: extent,
3667            },
3668        );
3669
3670        // --- the antialiasing resolve ---
3671        //
3672        // **After the grid, and that is the same decision the grid's placement
3673        // was.** The grid is a field of thin high-contrast lines, which is the
3674        // thing an edge filter exists for; drawing it into the target *after*
3675        // the resolve would leave it the one aliased element in an antialiased
3676        // frame. The UI goes the other way and is composited onto `target` by
3677        // the caller after this, so its glyphs are never filtered — topic 18
3678        // refuses to antialias text in as many words.
3679        //
3680        // `display` is `present` when neither antialiasing bit is on, and this
3681        // is the branch that makes that true: no pass, no second image, and the
3682        // frame the tonemap wrote is already where the frame ends.
3683        //
3684        // **Which tier fills the slot is decided here, once.** CMAA2 is the
3685        // higher one and takes it whenever its bit is on, whatever the FXAA bit
3686        // says — the two are never both recorded, which is what
3687        // [`RenderEffects::CMAA2`] means by a tier that is off being a frame with
3688        // fewer passes rather than a shader branch. Everything the paragraph
3689        // above says about the grid, the UI and the ordering holds for either.
3690        if display != present {
3691            if effects.contains(RenderEffects::CMAA2) {
3692                self.cmaa2
3693                    .as_mut()
3694                    .expect(BUILT_BY_BEGIN_FRAME)
3695                    .add_passes(graph, frame, display, present);
3696            } else {
3697                self.fxaa
3698                    .as_mut()
3699                    .expect(BUILT_BY_BEGIN_FRAME)
3700                    .add_pass(graph, frame, display, present);
3701            }
3702        }
3703
3704        // --- the render-scale upscale ---
3705        //
3706        // **After the resolve, and that ordering is not interchangeable.**
3707        // Either tier filters the edges the renderer actually drew; run the
3708        // other way round
3709        // it would be filtering an interpolation of them, which is both more
3710        // expensive — the resolve would run at the target's extent rather than
3711        // the internal one — and worse, because the edge it is looking for has
3712        // already been spread across several target texels.
3713        //
3714        // The UI goes the other way and is composited onto `target` by the
3715        // caller after this, at native resolution. That is the whole reason a
3716        // render-scale knob is usable: the 3D frame gets cheap and the text does
3717        // not get soft.
3718        //
3719        // The `begin_frame` that opened this frame froze both extents and
3720        // built this where they differ — see [`View::frame_extent`].
3721        if present != target {
3722            self.upscale
3723                .as_mut()
3724                .expect(BUILT_BY_BEGIN_FRAME)
3725                .add_pass(graph, frame, present, target);
3726        }
3727
3728        tonemapped
3729    }
3730
3731    /// Releases every resource this view owns.
3732    ///
3733    /// The caller's to call once no frame in flight still names them — the
3734    /// same contract [`ForwardRenderer::destroy`] has, because these are the
3735    /// handles that frame's passes and groups bind.
3736    pub(super) fn destroy(self, device: &dyn Device) {
3737        for (_, group) in self.tonemap_groups.into_iter().flatten() {
3738            device.destroy_bind_group(group);
3739        }
3740        for buffer in self.tonemap_uniforms {
3741            device.destroy_buffer(buffer);
3742        }
3743        // The water and grass passes a frame built — see
3744        // [`View::build_content`].
3745        if let Some(grass) = self.grass {
3746            grass.destroy(device);
3747        }
3748        if let Some(water) = self.water {
3749            water.destroy(device);
3750        }
3751        self.sky_pass.destroy(device);
3752        // The settings-driven passes a frame built, and none that no frame
3753        // asked for — see [`View::build_passes`].
3754        if let Some(pass) = self.upscale {
3755            pass.destroy(device);
3756        }
3757        if let Some(pass) = self.cmaa2 {
3758            pass.destroy(device);
3759        }
3760        if let Some(pass) = self.fxaa {
3761            pass.destroy(device);
3762        }
3763        if let Some(pass) = self.bloom {
3764            pass.destroy(device);
3765        }
3766        self.auto_exposure.destroy(device);
3767        self.volumetric.destroy(device);
3768        self.ssr.destroy(device);
3769        if let Some(pass) = self.hiz {
3770            pass.destroy(device);
3771        }
3772        self.occlusion_pyramid.destroy(device);
3773        if let Some(pass) = self.contact_shadows {
3774            pass.destroy(device);
3775        }
3776        if let Some(pass) = self.ssao {
3777            pass.destroy(device);
3778        }
3779        for group in self
3780            .mesh_groups
3781            .into_iter()
3782            .chain(self.prepass_groups)
3783            .chain(
3784                self.screen_channel_groups
3785                    .into_iter()
3786                    .flatten()
3787                    .map(|(_, group)| group),
3788            )
3789        {
3790            device.destroy_bind_group(group);
3791        }
3792        for buffer in self.prepass_stats {
3793            device.destroy_buffer(buffer);
3794        }
3795        for buffer in self.uniforms {
3796            device.destroy_buffer(buffer);
3797        }
3798        for buffer in self.cluster_selection {
3799            device.destroy_buffer(buffer);
3800        }
3801        if let Some(buffer) = self.fixed_probes {
3802            device.destroy_buffer(buffer);
3803        }
3804        self.lights.destroy(device);
3805        self.draws.destroy(device);
3806    }
3807}
3808
3809/// # Views
3810///
3811/// `docs/plan/29-fp-rendering.md`'s second camera: a view draws the scene this
3812/// renderer already holds, through a camera of its own, into a target of its
3813/// own — and shares every pool, page, probe and shadow map with the primary
3814/// camera rather than building them again.
3815impl ForwardRenderer {
3816    /// Builds a view of this renderer's scene and hands back its id.
3817    ///
3818    /// **What a view costs** is one camera's share of the frame and nothing
3819    /// else: its own cull and draw-argument buffers (sized by the instance
3820    /// capacity, like the primary camera's), its frame blocks, its light
3821    /// clustering and the per-frame blocks of every screen-space pass. Geometry,
3822    /// materials, pages, probes and the shadow atlas are the scene's, and a
3823    /// view reads them where they already are.
3824    ///
3825    /// A view draws nothing until a frame begins it — see
3826    /// [`begin_view`](Self::begin_view) and
3827    /// [`add_passes_with_views`](Self::add_passes_with_views).
3828    ///
3829    /// # Errors
3830    ///
3831    /// [`HalError::InvalidDescriptor`] when [`MAX_VIEWS`] views already exist,
3832    /// or for a [`ViewBackground::Transparent`] view whose effects name one of
3833    /// [`ViewBackground::REFUSED_ON_TRANSPARENT`] — a filter that would blend
3834    /// its coverage edges with the empty background, see that variant — or
3835    /// for a `queue` that is not the device's graphics queue: the view's
3836    /// start-up fills are submitted to it and not waited for, on the build's
3837    /// terms. And whatever the device refuses while building one — in which
3838    /// case nothing of the view is left behind.
3839    pub fn create_view(
3840        &mut self,
3841        device: &dyn Device,
3842        queue: QueueHandle,
3843        desc: &ViewDesc,
3844    ) -> Result<ViewId, HalError> {
3845        crcbl_frame::require_frame_queue(device, queue, "a forward renderer's view")?;
3846        let refused = desc
3847            .effects
3848            .intersection(ViewBackground::REFUSED_ON_TRANSPARENT);
3849        if desc.background.is_transparent() && !refused.is_empty() {
3850            return Err(HalError::InvalidDescriptor(format!(
3851                "a transparent view cannot run {refused:?}: an antialiasing filter blends each \
3852                 edge pixel with the transparent black beside it, which a straight-alpha consumer \
3853                 draws as a dark fringe. Take them out of `ViewDesc::effects`, as \
3854                 `ViewDesc::transparent()` does"
3855            )));
3856        }
3857        let free = (0..MAX_VIEWS - 1)
3858            .find(|index| self.views.get(*index).is_none_or(Option::is_none))
3859            .ok_or_else(|| {
3860                HalError::InvalidDescriptor(format!(
3861                    "a forward renderer draws at most {MAX_VIEWS} views, the primary camera \
3862                     included, and every one is in use"
3863                ))
3864            })?;
3865        let id = ViewId(u8::try_from(free + 1).unwrap_or_else(|_| unreachable!("below MAX_VIEWS")));
3866        let probes: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3867            .map(|frame| self.probes.buffer(frame))
3868            .collect();
3869        let probe_visibility = self.probe_visibility_placeholder.view;
3870        // Its own batch, submitted before this returns: a view created after
3871        // the build has no build's batch to join, and the caller may draw it
3872        // on the next frame. Not waited for, on the build's batch's terms —
3873        // the next frame is on the same queue, after it — so a view made
3874        // between frames no longer drains the device.
3875        let mut uploads = UploadBatch::new(device, queue, "view");
3876        // `create_view` takes no service, so its batch runs none.
3877        let pipelines = ViewPipelines::new(device, &mut || {})?;
3878        let view = View::build(
3879            device,
3880            &mut uploads,
3881            &ViewInputs {
3882                id,
3883                effects: desc.effects,
3884                // What the last frame drew, through this view's own mask: the
3885                // best guess at what its first frame will.
3886                expected: View::drawn_effects(self.frame_effects, desc.effects, desc.lighting),
3887                // Below full scale a view that is not transparent is drawn
3888                // below its target, whatever extent that target turns out to
3889                // be — see `view_extent`.
3890                expected_upscale: self.render_scale < 1.0 && !desc.background.is_transparent(),
3891                background: desc.background,
3892                lighting: desc.lighting,
3893                target_format: self.target_format,
3894                emit: self.emit,
3895                instances: self.instances.buffers(),
3896                mesh_table: self.pool.table_buffer(),
3897                // The renderer's set, not a new one: a view builds buffers and
3898                // groups for its cull and compiles nothing for it.
3899                draw_pipelines: &self.draw_pipelines,
3900                bucket_meshes: &self.draw_tables.bucket_meshes,
3901                bucket_modes: &self.bucket_modes,
3902                bucket_clusters: &self.draw_tables.bucket_clusters,
3903                bucket_cluster_bases: &self.draw_tables.bucket_cluster_bases,
3904                mesh_levels: &self.draw_tables.mesh_levels,
3905                level_groups: &self.draw_tables.level_groups,
3906                level_meshes: &self.draw_tables.level_meshes,
3907                instance_capacity: self.draw_tables.instance_capacity,
3908                light_capacity: self.draw_tables.light_capacity,
3909                clusters: self.clusters.as_ref(),
3910                task_lanes: task_lanes(self.culls_clusters),
3911                mesh_layout: self.mesh_layout,
3912                vertices: self.pool.vertex_buffer(),
3913                draw_constants: self.draw_constants,
3914                materials: self.materials.buffer(),
3915                // What each slot's groups name today, so a view built while a
3916                // new anisotropy or a replaced page is still moving through the
3917                // ring is adopted on the same frames the primary camera's
3918                // groups are.
3919                pages: &self.slot_pages,
3920                probes: &probes,
3921                specular_dfg: self.specular_dfg.view,
3922                ltc_table: self.ltc_table.view,
3923                sky_prefilter: self.sky_prefilter.view,
3924                shadow_map: self.shadow_atlas_view,
3925                shadow_sampler: self.shadow_sampler,
3926                ambient_occlusion: self.ambient_occlusion_placeholder.view,
3927                contact_shadow: self.contact_shadow_placeholder.view,
3928                probe_visibility,
3929            },
3930            pipelines,
3931            &mut || {},
3932        )?;
3933        // The last fallible step: a failed submit leaves nothing pending.
3934        match uploads.submit_deferred() {
3935            Ok(pending) => self.uploads_in_flight.push(pending),
3936            Err(error) => {
3937                view.destroy(device);
3938                return Err(error);
3939            }
3940        }
3941        if self.views.len() <= free {
3942            self.views.resize_with(free + 1, || None);
3943        }
3944        self.views[free] = Some(view);
3945        Ok(id)
3946    }
3947
3948    /// Releases `view` and hands its id back.
3949    ///
3950    /// **Every instance is drawn in the view the id names next**: the bit this
3951    /// view hid instances with is cleared from every record, so a view created
3952    /// later under the same id starts from [`ViewMask::ALL`] rather than from
3953    /// what a view it never was had hidden.
3954    ///
3955    /// Like [`destroy`](Self::destroy), the caller's to call once no frame in
3956    /// flight still names the view's buffers and groups. Any start-up upload
3957    /// not yet retired is waited for first — a view destroyed before a frame
3958    /// has run past its own fills would otherwise release what they write.
3959    ///
3960    /// # Panics
3961    ///
3962    /// If `view` is [`ViewId::PRIMARY`], which lives as long as the renderer,
3963    /// or names no view this renderer built.
3964    pub fn destroy_view(&mut self, device: &dyn Device, view: ViewId) {
3965        assert!(
3966            view != ViewId::PRIMARY,
3967            "the primary camera is released with the renderer, not on its own"
3968        );
3969        let built = self
3970            .views
3971            .get_mut(view.index() - 1)
3972            .and_then(Option::take)
3973            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"));
3974        // Every pending upload rather than this view's alone: the list does
3975        // not say whose each is, and once frames have run past them it is
3976        // usually empty.
3977        self.wait_for_uploads(device, "destroy_view");
3978        built.destroy(device);
3979        self.instances.clear_flags(view.hidden_bit());
3980    }
3981
3982    /// Writes `view`'s blocks for this frame, drawn through `camera` into a
3983    /// target of `extent`.
3984    ///
3985    /// **After [`begin_frame`](Self::begin_frame), in the same frame**, which is
3986    /// what rotated the instance ring, skinned what moves and fitted the shadow
3987    /// maps: a view writes into the slot that call chose, lit by the sun it was
3988    /// handed and shadowed through the maps the primary camera's frame draws —
3989    /// unless its [`ViewDesc::lighting`] fixes a light of its own. A view begun and then not named in
3990    /// [`add_passes_with_views`](Self::add_passes_with_views) records nothing.
3991    ///
3992    /// # Errors
3993    ///
3994    /// [`HalError`] if one of the view's blocks could not be written.
3995    ///
3996    /// # Panics
3997    ///
3998    /// If `view` is [`ViewId::PRIMARY`] — its blocks are `begin_frame`'s — or
3999    /// names no view this renderer built, or if no frame has begun.
4000    pub fn begin_view(
4001        &mut self,
4002        device: &dyn Device,
4003        view: ViewId,
4004        camera: &Camera,
4005        extent: (u32, u32),
4006    ) -> Result<(), HalError> {
4007        assert!(
4008            view != ViewId::PRIMARY,
4009            "the primary camera's blocks are written by `begin_frame`"
4010        );
4011        let background = self
4012            .views
4013            .get(view.index() - 1)
4014            .and_then(Option::as_ref)
4015            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"))
4016            .background;
4017        let scene = self
4018            .frame_scene
4019            .take()
4020            .expect("`begin_view` follows the `begin_frame` that opened the frame");
4021        let mut frame = self.view_frame(&scene, extent, self.instances.slot_count(), camera.eye);
4022        frame.extent = self.view_extent(background, extent);
4023        let written = self
4024            .views
4025            .get_mut(view.index() - 1)
4026            .and_then(Option::as_mut)
4027            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"))
4028            .begin_frame(device, camera, &frame, self.sky_view.as_ref());
4029        self.frame_scene = Some(scene);
4030        written.map(|_| ())
4031    }
4032
4033    /// Sets the views `handle` is drawn in. Every instance starts in
4034    /// [`ViewMask::ALL`].
4035    ///
4036    /// **A camera's cull and nothing else**: a view the instance is hidden from
4037    /// rejects it before testing a bound, and every shadow map still draws it —
4038    /// so a weapon hidden from a scope's view goes on casting the shadow the
4039    /// primary camera sees.
4040    ///
4041    /// Not a move: the record's transform history is left as it is, so a
4042    /// visibility change does not report motion. A stale handle is ignored, on
4043    /// [`set_instance`](Self::set_instance)'s terms.
4044    pub fn set_instance_views(&mut self, handle: InstanceHandle, views: ViewMask) {
4045        if let Some(record) = self.instances.get(handle) {
4046            let flags =
4047                (record.flags & !mesh::GpuInstance::HIDDEN_VIEWS_MASK) | views.hidden_bits();
4048            self.instances.set_flags(handle, flags);
4049        }
4050    }
4051
4052    /// The views `handle` is drawn in, or `None` for a stale handle.
4053    #[must_use]
4054    pub fn instance_views(&self, handle: InstanceHandle) -> Option<ViewMask> {
4055        self.instances
4056            .get(handle)
4057            .map(|record| ViewMask::from_flags(record.flags))
4058    }
4059
4060    /// `view`'s draw generator — [`draws`](Self::draws) for a view other than
4061    /// the primary camera.
4062    ///
4063    /// # Panics
4064    ///
4065    /// If `view` names no view this renderer built.
4066    #[must_use]
4067    pub fn view_draws(&self, view: ViewId) -> &DrawGen {
4068        if view == ViewId::PRIMARY {
4069            return &self.primary.draws;
4070        }
4071        &self
4072            .views
4073            .get(view.index() - 1)
4074            .and_then(Option::as_ref)
4075            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"))
4076            .draws
4077    }
4078
4079    /// The target's aspect and the internal extent a frame into `target` is
4080    /// drawn at.
4081    ///
4082    /// **The aspect is the target's and the extent is the internal render
4083    /// extent's.** What a viewer sees is the target: the upscale maps the whole
4084    /// internal image onto the whole of it, so a frame composed for the internal
4085    /// extent's own aspect would be composed for a rectangle nobody looks at.
4086    /// What the rounding of the two extents leaves is a sub-pixel
4087    /// non-squareness in the internal target, which the upscale undoes on the
4088    /// way out.
4089    ///
4090    /// A minimised window reports a zero extent in *either* dimension, and
4091    /// `Projection::matrix` asserts a finite positive aspect. Guarding only the
4092    /// height left `extent.0 == 0` producing `0.0`, which trips that assert and
4093    /// takes the frame loop down with it.
4094    ///
4095    /// The extent is the one a frame is *drawn* at, which is the caller's at a
4096    /// render scale of `1.0` and smaller below it. Every use of it sizes
4097    /// something — the cluster grid, the LOD metric's pixel budget, the Hi-Z
4098    /// pyramid's height, the bloom chain, the resolve's texel size — and every
4099    /// one of those wants the extent the pixels are actually at. See
4100    /// [`Self::set_render_scale`] — and taken at the scale the frame's
4101    /// `begin_frame` froze, [`Self::frame_render_scale`], so a view begun after
4102    /// a scale moved is drawn at the frame's scale and not the next one's.
4103    pub(super) fn frame_extents(&self, target: (u32, u32)) -> (f32, (u32, u32)) {
4104        let aspect = if target.0 == 0 || target.1 == 0 {
4105            1.0
4106        } else {
4107            target.0 as f32 / target.1 as f32
4108        };
4109        (aspect, Self::scaled_extent(self.frame_render_scale, target))
4110    }
4111
4112    /// The internal extent a secondary view with `background` is drawn at, for
4113    /// a target of `target`: [`frame_extents`](Self::frame_extents)' answer,
4114    /// except that a [`ViewBackground::Transparent`] view is always drawn at
4115    /// its target's own extent — the upscale would filter its coverage edges,
4116    /// see that variant.
4117    pub(super) fn view_extent(&self, background: ViewBackground, target: (u32, u32)) -> (u32, u32) {
4118        if background.is_transparent() {
4119            target
4120        } else {
4121            self.frame_extents(target).1
4122        }
4123    }
4124
4125    /// What every view's [`View::begin_frame`] reads of this frame, for a view
4126    /// drawn into a target of `target_extent`.
4127    pub(super) fn view_frame<'s>(
4128        &self,
4129        scene: &'s FrameScene,
4130        target_extent: (u32, u32),
4131        instance_count: u32,
4132        selection_eye: Vec3,
4133    ) -> ViewFrame<'s> {
4134        let (aspect, extent) = self.frame_extents(target_extent);
4135        // The frame's gradient, resolved once and handed to all three of the
4136        // things that want a sky: the L1 projection below for the ambient term,
4137        // the march's block for a reflection that hit nothing, and the pass that
4138        // draws the background. One `SkyGradient` rather than three readings of
4139        // the field, so the sky a surface is lit by cannot differ from the one
4140        // behind it.
4141        //
4142        // An atmosphere replaces the gradient outright — see `set_atmosphere`.
4143        // `gradient_fit` is what the reflection pass and the background's own
4144        // gradient rows take, `irradiance` is the ambient term, and the LUT
4145        // itself is what the background samples. The first two are taken when
4146        // a march finishes rather than here — see `PresentedSky` — so a frame
4147        // whose sun has not moved reads them.
4148        let sky_view = self.sky_view.as_ref();
4149        let gradient = match sky_view {
4150            Some(presented) => presented.gradient,
4151            None => self.sky.gradient(),
4152        };
4153        // Projected on the host — once per gradient, and for an atmosphere once
4154        // per completed march rather than once per frame — which is also why
4155        // the shading rule that governs `mesh.slang` has nothing to say about
4156        // it: these coefficients reach every backend as uploaded numbers.
4157        let sky_irradiance = match sky_view {
4158            Some(presented) => presented.irradiance,
4159            None => gradient.irradiance(),
4160        };
4161        ViewFrame {
4162            slot: self.frame,
4163            serial: self.frame_serial,
4164            aspect,
4165            extent,
4166            target_extent,
4167            effects: self.frame_effects,
4168            instance_count,
4169            selection_eye,
4170            lod_error_budget: self.lod_error_budget,
4171            lod_hold_ratio: self.lod_hold_ratio,
4172            scene,
4173            // Whether this frame's slot has water, as `begin_frame` uploaded it
4174            // before any view began — the value `add_passes` records from.
4175            water: self.water.has_water(self.frame),
4176            // The field as `begin_frame` froze it, and the weather over it.
4177            // Read here rather than in `View::begin_frame` because that method
4178            // takes `&mut self` on the view and the field is the *renderer's*.
4179            grass: self.frame_grass,
4180            wind: self.wind,
4181            fog: self.fog,
4182            probe_volume: self.probe_volume,
4183            attribute_base: self.pool.attribute_base(),
4184            gradient,
4185            sky_irradiance,
4186            debug_view_lane: self.debug_view_lane(),
4187            exposure: self.exposure,
4188            exposure_adaptation: self.exposure_adaptation,
4189            tonemap_curve: self.resolved_tonemap_curve(),
4190            occlusion: self.resolved_occlusion_culling(),
4191        }
4192    }
4193}
4194
4195// Uses `forward::tests`' fixtures, which are native-only with them.
4196#[cfg(all(test, not(target_arch = "wasm32")))]
4197mod tests;