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